Skip to content

Commit 63a8310

Browse files
authored
fix(tools): improve json parsing (#1356)
* fix(tools): improve json parsing * lint
1 parent 88a904b commit 63a8310

File tree

2 files changed

+57
-29
lines changed

2 files changed

+57
-29
lines changed

src/lib/server/textGeneration/tools.ts

Lines changed: 18 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import { ToolResultStatus, type ToolCall, type ToolResult } from "$lib/types/Tool";
22
import { v4 as uuidV4 } from "uuid";
3-
import JSON5 from "json5";
43
import type { BackendTool, BackendToolContext } from "../tools";
54
import {
65
MessageToolUpdateType,
@@ -15,7 +14,7 @@ import directlyAnswer from "../tools/directlyAnswer";
1514
import websearch from "../tools/web/search";
1615
import { z } from "zod";
1716
import { logger } from "../logger";
18-
import { toolHasName } from "../tools/utils";
17+
import { extractJson, toolHasName } from "../tools/utils";
1918
import type { MessageFile } from "$lib/types/Message";
2019
import { mergeAsyncGenerators } from "$lib/utils/mergeAsyncGenerators";
2120
import { MetricsServer } from "../metrics";
@@ -143,33 +142,23 @@ export async function* runTools(
143142
// look for a code blocks of ```json and parse them
144143
// if they're valid json, add them to the calls array
145144
if (output.generated_text) {
146-
if (!output.generated_text.endsWith("```")) {
147-
output.generated_text = output.generated_text + "```";
148-
}
149-
const codeBlocks = Array.from(output.generated_text.matchAll(/```json\n(.*?)```/gs))
150-
.map(([, block]) => block)
151-
// remove trailing comma
152-
.map((block) => block.trim().replace(/,$/, ""));
153-
if (codeBlocks.length === 0) continue;
154-
// grab only the capture group from the regex match
155-
for (const block of codeBlocks) {
156-
// make it an array if it's not already
157-
let call = JSON5.parse(block);
158-
if (!Array.isArray(call)) {
159-
call = [call];
160-
}
161-
162-
try {
163-
calls.push(...call.filter(isExternalToolCall).map(externalToToolCall).filter(Boolean));
164-
} catch (e) {
165-
logger.error(e, "Error while parsing tool calls, please retry");
166-
// error parsing the calls
167-
yield {
168-
type: MessageUpdateType.Status,
169-
status: MessageUpdateStatus.Error,
170-
message: "Error while parsing tool calls, please retry",
171-
};
172-
}
145+
logger.info(output.generated_text);
146+
try {
147+
const rawCalls = await extractJson(output.generated_text);
148+
const newCalls = rawCalls
149+
.filter(isExternalToolCall)
150+
.map(externalToToolCall)
151+
.filter((call) => call !== undefined) as ToolCall[];
152+
153+
calls.push(...newCalls);
154+
} catch (e) {
155+
logger.error(e, "Error while parsing tool calls, please retry");
156+
// error parsing the calls
157+
yield {
158+
type: MessageUpdateType.Status,
159+
status: MessageUpdateStatus.Error,
160+
message: "Error while parsing tool calls, please retry",
161+
};
173162
}
174163
}
175164
}

src/lib/server/tools/utils.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { env } from "$env/dynamic/private";
22
import { Client } from "@gradio/client";
33
import { SignJWT } from "jose";
4+
import JSON5 from "json5";
45

56
export type GradioImage = {
67
path: string;
@@ -52,3 +53,41 @@ export async function getIpToken(ip: string, username?: string) {
5253
}
5354

5455
export { toolHasName } from "$lib/utils/tools";
56+
57+
export async function extractJson(text: string): Promise<unknown[]> {
58+
const calls: string[] = [];
59+
60+
let codeBlocks = Array.from(text.matchAll(/```json\n(.*?)```/gs))
61+
.map(([, block]) => block)
62+
// remove trailing comma
63+
.map((block) => block.trim().replace(/,$/, ""));
64+
65+
// if there is no code block, try to find the first json object
66+
// by trimming the string and trying to parse with JSON5
67+
if (codeBlocks.length === 0) {
68+
const start = [text.indexOf("["), text.indexOf("{")]
69+
.filter((i) => i !== -1)
70+
.reduce((a, b) => Math.max(a, b), -Infinity);
71+
const end = [text.lastIndexOf("]"), text.lastIndexOf("}")]
72+
.filter((i) => i !== -1)
73+
.reduce((a, b) => Math.min(a, b), Infinity);
74+
75+
if (start === -Infinity || end === Infinity) {
76+
return [""];
77+
}
78+
79+
const json = text.substring(start, end + 1);
80+
codeBlocks = [json];
81+
}
82+
83+
// grab only the capture group from the regex match
84+
for (const block of codeBlocks) {
85+
// make it an array if it's not already
86+
let call = JSON5.parse(block);
87+
if (!Array.isArray(call)) {
88+
call = [call];
89+
}
90+
calls.push(call);
91+
}
92+
return calls.flat();
93+
}

0 commit comments

Comments
 (0)