-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathparseResponse.ts
62 lines (58 loc) · 1.64 KB
/
parseResponse.ts
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
import { toolSchemaUnion, type ToolOperation } from "./tools";
import { fromError } from "zod-validation-error";
export type Action = {
thought: string;
speak?: string;
operation: ToolOperation;
};
// sometimes AI replies with a JSON wrapped in triple backticks
export function extractJsonFromMarkdown(input: string): string[] {
// Create a regular expression to capture code wrapped in triple backticks
const regex = /```(json)?\s*([\s\S]*?)\s*```/g;
const results = [];
let match;
while ((match = regex.exec(input)) !== null) {
// If 'json' is specified, add the content to the results array
if (match[1] === "json") {
results.push(match[2]);
} else if (match[2].startsWith("{")) {
results.push(match[2]);
}
}
return results;
}
export function parseResponse(rawResponse: string): Action {
let response;
try {
response = JSON.parse(rawResponse);
} catch (_e) {
try {
response = JSON.parse(extractJsonFromMarkdown(rawResponse)[0]);
} catch (_e) {
throw new Error("Response does not contain valid JSON.");
}
}
if (response.thought == null || response.action == null) {
throw new Error("Invalid response: Thought and Action are required");
}
let operation;
try {
operation = toolSchemaUnion.parse(response.action);
} catch (err) {
const validationError = fromError(err);
// user friendly error message
throw new Error(validationError.toString());
}
if ("speak" in response) {
return {
thought: response.thought,
speak: response.speak,
operation,
};
} else {
return {
thought: response.thought,
operation,
};
}
}