🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(tool-parsing): ai sdk handle stringified jsons as well (#13550)
Nimarc4f50a1e3fe1
diff --git a/packages/shared/src/server/ingestion/extractToolsBackend.ts b/packages/shared/src/server/ingestion/extractToolsBackend.tsindex cf41280de3..3f0c868559 100644--- a/packages/shared/src/server/ingestion/extractToolsBackend.ts+++ b/packages/shared/src/server/ingestion/extractToolsBackend.ts@@ -129,6 +129,80 @@ function addToolArgument(args: ClickhouseToolArgument[], call: unknown): void {});}+function addToolArguments(+ args: ClickhouseToolArgument[],+ calls: unknown[] | undefined,+): void {+ if (!calls) return;++ for (const call of calls) {+ addToolArgument(args, call);+ }+}++function parseArrayIfString(data: unknown): unknown[] | undefined {+ if (Array.isArray(data)) return data;+ if (typeof data !== "string") return undefined;++ try {+ const parsed = JSON.parse(data);+ return Array.isArray(parsed) ? parsed : undefined;+ } catch {+ return undefined;+ }+}++/**+ * Detects model-requested tool invocations in unlabelled output arrays.+ * Excludes available tool definitions and tool result payloads.+ */+function isToolCallLike(value: unknown): boolean {+ if (!value || typeof value !== "object") return false;++ const call = value as Record<string, unknown>;+ if (call.type === "tool-result") return false;++ const functionCall = call.function as Record<string, unknown> | undefined;+ const hasOpenAiShape = Boolean(+ functionCall?.name && "arguments" in functionCall,+ );+ const hasAiSdkToolCallShape =+ Boolean(call.toolName) &&+ (call.type === "tool-call" || ["input", "args"].some((key) => key in call));+ const hasResponsesShape = Boolean(+ call.call_id && call.name && "arguments" in call,+ );+ const hasAnthropicToolUseShape = Boolean(+ call.type === "tool_use" && call.name && "input" in call,+ );+ const hasToolCallMarker =+ "id" in call ||+ "index" in call ||+ ["function", "function_call", "tool-call", "tool_use"].includes(+ String(call.type),+ );+ const hasFlatToolCallShape = Boolean(+ call.name && "arguments" in call && hasToolCallMarker,+ );++ return (+ hasOpenAiShape ||+ hasAiSdkToolCallShape ||+ hasResponsesShape ||+ hasAnthropicToolUseShape ||+ hasFlatToolCallShape+ );+}++function isMessageLike(value: unknown): boolean {+ if (!value || typeof value !== "object") return false;++ const message = value as Record<string, unknown>;+ return ["role", "content", "tool_calls", "additional_kwargs"].some(+ (key) => key in message,+ );+}+/*** Helper to add a tool call from content-array parts.* Handles Anthropic `tool_use` and AI SDK `tool-call` parts.@@ -207,9 +281,14 @@ function extractToolCallsFromRawOutput(// Array of messagesif (Array.isArray(output)) {- for (const msg of output) {- if (msg && typeof msg === "object") {- extractToolCallsFromMessage(msg as Record<string, unknown>, args);+ for (const item of output) {+ if (item && typeof item === "object") {+ const obj = item as Record<string, unknown>;+ if (isToolCallLike(obj) && !isMessageLike(obj)) {+ addToolArgument(args, obj);+ } else {+ extractToolCallsFromMessage(obj, args);+ }}}return;@@ -219,11 +298,9 @@ function extractToolCallsFromRawOutput(const obj = output as Record<string, unknown>;// Direct tool_calls at top level- if (Array.isArray(obj.tool_calls)) {- for (const call of obj.tool_calls) {- addToolArgument(args, call);- }- }+ const directToolCalls =+ parseArrayIfString(obj.tool_calls) ?? parseArrayIfString(obj.toolCalls);+ addToolArguments(args, directToolCalls);// OpenAI choices format: {choices: [{message: {tool_calls: [...]}}]}if (Array.isArray(obj.choices)) {@@ -231,11 +308,10 @@ function extractToolCallsFromRawOutput(if (choice && typeof choice === "object") {const c = choice as Record<string, unknown>;const message = c.message as Record<string, unknown> | undefined;- if (message && Array.isArray(message.tool_calls)) {- for (const call of message.tool_calls) {- addToolArgument(args, call);- }- }+ const messageToolCalls =+ parseArrayIfString(message?.tool_calls) ??+ parseArrayIfString(message?.toolCalls);+ addToolArguments(args, messageToolCalls);}}}@@ -259,11 +335,8 @@ function extractToolCallsFromRawOutput(const additionalKwargs = obj.additional_kwargs as| Record<string, unknown>| undefined;- if (additionalKwargs && Array.isArray(additionalKwargs.tool_calls)) {- for (const call of additionalKwargs.tool_calls) {- addToolArgument(args, call);- }- }+ const additionalToolCalls = parseArrayIfString(additionalKwargs?.tool_calls);+ addToolArguments(args, additionalToolCalls);}/**@@ -273,11 +346,9 @@ function extractToolCallsFromMessage(msg: Record<string, unknown>,args: ClickhouseToolArgument[],): void {- if (Array.isArray(msg.tool_calls)) {- for (const call of msg.tool_calls) {- addToolArgument(args, call);- }- }+ const messageToolCalls =+ parseArrayIfString(msg.tool_calls) ?? parseArrayIfString(msg.toolCalls);+ addToolArguments(args, messageToolCalls);// Tool calls in content arrays: Anthropic `tool_use`, AI SDK `tool-call`if (Array.isArray(msg.content)) {diff --git a/worker/src/__tests__/extractToolsBackend.test.ts b/worker/src/__tests__/extractToolsBackend.test.tsindex 6488896f46..5fad4de7cd 100644--- a/worker/src/__tests__/extractToolsBackend.test.ts+++ b/worker/src/__tests__/extractToolsBackend.test.ts@@ -351,6 +351,160 @@ describe("extractToolsFromObservation", () => {});});+ it("extracts AI SDK tool_calls when OTel stores the tool call array as a JSON string", () => {+ const output = JSON.stringify({+ role: "assistant",+ content: "I'll check the weather.",+ tool_calls: JSON.stringify([+ {+ toolCallId: "tooluse_weather",+ toolName: "getWeather",+ input: {+ location: "Berlin",+ unit: "celsius",+ },+ },+ ]),+ });++ const { toolArguments } = extractToolsFromObservation(null, output);++ expect(toolArguments).toHaveLength(1);+ expect(toolArguments[0]).toMatchObject({+ id: "tooluse_weather",+ name: "getWeather",+ arguments: JSON.stringify({+ location: "Berlin",+ unit: "celsius",+ }),+ });+ });++ it("extracts raw AI SDK tool call arrays from ingestion output", () => {+ const output = JSON.stringify([+ {+ toolCallId: "tooluse_forecast",+ toolName: "getForecast",+ input: {+ location: "San Francisco",+ days: 3,+ },+ },+ ]);++ const { toolArguments } = extractToolsFromObservation(null, output);++ expect(toolArguments).toHaveLength(1);+ expect(toolArguments[0]).toMatchObject({+ id: "tooluse_forecast",+ name: "getForecast",+ arguments: JSON.stringify({+ location: "San Francisco",+ days: 3,+ }),+ });+ });++ it("extracts mixed message and raw tool call arrays from ingestion output", () => {+ const output = JSON.stringify([+ {+ role: "assistant",+ content: "I'll check the weather.",+ },+ {+ toolCallId: "tooluse_weather",+ toolName: "getWeather",+ input: {+ location: "Berlin",+ unit: "celsius",+ },+ },+ ]);++ const { toolArguments } = extractToolsFromObservation(null, output);++ expect(toolArguments).toHaveLength(1);+ expect(toolArguments[0]).toMatchObject({+ id: "tooluse_weather",+ name: "getWeather",+ arguments: JSON.stringify({+ location: "Berlin",+ unit: "celsius",+ }),+ });+ });++ it("does not treat arbitrary output arrays with id and name fields as tool calls", () => {+ const output = JSON.stringify([+ {+ id: "weather_station_1",+ name: "Berlin weather station",+ },+ {+ id: "weather_station_2",+ name: "San Francisco weather station",+ },+ ]);++ const { toolArguments } = extractToolsFromObservation(null, output);++ expect(toolArguments).toEqual([]);+ });++ it("does not treat AI SDK tool-result arrays as tool calls", () => {+ // tool-result arrays are not treated as tool calls, they might not be caused+ // because a model choose to call a tool, but might be externally caused+ const output = JSON.stringify([+ {+ type: "tool-result",+ toolCallId: "tooluse_weather",+ toolName: "getWeather",+ result: {+ temperature: 19,+ },+ },+ ]);++ const { toolArguments } = extractToolsFromObservation(null, output);++ expect(toolArguments).toEqual([]);+ });++ it("does not treat function definition arrays as tool calls", () => {+ const output = JSON.stringify([+ {+ type: "function",+ function: {+ name: "getWeather",+ parameters: {+ type: "object",+ properties: {+ location: { type: "string" },+ },+ },+ },+ },+ ]);++ const { toolArguments } = extractToolsFromObservation(null, output);++ expect(toolArguments).toEqual([]);+ });++ it("does not treat arbitrary output arrays with name and input fields as tool calls", () => {+ const output = JSON.stringify([+ {+ id: "review_1",+ name: "Alice",+ input: "Great weather forecast.",+ },+ ]);++ const { toolArguments } = extractToolsFromObservation(null, output);++ expect(toolArguments).toEqual([]);+ });+it("preserves index field for parallel tool calls", () => {const output = {tool_calls: [diff --git a/worker/src/queues/__tests__/otelToObservationForEval.test.ts b/worker/src/queues/__tests__/otelToObservationForEval.test.tsindex b546dd3c49..c7e540d8a8 100644--- a/worker/src/queues/__tests__/otelToObservationForEval.test.ts+++ b/worker/src/queues/__tests__/otelToObservationForEval.test.ts@@ -656,6 +656,91 @@ describe("OTEL to ObservationForEval Schema Validation", () => {expect(obs.input).toBe('[{"role":"user","content":"Say hello"}]');expect(obs.output).toBe("Hello! How can I help you today?");});++ it("should extract AI SDK tool calls from stringified OTel toolCalls attributes", async () => {+ const vercelAIToolCallSpan = {+ resource: { attributes: [] },+ scopeSpans: [+ {+ scope: { name: "ai" },+ spans: [+ {+ traceId: createBufferId("a1e2d3c4b5a69788a1e2d3c4b5a69788"),+ spanId: createBufferId("1122334455667799"),+ name: "ai.generateText.doGenerate",+ kind: 1,+ startTimeUnixNano: createNanoTimestamp(+ BigInt(1738241387865000000),+ ),+ endTimeUnixNano: createNanoTimestamp(+ BigInt(1738241389310000000),+ ),+ attributes: [+ {+ key: "ai.model.id",+ value: { stringValue: "claude-opus-4-6" },+ },+ {+ key: "ai.operationId",+ value: { stringValue: "ai.generateText.doGenerate" },+ },+ {+ key: "ai.prompt.messages",+ value: {+ stringValue: JSON.stringify([+ {+ role: "user",+ content: "Check the weather in Berlin",+ },+ ]),+ },+ },+ {+ key: "ai.response.text",+ value: { stringValue: "I'll check the weather." },+ },+ {+ key: "ai.response.toolCalls",+ value: {+ stringValue: JSON.stringify([+ {+ toolCallId: "tooluse_weather",+ toolName: "getWeather",+ input: {+ location: "Berlin",+ unit: "celsius",+ },+ },+ ]),+ },+ },+ ],+ status: {},+ },+ ],+ },+ ],+ };++ const observations =+ await processOtelSpanToObservationForEval(vercelAIToolCallSpan);++ expect(observations).toHaveLength(1);+ const obs = observations[0];++ const result = observationForEvalSchema.safeParse(obs);+ expect(result.success).toBe(true);++ expect(obs.tool_call_names).toEqual(["getWeather"]);+ expect(obs.tool_calls).toHaveLength(1);+ expect(JSON.parse(obs.tool_calls[0])).toMatchObject({+ id: "tooluse_weather",+ arguments: JSON.stringify({+ location: "Berlin",+ unit: "celsius",+ }),+ });+ });});describe("Schema field coverage", () => {