JSON parsing progress

This commit is contained in:
Dallin Romney 2025-06-04 15:16:41 -07:00
parent 422315fe8c
commit dcdc04f0ba
17 changed files with 126 additions and 57 deletions

View file

@ -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",
},
];
}
}

View file

@ -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");

View file

@ -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,

View file

@ -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) {

View file

@ -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),
},
})),
};

View file

@ -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}`);
}
}
}

View file

@ -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),
},
});
}

View file

@ -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,
},
})),
};

View file

@ -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);

26
core/tools/parseArgs.ts Normal file
View file

@ -0,0 +1,26 @@
import { ToolCallDelta } from "..";
function safeParseArgs(
args: string | undefined,
errorId?: string,
): Record<string, any> {
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<string, any> {
return safeParseArgs(
toolCall.function?.arguments,
`${toolCall.function?.name} ${toolCall.id}`,
);
}

View file

@ -60,7 +60,7 @@ export const callCurrentTool = createAsyncThunk<void, undefined, ThunkApiType>(
output: clientToolOuput,
respondImmediately,
errorMessage: clientToolError,
} = await callClientTool(toolCallState.toolCall, {
} = await callClientTool(toolCallState, {
dispatch,
ideMessenger: extra.ideMessenger,
streamId: state.session.codeBlockApplyStates.states.find(

View file

@ -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<ClientToolOutput>;
export async function callClientTool(
toolCall: ToolCall,
toolCallState: ToolCallState,
extras: ClientToolExtras,
): Promise<ClientToolResult> {
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}`);

View file

@ -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 || "{}");

View file

@ -126,8 +126,12 @@ export async function* streamJSON(response: Response): AsyncGenerator<any> {
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);
}
}

View file

@ -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}`,
),
})),
};
}

View file

@ -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}`,
),
},
})),
};

View file

@ -0,0 +1,15 @@
export function safeParseArgs(
args: string | undefined,
errorId?: string,
): Record<string, any> {
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 {};
}
}