File size: 8,368 Bytes
0d6f04b
 
6b8f69a
 
 
 
 
 
 
 
 
 
 
0d6f04b
 
 
 
 
 
 
 
f665131
 
 
 
 
 
 
0d6f04b
 
 
f665131
 
 
0d6f04b
 
 
 
 
 
63d0776
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d7d435
 
 
 
63d0776
 
 
 
 
5d7d435
 
 
 
 
 
 
63d0776
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d7d435
3a22cf3
 
 
 
 
5d7d435
63d0776
3a22cf3
 
0d6f04b
 
 
 
3a22cf3
 
5d7d435
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import { MessageBase } from './types';
import { CLEANED_SEPARATOR } from './constants';

const PAIRS: Record<string, string> = {
  '┍': 'β”‘',
  '┝': 'β”₯',
  'β”œ': '─',
  'β”•': 'β”™',
};

const MIDDLE_STARTER = '┝';
const MIDDLE_SEPARATOR = 'β”Ώ';

const ANSWERS_PREFIX = 'answers';
const INPUT_PREFIX = 'input';

export const generateAnswersImageMarkdown = (index: number, url: string) => {
  return `![${ANSWERS_PREFIX}-${index}](${url})`;
};

export const generateInputImageMarkdown = (url: string, index = 0) => {
  if (url.toLowerCase().endsWith('.mp4')) {
    const prefix = 'input-video';
    return `![${INPUT_PREFIX}-${index}](<${url}>)`;
  } else {
    const prefix = 'input';
    return `![${INPUT_PREFIX}-${index}](<${url}>)`;
  }
};

export const cleanInputMessage = (content: string) => {
  return content
    .replace(/!\[input-.*?\)/g, '')
    .replace(/<video[^>]*>.*?<\/video>/g, '');
};

export const cleanAnswerMessage = (content: string) => {
  return content.replace(/!\[answers.*?\.png\)/g, '');
};

const generateJSONArrayMarkdown = (
  message: string,
  payload: Array<Record<string, string | boolean>>,
) => {
  if (payload.length === 0) return '';
  const keys = Object.keys(payload[0]);
  message += '\n';
  message += '| ' + keys.join(' | ') + ' |' + '\n';
  message += new Array(keys.length + 1).fill('|').join(' :- ') + '\n';
  payload.forEach((obj: any) => {
    message +=
      '| ' +
      keys
        .map(key => {
          if (key === 'documentation') {
            const doc = `\`\`\`\n${obj[key]}\n\`\`\`\n`;
            return `<button data-details=${JSON.stringify(encodeURI(doc))}>Show</button>`;
          } else {
            return obj[key];
          }
        })
        .join(' | ') +
      ' |' +
      '\n';
  });
  message += '\n';
  return message;
};

const generateStringArrayMarkdown = (
  message: string,
  header: string,
  payload: Array<string>,
) => {
  message += '\n';
  message += '| ' + header + ' |' + '\n';
  message += '| ' + ':-' + ' |' + '\n';
  payload.forEach((tool: string) => {
    message += '| ' + tool + ' |' + '\n';
  });
  message += '\n';
  return message;
};

const generateCodeExecutionMarkdown = (
  message: string,
  payload: {
    code: string;
    test: string;
    result?: string;
  },
) => {
  let Details = 'Code: \n';
  Details += `\`\`\`python\n${payload.code}\n\`\`\`\n`;
  Details += 'Test: \n';
  Details += `\`\`\`python\n${payload.test}\n\`\`\`\n`;
  if (payload.result) {
    Details += 'Execution result: \n';
    Details += `\`\`\`python\n${payload.result}\n\`\`\`\n`;
  }
  message += `<button data-details=${JSON.stringify(encodeURI(Details))}>View details</button> \n`;

  return message;
};

const generateFinalCodeMarkdown = (
  message: string,
  payload: {
    code: string;
    test: string;
    result: string;
  },
) => {
  message += 'Final Code: \n';
  message += `\`\`\`python\n${payload.code}\n\`\`\`\n`;
  message += 'Final test: \n';
  message += `\`\`\`python\n${payload.test}\n\`\`\`\n`;
  message += `Final result: \n`;
  message += `\`\`\`\n${payload.result}\n\`\`\`\n`;
  return message;
};

const generateFinalResultMarkdown = (
  message: string,
  payload: {
    success: boolean;
    reach_max_retries: boolean;
  },
) => {
  if (payload.reach_max_retries) {
    message += 'Reach max debug retries!\n';
  } else if (payload.success) {
    message += 'Success!';
  }
  message += '\n';
  return message;
};

type PlansBody =
  | {
      type: 'plans';
      status: 'started';
    }
  | {
      type: 'plans';
      status: 'completed';
      payload: Array<Record<string, string>>;
    };

