From dcdc04f0bad2ef212f21390c71ef20166dd9a602 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 4 Jun 2025 15:16:41 -0700 Subject: [PATCH] JSON parsing progress --- .../providers/GoogleContextProvider.ts | 42 +++++++++++-------- .../providers/GreptileContextProvider.ts | 18 ++++---- core/core.ts | 2 +- core/llm/llms/Anthropic.ts | 3 +- core/llm/llms/Bedrock.ts | 3 +- core/llm/llms/BedrockImport.ts | 12 ++++-- core/llm/llms/Gemini.ts | 5 ++- core/llm/openaiTypeConverters.ts | 17 +++----- core/tools/callTool.ts | 7 ++-- core/tools/parseArgs.ts | 26 ++++++++++++ gui/src/redux/thunks/callCurrentTool.ts | 2 +- gui/src/util/clientTools/callClientTool.ts | 8 ++-- gui/src/util/toolCallState.ts | 3 +- packages/fetch/src/stream.ts | 8 +++- .../openai-adapters/src/apis/Anthropic.ts | 6 ++- packages/openai-adapters/src/apis/Gemini.ts | 6 ++- .../openai-adapters/src/util/parseArgs.ts | 15 +++++++ 17 files changed, 126 insertions(+), 57 deletions(-) create mode 100644 core/tools/parseArgs.ts create mode 100644 packages/openai-adapters/src/util/parseArgs.ts diff --git a/core/context/providers/GoogleContextProvider.ts b/core/context/providers/GoogleContextProvider.ts index fb8a04d40..b27b9f565 100644 --- a/core/context/providers/GoogleContextProvider.ts +++ b/core/context/providers/GoogleContextProvider.ts @@ -38,27 +38,35 @@ class GoogleContextProvider extends BaseContextProvider { body: payload, }); + if (!response.ok) { + throw new Error( + `Failed to fetch Google search results: ${response.statusText}`, + ); + } const results = await response.text(); + try { + const parsed = JSON.parse(results); + let content = `Google Search: ${query}\n\n`; + const answerBox = parsed.answerBox; - const jsonResults = JSON.parse(results); - let content = `Google Search: ${query}\n\n`; - const answerBox = jsonResults.answerBox; + if (answerBox) { + content += `Answer Box (${answerBox.title}): ${answerBox.answer}\n\n`; + } - if (answerBox) { - content += `Answer Box (${answerBox.title}): ${answerBox.answer}\n\n`; + for (const result of parsed.organic) { + content += `${result.title}\n${result.link}\n${result.snippet}\n\n`; + } + + return [ + { + content, + name: "Google Search", + description: "Google Search", + }, + ]; + } catch (e) { + throw new Error(`Failed to parse Google search results: ${results}`); } - - for (const result of jsonResults.organic) { - content += `${result.title}\n${result.link}\n${result.snippet}\n\n`; - } - - return [ - { - content, - name: "Google Search", - description: "Google Search", - }, - ]; } } diff --git a/core/context/providers/GreptileContextProvider.ts b/core/context/providers/GreptileContextProvider.ts index a13e4376f..23a730bc9 100644 --- a/core/context/providers/GreptileContextProvider.ts +++ b/core/context/providers/GreptileContextProvider.ts @@ -81,13 +81,17 @@ class GreptileContextProvider extends BaseContextProvider { } // Parse the response as JSON - const json = JSON.parse(rawText); - - return json.sources.map((source: any) => ({ - description: source.filepath, - content: `File: ${source.filepath}\nLines: ${source.linestart}-${source.lineend}\n\n${source.summary}`, - name: (source.filepath.split("/").pop() ?? "").split("\\").pop() ?? "", - })); + try { + const json = JSON.parse(rawText); + return json.sources.map((source: any) => ({ + description: source.filepath, + content: `File: ${source.filepath}\nLines: ${source.linestart}-${source.lineend}\n\n${source.summary}`, + name: + (source.filepath.split("/").pop() ?? "").split("\\").pop() ?? "", + })); + } catch (jsonError) { + throw new Error(`Failed to parse Greptile response:\n${rawText}`); + } } catch (error) { console.error("Error getting context items from Greptile:", error); throw new Error("Error getting context items from Greptile"); diff --git a/core/core.ts b/core/core.ts index aae912b11..dbec07062 100644 --- a/core/core.ts +++ b/core/core.ts @@ -699,7 +699,7 @@ export class Core { this.messenger.send("toolCallPartialOutput", params); }; - return await callTool(tool, toolCall.function.arguments, { + return await callTool(tool, toolCall, { config, ide: this.ide, llm: config.selectedModelByRole.chat, diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index b5906590a..8d1d3a67f 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -1,5 +1,6 @@ import { streamSse } from "@continuedev/fetch"; import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; +import { safeParseToolCallArgs } from "../../tools/parseArgs.js"; import { renderChatMessage, stripImages } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; @@ -66,7 +67,7 @@ class Anthropic extends BaseLLM { type: "tool_use", id: toolCall.id, name: toolCall.function?.name, - input: JSON.parse(toolCall.function?.arguments || "{}"), + input: safeParseToolCallArgs(toolCall), })), }; } else if (message.role === "thinking" && !message.redactedThinking) { diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 83b9a98c1..b39113aaf 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -15,6 +15,7 @@ import { CompletionOptions, LLMOptions, } from "../../index.js"; +import { safeParseToolCallArgs } from "../../tools/parseArgs.js"; import { renderChatMessage, stripImages } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { PROVIDER_TOOL_SUPPORT } from "../toolSupport.js"; @@ -408,7 +409,7 @@ class Bedrock extends BaseLLM { toolUse: { toolUseId: toolCall.id, name: toolCall.function?.name, - input: JSON.parse(toolCall.function?.arguments || "{}"), + input: safeParseToolCallArgs(toolCall), }, })), }; diff --git a/core/llm/llms/BedrockImport.ts b/core/llm/llms/BedrockImport.ts index 78701ca70..3ab45f373 100644 --- a/core/llm/llms/BedrockImport.ts +++ b/core/llm/llms/BedrockImport.ts @@ -51,9 +51,15 @@ class BedrockImport extends BaseLLM { if (response.body) { for await (const item of response.body) { - const chunk = JSON.parse(new TextDecoder().decode(item.chunk?.bytes)); - if (chunk.outputs[0].text) { - yield chunk.outputs[0].text; + const decoder = new TextDecoder(); + const decoded = decoder.decode(item.chunk?.bytes); + try { + const chunk = JSON.parse(decoded); + if (chunk.outputs[0].text) { + yield chunk.outputs[0].text; + } + } catch (e) { + throw new Error(`Malformed JSON received from Bedrock: ${decoded}`); } } } diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 63dd9cc3a..c6d32b501 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -9,6 +9,7 @@ import { TextMessagePart, ToolCallDelta, } from "../../index.js"; +import { safeParseToolCallArgs } from "../../tools/parseArgs.js"; import { renderChatMessage, stripImages } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { @@ -250,11 +251,11 @@ class Gemini extends BaseLLM { }; if (msg.toolCalls) { msg.toolCalls.forEach((toolCall) => { - if (toolCall.function?.name && toolCall.function?.arguments) { + if (toolCall.function?.name) { assistantMsg.parts.push({ functionCall: { name: toolCall.function.name, - args: JSON.parse(toolCall.function.arguments), + args: safeParseToolCallArgs(toolCall), }, }); } diff --git a/core/llm/openaiTypeConverters.ts b/core/llm/openaiTypeConverters.ts index a3a6ad895..a24af02f7 100644 --- a/core/llm/openaiTypeConverters.ts +++ b/core/llm/openaiTypeConverters.ts @@ -1,21 +1,14 @@ import { FimCreateParamsStreaming } from "@continuedev/openai-adapters/dist/apis/base"; import { - Chat, ChatCompletion, ChatCompletionAssistantMessageParam, ChatCompletionChunk, ChatCompletionCreateParams, ChatCompletionMessageParam, - ChatCompletionUserMessageParam, CompletionCreateParams, } from "openai/resources/index"; -import { - ChatMessage, - CompletionOptions, - MessageContent, - TextMessagePart, -} from ".."; +import { ChatMessage, CompletionOptions, TextMessagePart } from ".."; export function toChatMessage( message: ChatMessage, @@ -51,7 +44,7 @@ export function toChatMessage( type: toolCall.type!, function: { name: toolCall.function?.name!, - arguments: toolCall.function?.arguments! || "{}", + arguments: toolCall.function?.arguments || "{}", }, })); } @@ -189,12 +182,12 @@ export function fromChatCompletionChunk( return { role: "assistant", content: "", - toolCalls: delta?.tool_calls.map((tool_call: any) => ({ + toolCalls: delta?.tool_calls.map((tool_call) => ({ id: tool_call.id, type: tool_call.type, function: { - name: tool_call.function.name, - arguments: tool_call.function.arguments, + name: tool_call.function?.name, + arguments: tool_call.function?.arguments, }, })), }; diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 243c162bb..6ea95610b 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -1,4 +1,4 @@ -import { ContextItem, Tool, ToolExtras } from ".."; +import { ContextItem, Tool, ToolCall, ToolExtras } from ".."; import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton"; import { canParseUrl } from "../util/url"; import { BuiltInToolNames } from "./builtIn"; @@ -14,6 +14,7 @@ import { requestRuleImpl } from "./implementations/requestRule"; import { runTerminalCommandImpl } from "./implementations/runTerminalCommand"; import { searchWebImpl } from "./implementations/searchWeb"; import { viewDiffImpl } from "./implementations/viewDiff"; +import { safeParseToolCallArgs } from "./parseArgs"; async function callHttpTool( url: string, @@ -170,14 +171,14 @@ async function callBuiltInTool( // Note: Edit tool is handled on client export async function callTool( tool: Tool, - callArgs: string, + toolCall: ToolCall, extras: ToolExtras, ): Promise<{ contextItems: ContextItem[]; errorMessage: string | undefined; }> { try { - const args = JSON.parse(callArgs || "{}"); + const args = safeParseToolCallArgs(toolCall); const contextItems = tool.uri ? await callToolFromUri(tool.uri, args, extras) : await callBuiltInTool(tool.function.name, args, extras); diff --git a/core/tools/parseArgs.ts b/core/tools/parseArgs.ts new file mode 100644 index 000000000..9e43ec48f --- /dev/null +++ b/core/tools/parseArgs.ts @@ -0,0 +1,26 @@ +import { ToolCallDelta } from ".."; + +function safeParseArgs( + args: string | undefined, + errorId?: string, +): Record { + try { + return JSON.parse(args ?? "{}"); + } catch (e) { + const identifier = errorId ? `Call: ${errorId}\nArgs:${args}\n` : ""; + console.error( + `Failed to parse tool call arguments\n${identifier}Error:`, + e, + ); + return {}; + } +} + +export function safeParseToolCallArgs( + toolCall: ToolCallDelta, +): Record { + return safeParseArgs( + toolCall.function?.arguments, + `${toolCall.function?.name} ${toolCall.id}`, + ); +} diff --git a/gui/src/redux/thunks/callCurrentTool.ts b/gui/src/redux/thunks/callCurrentTool.ts index 84270fdd8..af8b4d4d9 100644 --- a/gui/src/redux/thunks/callCurrentTool.ts +++ b/gui/src/redux/thunks/callCurrentTool.ts @@ -60,7 +60,7 @@ export const callCurrentTool = createAsyncThunk( output: clientToolOuput, respondImmediately, errorMessage: clientToolError, - } = await callClientTool(toolCallState.toolCall, { + } = await callClientTool(toolCallState, { dispatch, ideMessenger: extra.ideMessenger, streamId: state.session.codeBlockApplyStates.states.find( diff --git a/gui/src/util/clientTools/callClientTool.ts b/gui/src/util/clientTools/callClientTool.ts index 65f11fbf6..cdf6a960f 100644 --- a/gui/src/util/clientTools/callClientTool.ts +++ b/gui/src/util/clientTools/callClientTool.ts @@ -1,4 +1,4 @@ -import { ContextItem, ToolCall } from "core"; +import { ContextItem, ToolCallState } from "core"; import { BuiltInToolNames } from "core/tools/builtIn"; import { IIdeMessenger } from "../../context/IdeMessenger"; import { AppThunkDispatch, RootState } from "../../redux/store"; @@ -27,15 +27,15 @@ export type ClientToolImpl = ( ) => Promise; export async function callClientTool( - toolCall: ToolCall, + toolCallState: ToolCallState, extras: ClientToolExtras, ): Promise { - const args = JSON.parse(toolCall.function.arguments || "{}"); + const { toolCall, parsedArgs } = toolCallState; try { let output: ClientToolOutput; switch (toolCall.function.name) { case BuiltInToolNames.EditExistingFile: - output = await editToolImpl(args, toolCall.id, extras); + output = await editToolImpl(parsedArgs, toolCall.id, extras); break; default: throw new Error(`Invalid client tool name ${toolCall.function.name}`); diff --git a/gui/src/util/toolCallState.ts b/gui/src/util/toolCallState.ts index 8e3656b5b..1456be3f9 100644 --- a/gui/src/util/toolCallState.ts +++ b/gui/src/util/toolCallState.ts @@ -21,8 +21,9 @@ export function addToolCallDeltaToState( const nameDelta = toolCallDelta.function?.name ?? ""; const argsDelta = toolCallDelta.function?.arguments ?? ""; + // Some models may include the name repeatedly. This doesn't account for an edge case where the name is like "dothisdothis" and it happens to stream name in chunks "dothis" and "dothis" but that's a super edge case const mergedName = - currentName === nameDelta ? currentName : currentName + nameDelta; // Some models may include the name repeatedly. This doesn't account for an edge case where the name is like "dothisdothis" and it happens to stream name in chunks "dothis" and "dothis" but that's a super edge case + currentName === nameDelta ? currentName : currentName + nameDelta; const mergedArgs = currentArgs + argsDelta; const [_, parsedArgs] = incrementalParseJson(mergedArgs || "{}"); diff --git a/packages/fetch/src/stream.ts b/packages/fetch/src/stream.ts index b1f5ab906..fd84b7660 100644 --- a/packages/fetch/src/stream.ts +++ b/packages/fetch/src/stream.ts @@ -126,8 +126,12 @@ export async function* streamJSON(response: Response): AsyncGenerator { let position; while ((position = buffer.indexOf("\n")) >= 0) { const line = buffer.slice(0, position); - const data = JSON.parse(line); - yield data; + try { + const data = JSON.parse(line); + yield data; + } catch (e) { + throw new Error(`Malformed JSON sent from server: ${line}`); + } buffer = buffer.slice(position + 1); } } diff --git a/packages/openai-adapters/src/apis/Anthropic.ts b/packages/openai-adapters/src/apis/Anthropic.ts index 1bab370b0..299f895af 100644 --- a/packages/openai-adapters/src/apis/Anthropic.ts +++ b/packages/openai-adapters/src/apis/Anthropic.ts @@ -13,6 +13,7 @@ import { ChatCompletionCreateParams } from "openai/src/resources/index.js"; import { AnthropicConfig } from "../types.js"; import { chatChunk, chatChunkFromDelta, customFetch } from "../util.js"; import { EMPTY_CHAT_COMPLETION } from "../util/emptyChatCompletion.js"; +import { safeParseArgs } from "../util/parseArgs.js"; import { BaseLlmApi, CreateRerankResponse, @@ -105,7 +106,10 @@ export class AnthropicApi implements BaseLlmApi { type: "tool_use", id: toolCall.id, name: toolCall.function?.name, - input: JSON.parse(toolCall.function?.arguments || "{}"), + input: safeParseArgs( + toolCall.function?.arguments, + `${toolCall.function?.name} ${toolCall.id}`, + ), })), }; } diff --git a/packages/openai-adapters/src/apis/Gemini.ts b/packages/openai-adapters/src/apis/Gemini.ts index 6b6f58870..9df0c2e85 100644 --- a/packages/openai-adapters/src/apis/Gemini.ts +++ b/packages/openai-adapters/src/apis/Gemini.ts @@ -28,6 +28,7 @@ import { GeminiChatContentPart, GeminiToolFunctionDeclaration, } from "../util/gemini-types.js"; +import { safeParseArgs } from "../util/parseArgs.js"; import { BaseLlmApi, CreateRerankResponse, @@ -125,7 +126,10 @@ export class GeminiApi implements BaseLlmApi { functionCall: { id: toolCall.id, name: toolCall.function.name, - args: JSON.parse(toolCall.function.arguments || "{}"), + args: safeParseArgs( + toolCall.function.arguments, + `Call: ${toolCall.function.name} ${toolCall.id}`, + ), }, })), }; diff --git a/packages/openai-adapters/src/util/parseArgs.ts b/packages/openai-adapters/src/util/parseArgs.ts new file mode 100644 index 000000000..8e7bb7380 --- /dev/null +++ b/packages/openai-adapters/src/util/parseArgs.ts @@ -0,0 +1,15 @@ +export function safeParseArgs( + args: string | undefined, + errorId?: string, +): Record { + try { + return JSON.parse(args ?? "{}"); + } catch (e) { + const identifier = errorId ? `Call: ${errorId}\nArgs:${args}\n` : ""; + console.error( + `Failed to parse tool call arguments\n${identifier}Error:`, + e, + ); + return {}; + } +}