🪢 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(playground): show openai agent tools (#10330)
Nimar446ff8043470
diff --git a/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx b/web/src/features/playground/page/components/JumpToPlaygroundButton.tsxindex 768d8b3196..c9cebfcec1 100644--- a/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx+++ b/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx@@ -34,7 +34,7 @@ import {PromptType,isGenerationLike,} from "@langfuse/shared";-import { normalizeInput } from "@/src/utils/chatml";+import { normalizeInput, normalizeOutput } from "@/src/utils/chatml";import { extractTools } from "@/src/utils/chatml/extractTools";import { convertChatMlToPlayground } from "@/src/utils/chatml/playgroundConverter";import { api } from "@/src/utils/api";@@ -258,7 +258,11 @@ const parseGeneration = (if (!isGenerationLike(generation.type)) return null;let modelParams = parseModelParams(generation, modelToProviderMap);- const tools = parseTools(generation.input, generation.metadata);+ const tools = parseTools(+ generation.input,+ generation.output,+ generation.metadata,+ );const structuredOutputSchema = parseStructuredOutputSchema(generation);const providerOptions = parseLitellmMetadataFromGeneration(generation);@@ -334,7 +338,7 @@ const parseGeneration = (const inResult = normalizeInput(input, ctx);- const messages = inResult.success+ let messages = inResult.success? inResult.data.map(convertChatMlToPlayground).filter(@@ -342,12 +346,59 @@ const parseGeneration = (): [];+ // process output for final assistant message+ // this doesn't make that much sense, because the output is already the LLM result+ // but some people wanted to have the entire thing, so that they can then iterate+ // on the final result (e.g. ask it questions).+ // NOTE: will probably remove later at some point on next playground release+ let output = generation.output?.valueOf();+ if (output && typeof output === "string") {+ try {+ output = JSON.parse(output);+ } catch {+ // ignore parse errors+ }+ }++ if (output && typeof output === "object") {+ try {+ const outResult = normalizeOutput(output, ctx);+ const outputMessages = outResult.success+ ? outResult.data+ .map(convertChatMlToPlayground)+ .filter(+ (msg): msg is ChatMessage | PlaceholderMessage =>+ msg !== null,+ )+ // Filter tool calls without results (i.e. assistant messages with tool_calls but no results)+ // here, a tool was just selected by an LLM but not called yet.+ // we don't want this in the playground, because we a) cannot run the playground+ // and b) if we jump to the playground, we exactly want to test if the LLM selects the tool+ .filter((msg) => msg.type !== ChatMessageType.AssistantToolCall)+ : [];++ // Append output messages to input messages+ messages = [...messages, ...outputMessages];+ } catch {+ // ignore output processing errors+ }+ }+if (messages.length === 0) return null;+ // Extract tools from normalized ChatML messages (they may have tools attached)+ const normalizedTools =+ inResult.success && inResult.data+ ? extractTools(inResult.data, ctx.metadata)+ : [];++ // Merge with tools from input/metadata, prefer normalized tools+ const mergedTools = normalizedTools.length > 0 ? normalizedTools : tools;+return {messages,modelParams,- tools,+ tools: mergedTools,structuredOutputSchema,};} catch {@@ -402,14 +453,25 @@ function parseModelParams(function parseTools(inputString: string | null,+ outputString: string | null,metadataString: string | null,): PlaygroundTool[] {- if (!inputString && !metadataString) return [];+ if (!inputString && !outputString && !metadataString) return [];try {const input = inputString ? JSON.parse(inputString) : null;+ const output = outputString ? JSON.parse(outputString) : null;const metadata = metadataString ? JSON.parse(metadataString) : null;- return extractTools(input, metadata);++ const inputTools = extractTools(input, metadata);+ if (inputTools.length > 0) return inputTools;++ // also check the output for tools, e.g. if a user jumps from the last generation+ if (output) {+ return extractTools(output, metadata);+ }++ return [];} catch {return [];}diff --git a/web/src/utils/chatml/adapters/langgraph.ts b/web/src/utils/chatml/adapters/langgraph.tsindex 3ec216f8ec..8f0d8b8f49 100644--- a/web/src/utils/chatml/adapters/langgraph.ts+++ b/web/src/utils/chatml/adapters/langgraph.ts@@ -273,6 +273,20 @@ export const langgraphAdapter: ProviderAdapter = {// EXPLICIT: Framework hintif (ctx.framework === "langgraph") return true;+ // REJECTIONS: Reject OpenAI Agents SDK format+ if (meta && typeof meta === "object") {+ if ("scope" in meta && typeof meta.scope === "object") {+ const scope = meta.scope as Record<string, unknown>;+ if (+ scope.name === "openinference.instrumentation.openai_agents" ||+ (typeof scope.name === "string" &&+ scope.name.includes("openai_agents"))+ ) {+ return false;+ }+ }+ }+// HINTS: LangGraph/LangChain-specific metadata markersif (meta && typeof meta === "object") {// LangGraph markersdiff --git a/web/src/utils/chatml/adapters/openai.clienttest.ts b/web/src/utils/chatml/adapters/openai.clienttest.tsindex 670db77617..f9cadbdd46 100644--- a/web/src/utils/chatml/adapters/openai.clienttest.ts+++ b/web/src/utils/chatml/adapters/openai.clienttest.ts@@ -207,6 +207,72 @@ describe("OpenAI Adapter", () => {expect(result.data?.[0].tool_call_id).toBe("call_456");});+ describe("OpenAI Agents SDK format", () => {+ it("should convert function_call to assistant with tool_calls", () => {+ const output = [+ {+ type: "function_call",+ name: "get_weather",+ arguments: { city: "SF" },+ call_id: "call_123",+ },+ ];++ const result = normalizeOutput(output, { framework: "openai" });++ expect(result.data?.[0].role).toBe("assistant");+ expect(result.data?.[0].tool_calls?.[0]).toEqual({+ id: "call_123",+ name: "get_weather",+ arguments: '{"city":"SF"}',+ type: "function",+ });+ });++ it("should convert function_call_output to tool message", () => {+ const input = [+ {+ type: "function_call_output",+ call_id: "call_456",+ output: "It's sunny.",+ },+ ];++ const result = normalizeInput(input, { framework: "openai" });++ expect(result.data?.[0].role).toBe("tool");+ expect(result.data?.[0].tool_call_id).toBe("call_456");+ expect(result.data?.[0].content).toBe("It's sunny.");+ });++ it("should attach tools to messages in Responses API format", () => {+ const output = {+ tools: [{ name: "get_weather", type: "function", description: null }],+ output: [{ type: "function_call", name: "get_weather", call_id: "c1" }],+ };++ const result = normalizeOutput(output, { framework: "openai" });++ expect(result.data?.[0].tools?.[0].name).toBe("get_weather");+ expect(result.data?.[0].tools?.[0].description).toBe("");+ });++ it("should extract text from output_text content", () => {+ const output = {+ output: [+ {+ content: [{ type: "output_text", text: "Hello" }],+ role: "assistant",+ },+ ],+ };++ const result = normalizeOutput(output, { framework: "openai" });++ expect(result.data?.[0].content).toBe("Hello");+ });+ });+describe("Chat Completions API", () => {it("should handle request format with tools and flatten tool_calls", () => {const input = {diff --git a/web/src/utils/chatml/adapters/openai.ts b/web/src/utils/chatml/adapters/openai.tsindex f972257e3f..4bccb13d49 100644--- a/web/src/utils/chatml/adapters/openai.ts+++ b/web/src/utils/chatml/adapters/openai.ts@@ -65,49 +65,95 @@ const OpenAIOutputSingleMessageSchema = z.looseObject({function normalizeMessage(msg: unknown): Record<string, unknown> {if (!msg || typeof msg !== "object") return {};- let normalized = removeNullFields(msg);-- // Normalize camelCase toolCalls to snake_case tool_calls (VAPI framework does this, otherwise it matches OpenAI)- if ("toolCalls" in normalized && Array.isArray(normalized.toolCalls)) {- normalized.tool_calls = normalized.toolCalls;- delete normalized.toolCalls;- }+ // we want to do type-based conversions BEFORE removeNullFields+ // because removeNullFields moves unrecognized fields to json passthrough+ let working = msg as Record<string, unknown>;// Convert direct function call message to tool_calls array format// Format: { type: "function_call", name: "...", arguments: {...}, call_id: "..." }// Convert to: { role: "assistant", tool_calls: [{ id, name, arguments, type }] }if (- (normalized.type === "function_call" || normalized.type === "tool_call") &&- normalized.name &&- typeof normalized.name === "string"+ (working.type === "function_call" || working.type === "tool_call") &&+ working.name &&+ typeof working.name === "string") {const toolCall: Record<string, unknown> = {- id: normalized.call_id || normalized.id || "",- name: normalized.name,+ id: working.call_id || working.id || "",+ name: working.name,arguments:- typeof normalized.arguments === "string"- ? normalized.arguments- : JSON.stringify(normalized.arguments ?? {}),+ typeof working.arguments === "string"+ ? working.arguments+ : JSON.stringify(working.arguments ?? {}),type: "function",};- // Remove the direct function call properties and add tool_calls array/* eslint-disable @typescript-eslint/no-unused-vars */const {type: _type,name: _name,arguments: _args,call_id: _call_id,+ id: _id,+ status: _status,...rest- } = normalized;+ } = working;/* eslint-enable @typescript-eslint/no-unused-vars */- normalized = {+ working = {...rest,role: rest.role || "assistant",tool_calls: [toolCall],};}+ // Convert function_call_output to standard tool message format+ // Format: { type: "function_call_output", call_id: "...", output: "..." }+ // Convert to: { role: "tool", tool_call_id: "...", content: "..." }+ if (working.type === "function_call_output") {+ const content =+ typeof working.output === "string"+ ? working.output+ : JSON.stringify(working.output ?? "");++ /* eslint-disable @typescript-eslint/no-unused-vars */+ const { type: _type, call_id, output: _output, ...rest } = working;+ /* eslint-enable @typescript-eslint/no-unused-vars */++ working = {+ ...rest,+ role: "tool",+ tool_call_id: call_id,+ content,+ };+ }++ // Now apply removeNullFields after conversions+ let normalized = removeNullFields(working);++ // Extract text from OpenAI Agents output_text format+ // Format: content: [{type: "output_text", text: "..."}]+ if (+ normalized.content &&+ Array.isArray(normalized.content) &&+ normalized.content.length > 0+ ) {+ const firstItem = normalized.content[0];+ if (+ firstItem &&+ typeof firstItem === "object" &&+ (firstItem as Record<string, unknown>).type === "output_text" &&+ typeof (firstItem as Record<string, unknown>).text === "string"+ ) {+ // Extract just the text for simple output+ normalized.content = (firstItem as Record<string, unknown>).text;+ }+ }++ // Normalize camelCase toolCalls to snake_case tool_calls (VAPI framework does this, otherwise it matches OpenAI)+ if ("toolCalls" in normalized && Array.isArray(normalized.toolCalls)) {+ normalized.tool_calls = normalized.toolCalls;+ delete normalized.toolCalls;+ }+// Flatten OpenAI nested tool_calls format: function.name → name, function.arguments → arguments// Format: { id, type: "function", function: { name, arguments } }// Convert to: { id, name, arguments, type }@@ -172,8 +218,10 @@ function flattenToolDefinition(tool: unknown): Record<string, unknown> {// Handle nested {type, function: {name, ...}} or flat {name, ...}const toolFunc = (t.function as Record<string, unknown> | undefined) ?? t;- const toolDef: Record<string, unknown> = { name: toolFunc.name };- if (toolFunc.description != null) toolDef.description = toolFunc.description;+ const toolDef: Record<string, unknown> = {+ name: toolFunc.name,+ description: toolFunc.description ?? "",+ };if (toolFunc.parameters != null) toolDef.parameters = toolFunc.parameters;return toolDef;}@@ -203,6 +251,20 @@ function preprocessData(data: unknown): unknown {}}+ // Responses API without tools: {output: [...]}+ if (+ typeof data === "object" &&+ !Array.isArray(data) &&+ "output" in data &&+ !("messages" in data) &&+ !("tools" in data)+ ) {+ const obj = data as Record<string, unknown>;+ if (Array.isArray(obj.output)) {+ return (obj.output as unknown[]).map(normalizeMessage);+ }+ }+// Chat Completions response: {choices: [{message: {...}}]}if (typeof data === "object" && !Array.isArray(data) && "choices" in data) {const obj = data as Record<string, unknown>;diff --git a/web/src/utils/chatml/extractTools.ts b/web/src/utils/chatml/extractTools.tsindex 9a4b6c995a..c9566068ef 100644--- a/web/src/utils/chatml/extractTools.ts+++ b/web/src/utils/chatml/extractTools.ts@@ -3,6 +3,21 @@ import { OpenAIToolSchema } from "@langfuse/shared";import type { PlaygroundTool } from "@/src/features/playground/page/types";import { extractAdditionalInput } from "./core";+/**+ * Helper to map parsed OpenAI tool schemas to PlaygroundTool format.+ * Ensures description is always a string (never null/undefined).+ */+function mapToolsToPlayground(+ tools: z.infer<typeof OpenAIToolSchema>[],+): PlaygroundTool[] {+ return tools.map((tool) => ({+ id: Math.random().toString(36).substring(2),+ name: tool.function.name,+ description: tool.function.description ?? "",+ parameters: tool.function.parameters,+ }));+}+/*** Extracts tool definitions from various LLM input formats.* Supports OpenAI, LangChain, and Microsoft Agent Framework formats.@@ -16,19 +31,31 @@ export function extractTools(input: unknown,metadata?: unknown,): PlaygroundTool[] {- // Microsoft Agent Framework: tools in metadata.attributes["gen_ai.tool.definitions"]+ // Check metadata for tool definitionsif (metadata && typeof metadata === "object" && metadata !== null) {const meta = metadata as Record<string, unknown>;if (meta.attributes && typeof meta.attributes === "object") {const attributes = meta.attributes as Record<string, unknown>;++ // Microsoft Agent Framework: tools in "gen_ai.tool.definitions"const toolDefs = attributes["gen_ai.tool.definitions"];if (toolDefs && Array.isArray(toolDefs)) {const parsedTools = z.array(OpenAIToolSchema).safeParse(toolDefs);if (parsedTools.success) {- return parsedTools.data.map((tool) => ({- id: Math.random().toString(36).substring(2),- ...tool.function,- }));+ return mapToolsToPlayground(parsedTools.data);+ }+ }++ // OpenTelemetry semantic convention: tools indexed as "llm.tools.{N}.tool.json_schema"+ // Example: "llm.tools.0.tool.json_schema", "llm.tools.1.tool.json_schema", ...+ const toolKeys = Object.keys(attributes).filter((key) =>+ /^llm\.tools\.\d+\.tool\.json_schema$/.test(key),+ );+ if (toolKeys.length > 0) {+ const toolDefs = toolKeys.map((key) => attributes[key]);+ const parsedTools = z.array(OpenAIToolSchema).safeParse(toolDefs);+ if (parsedTools.success) {+ return mapToolsToPlayground(parsedTools.data);}}}@@ -36,13 +63,34 @@ export function extractTools(if (!input) return [];+ // ChatML normalized format: tools attached to messages (from OpenAI Agents/Responses API)+ // After preprocessing, tools are attached to each message+ if (Array.isArray(input)) {+ const firstMessageWithTools = input.find(+ (msg: any) =>+ msg &&+ typeof msg === "object" &&+ msg.tools &&+ Array.isArray(msg.tools) &&+ msg.tools.length > 0,+ );+ if (firstMessageWithTools && Array.isArray(firstMessageWithTools.tools)) {+ return firstMessageWithTools.tools.map((tool: any) => ({+ id: Math.random().toString(36).substring(2),+ name: tool.name || tool.function?.name,+ description: tool.description ?? tool.function?.description ?? "",+ parameters: tool.parameters || tool.function?.parameters,+ }));+ }+ }+// LangChain format: tools in additional.tools fieldconst additionalInput = extractAdditionalInput(input);if (additionalInput?.tools && Array.isArray(additionalInput.tools)) {return additionalInput.tools.map((tool: any) => ({id: Math.random().toString(36).substring(2),name: tool.name || tool.function?.name,- description: tool.description || tool.function?.description,+ description: tool.description ?? tool.function?.description ?? "",parameters: tool.parameters || tool.function?.parameters,}));}@@ -54,10 +102,7 @@ export function extractTools(.safeParse((input as Record<string, unknown>)["tools"]);if (parsedTools.success) {- return parsedTools.data.map((tool) => ({- id: Math.random().toString(36).substring(2),- ...tool.function,- }));+ return mapToolsToPlayground(parsedTools.data);}}@@ -78,10 +123,7 @@ export function extractTools(const parsedTools = z.array(OpenAIToolSchema).safeParse(toolDefs);if (parsedTools.success) {- return parsedTools.data.map((tool) => ({- id: Math.random().toString(36).substring(2),- ...tool.function,- }));+ return mapToolsToPlayground(parsedTools.data);}}}@@ -109,10 +151,7 @@ export function extractTools(const parsedTools = z.array(OpenAIToolSchema).safeParse(toolDefs);if (parsedTools.success) {- return parsedTools.data.map((tool) => ({- id: Math.random().toString(36).substring(2),- ...tool.function,- }));+ return mapToolsToPlayground(parsedTools.data);}}}diff --git a/web/src/utils/chatml/jumptoplayground.clienttest.ts b/web/src/utils/chatml/jumptoplayground.clienttest.tsindex c00c3edb01..2180ae28aa 100644--- a/web/src/utils/chatml/jumptoplayground.clienttest.ts+++ b/web/src/utils/chatml/jumptoplayground.clienttest.ts@@ -664,6 +664,61 @@ describe("Playground Jump Full Pipeline", () => {).toContain("PatientNo");});+ it("should handle OpenAI Agents function_call and function_call_output", () => {+ // user message, function_call (tool call), function_call_output (tool result)+ const input = [+ { content: "What's the weather in Tokyo?", role: "user" },+ {+ arguments: { city: "Tokyo" },+ call_id: "call_abc123",+ name: "get_weather",+ type: "function_call",+ id: "fc_xyz",+ status: "completed",+ },+ {+ call_id: "call_abc123",+ output: "The weather in Tokyo is sunny.",+ type: "function_call_output",+ },+ ];++ const inResult = normalizeInput(input, { framework: "openai" });+ expect(inResult.success).toBe(true);++ const playgroundMessages = inResult+ .data!.map(convertChatMlToPlayground)+ .filter((msg) => msg !== null);++ // Should have 3 messages+ expect(playgroundMessages).toHaveLength(3);++ // Message 1: user+ expect(playgroundMessages[0]?.type).toBe("public-api-created");+ if (playgroundMessages[0]?.type === "public-api-created") {+ expect(playgroundMessages[0].role).toBe("user");+ expect(playgroundMessages[0].content).toBe(+ "What's the weather in Tokyo?",+ );+ }++ // Message 2: assistant with tool call+ expect(playgroundMessages[1]?.type).toBe("assistant-tool-call");+ if (playgroundMessages[1]?.type === "assistant-tool-call") {+ expect(playgroundMessages[1].toolCalls[0].id).toBe("call_abc123");+ expect(playgroundMessages[1].toolCalls[0].name).toBe("get_weather");+ }++ // Message 3: tool result+ expect(playgroundMessages[2]?.type).toBe("tool-result");+ if (playgroundMessages[2]?.type === "tool-result") {+ expect(playgroundMessages[2].toolCallId).toBe("call_abc123");+ expect(playgroundMessages[2].content).toBe(+ "The weather in Tokyo is sunny.",+ );+ }+ });+it("should handle VAPI camelCase toolCalls and preserve IDs", () => {// VAPI uses camelCase toolCalls instead of tool_calls// Critical: Tool call IDs must be preserved for OpenAI API compatibility