type ToolsBody =
  | {
      type: 'tools';
      status: 'started';
    }
  | {
      type: 'tools';
      status: 'completed';
      payload: Array<Record<string, string>>;
    };

type CodeBody =
  | {
      type: 'code';
      status: 'started';
    }
  | {
      type: 'code';
      status: 'running';
      payload: {
        code: string;
        test: string;
      };
    }
  | {
      type: 'code';
      status: 'completed' | 'failed';
      payload: {
        code: string;
        test: string;
        result: string;
      };
    };

type FinalCodeBody = {
  type: 'final_code';
  status: 'completed' | 'failed';
  payload: {
    code: string;
    test: string;
    result: string;
  };
};

// this will return if self_reflection flag is true
type ReflectionBody =
  | {
      type: 'self_reflection';
      status: 'started';
    }
  | {
      type: 'self_reflection';
      status: 'completed' | 'failed';
      payload: { feedback: string; success: boolean };
    };

type MessageBody =
  | PlansBody
  | ToolsBody
  | CodeBody
  | ReflectionBody
  | FinalCodeBody;

const getMessageTitle = (json: MessageBody) => {
  switch (json.type) {
    case 'plans':
      if (json.status === 'started') {
        return '🎬 Start generating plans...\n';
      } else {
        return 'βœ… Going to run the following plan(s) in sequence:\n';
      }
    case 'tools':
      if (json.status === 'started') {
        return '🎬 Start retrieving tools...\n';
      } else {
        return 'βœ… Tools retrieved:\n';
      }
    case 'code':
      if (json.status === 'started') {
        return '🎬 Start generating code...\n';
      } else if (json.status === 'running') {
        return '🎬 Code generated, start execution... ';
      } else if (json.status === 'completed') {
        return 'βœ… Code executed successfully. ';
      } else {
        return '❌ Code execution failed. ';
      }
    case 'self_reflection':
      if (json.status === 'started') {
        return '🎬 Start self reflection...\n';
      } else if (json.status === 'completed') {
        return 'βœ… Self reflection completed: \n';
      } else {
        return '❌ Self reflection failed: \n';
      }
    case 'final_code':
      if (json.status === 'completed') {
        return 'βœ… The vision agent has concluded the chat, the last execution is successful. \n';
      } else {
        return '❌ he vision agent has concluded the chat, the last execution is failed. \n';
      }
    default:
      throw 'Not supported type';
  }
};
const parseLine = (json: MessageBody) => {
  const title = getMessageTitle(json);
  if (json.status === 'started') {
    return title;
  }
  switch (json.type) {
    case 'plans':
      return generateJSONArrayMarkdown(title, json.payload);
    case 'tools':
      return generateJSONArrayMarkdown(title, json.payload);
    case 'code':
      return generateCodeExecutionMarkdown(title, json.payload);
    case 'self_reflection':
      return generateJSONArrayMarkdown(title, [json.payload]);
    case 'final_code':
      return generateFinalCodeMarkdown(title, json.payload);
    default:
      throw 'Not supported type';
  }
};

export const getCleanedUpMessages = ({
  content,
  role,
}: Pick<MessageBase, 'role' | 'content'>) => {
  if (role === 'user') {
    return {
      logs: content,
    };
  }
  if (content.split(CLEANED_SEPARATOR).length === 2) {
    return {
      logs: content.split(CLEANED_SEPARATOR)[0],
      content: content.split(CLEANED_SEPARATOR)[1],
    };
  }
  const [logs = '', answer = ''] = content.split('<ANSWER>');
  const lines = logs.split('\n');
  let formattedLogs = '';
  const jsons: MessageBody[] = [];
  for (let line of lines) {
    if (!line.trim()) {
      continue;
    }
    try {
      const json = JSON.parse(line) as MessageBody;
      if (
        jsons.length > 0 &&
        json.type === jsons[jsons.length - 1].type &&
        json.status !== 'started'
      ) {
        jsons[jsons.length - 1] = json;
      } else {
        jsons.push(json);
      }
    } catch (e) {
      console.error((e as Error).message);
      console.error(line);
    }
  }
  jsons.forEach(json => (formattedLogs += parseLine(json)));
  const [answerText, imagesStr = ''] = answer.split('<VIZ>');
  const [imagesArrayStr, ...rest] = imagesStr.split('</VIZ>');
  const images = imagesArrayStr
    .split('</IMG>')
    .map(str => str.replace('<IMG>', ''))
    .slice(0, -1);
  return {
    logs: formattedLogs,
    content:
      answerText.replace('</</ANSWER>', '').replace('</ANSWER>', '') +
      '\n\n' +
      images
        .map((_, index) => generateAnswersImageMarkdown(index, '/loading.gif'))
        .join('') +
      rest.join(''),
    images: images,
  };
};