MCPcopy Create free account
hub / github.com/Superflows-AI/superflows / parseDataAnalysisResponse

Function parseDataAnalysisResponse

lib/parsers/dataAnalysis.ts:1–69  ·  view source on GitHub ↗
(
  response: string,
  userDefinedVariables: string[] = [],
)

Source from the content-addressed store, hash-verified

1export function parseDataAnalysisResponse(
2 response: string,
3 userDefinedVariables: string[] = [],
4): { code: string } | { error: string } | null {
5 /** Parses the response from the LLM in data analysis mode. Returns the code **/
6 const codeRegex =
7 /\n```(javascript|typescript|js|ts)?\n([\w\W]+?)\n```/g.exec(response);
8 if (!codeRegex) {
9 console.error("No code block found in:\n---\n" + response + "\n---");
10 return null;
11 }
12 const rawCode = codeRegex[2];
13
14 // Automated output checks below
15
16 // Check if it's just an error
17 const errorMatch = /^\n?throw new Error\((.*)\);?$/.exec(rawCode);
18 if (errorMatch) {
19 console.error(`Error message from generated code: ${errorMatch[1]}`);
20 // slice(1, -1) removes the quotes from the error message
21 return { error: errorMatch[1].slice(1, -1) };
22 }
23 // Remove comments (stops false positives from comments containing illegal stuff) & convert from TS to JS
24 const code = stripBasicTypescriptTypes(rawCode.replace(/\/\/.*/g, ""));
25
26 // Check that fetch(), eval(), new Function() and WebAssembly aren't used
27 const illegalRegexes = [
28 /fetch\([\w\W]\)/,
29 /eval\([\w\W]\)/,
30 /new Function\([\w\W]\)/,
31 /WebAssembly\./,
32 ];
33 for (const regex of illegalRegexes) {
34 if (regex.test(code)) {
35 console.error(
36 `Illegal code found by ${String(regex)}:\n---\n${code}\n---`,
37 );
38 return null;
39 }
40 }
41
42 // Check expected variable is defined
43 const expectedVarName = [/var graphData/, /let graphData/, /const graphData/];
44 const expectedVarFound = expectedVarName.some((regex) => regex.test(code));
45 if (!expectedVarFound) {
46 console.error(
47 `Expected variable 'graphData' not found:\n---\n${code}\n---`,
48 );
49 return null;
50 }
51
52 // Check that the userDefined variables haven't been redefined
53 const userDefinedVarNameRegexes = userDefinedVariables
54 .map((v) => [
55 new RegExp(`var ${v}`),
56 new RegExp(`let ${v}`),
57 new RegExp(`const ${v}`),
58 ])
59 .flat();
60 const userDefinedVarFound = userDefinedVarNameRegexes.some((regex) =>

Callers 2

runDataAnalysisFunction · 0.90

Calls 1

Tested by

no test coverage detected