Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(playground): use playground with tool calls form langgraph traces (#7923)

Nimard6dac507345d
diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.ts
index a18481f96a..62d69e21bc 100644
--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts
+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts
@@ -192,11 +192,12 @@ export async function fetchLLMCompletion(
)
return new SystemMessage(safeContent);
- if (message.type === ChatMessageType.ToolResult)
+ if (message.type === ChatMessageType.ToolResult) {
return new ToolMessage({
content: safeContent,
tool_call_id: message.toolCallId,
});
+ }
return new AIMessage({
content: safeContent,
diff --git a/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx b/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
index b2dfb31f16..e93b2df998 100644
--- a/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
+++ b/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
@@ -243,7 +243,8 @@ const isLangchainToolDefinitionMessage = (
const transformToPlaygroundMessage = (
message: z.infer<typeof ParsedChatMessageListSchema>[0],
-): ChatMessage | PlaceholderMessage => {
+ allMessages?: z.infer<typeof ParsedChatMessageListSchema>,
+): ChatMessage | PlaceholderMessage | null => {
// Return placeholder messages as-is
if (isPlaceholder(message)) {
return message;
@@ -281,11 +282,46 @@ const transformToPlaygroundMessage = (
return playgroundMessage;
} else if (regularMessage.role === "tool") {
+ let toolCallId = (regularMessage as any).tool_call_id;
+
+ // Try to infer if tool_call_id is missing or empty (eg langgraph case)
+ if (!toolCallId && allMessages && regularMessage._originalRole) {
+ // Find all assistant messages with tool calls, most recent first
+ const assistantMessages = allMessages
+ .filter(
+ (msg): msg is Exclude<typeof msg, PlaceholderMessage> =>
+ !isPlaceholder(msg) &&
+ msg.role === "assistant" &&
+ !!(msg.tool_calls || msg.additional_kwargs?.tool_calls),
+ )
+ .reverse();
+
+ // Look for the first matching tool call by name
+ for (const prevMessage of assistantMessages) {
+ const toolCalls =
+ prevMessage.tool_calls ??
+ prevMessage.additional_kwargs?.tool_calls ??
+ [];
+
+ const matchingCall = toolCalls.find((tc) => {
+ if ("function" in tc) {
+ return tc.function.name === regularMessage._originalRole;
+ }
+ return tc.name === regularMessage._originalRole;
+ });
+
+ if (matchingCall && matchingCall.id) {
+ toolCallId = matchingCall.id;
+ break;
+ }
+ }
+ }
+
const playgroundMessage: ChatMessage = {
role: ChatMessageRole.Tool,
content,
type: ChatMessageType.ToolResult,
- toolCallId: regularMessage.tool_call_id ?? "",
+ toolCallId: toolCallId || "",
};
return playgroundMessage;
@@ -323,9 +359,15 @@ const parsePrompt = (
const parsedMessages =
ParsedChatMessageListSchema.safeParse(normalizedMessages);
- return parsedMessages.success
- ? { messages: parsedMessages.data.map(transformToPlaygroundMessage) }
- : null;
+ if (!parsedMessages.success) {
+ return null;
+ }
+
+ return {
+ messages: parsedMessages.data
+ .map((msg) => transformToPlaygroundMessage(msg, parsedMessages.data))
+ .filter((msg): msg is ChatMessage | PlaceholderMessage => msg !== null),
+ };
} else {
const promptString = prompt.resolvedPrompt;
@@ -403,15 +445,21 @@ const parseGeneration = (
const parsedMessages =
ParsedChatMessageListSchema.safeParse(normalizedMessages);
- if (parsedMessages.success)
- return {
- messages: parsedMessages.data
- .filter((m) => !isLangchainToolDefinitionMessage(m))
- .map(transformToPlaygroundMessage),
- modelParams,
- tools,
- structuredOutputSchema,
- };
+ if (!parsedMessages.success) {
+ return null;
+ }
+
+ const filteredMessages = parsedMessages.data.filter(
+ (m) => !isLangchainToolDefinitionMessage(m),
+ );
+ return {
+ messages: filteredMessages
+ .map((msg) => transformToPlaygroundMessage(msg, filteredMessages))
+ .filter((msg): msg is ChatMessage | PlaceholderMessage => msg !== null),
+ modelParams,
+ tools,
+ structuredOutputSchema,
+ };
}
if (typeof input === "object" && "messages" in input) {
@@ -424,15 +472,21 @@ const parseGeneration = (
const parsedMessages =
ParsedChatMessageListSchema.safeParse(normalizedMessages);
- if (parsedMessages.success)
- return {
- messages: parsedMessages.data
- .filter((m) => !isLangchainToolDefinitionMessage(m))
- .map(transformToPlaygroundMessage),
- modelParams,
- tools,
- structuredOutputSchema,
- };
+ if (!parsedMessages.success) {
+ return null;
+ }
+
+ const filteredMessages = parsedMessages.data.filter(
+ (m) => !isLangchainToolDefinitionMessage(m),
+ );
+ return {
+ messages: filteredMessages
+ .map((msg) => transformToPlaygroundMessage(msg, filteredMessages))
+ .filter((msg): msg is ChatMessage | PlaceholderMessage => msg !== null),
+ modelParams,
+ tools,
+ structuredOutputSchema,
+ };
}
return null;
diff --git a/web/src/features/playground/page/context/index.tsx b/web/src/features/playground/page/context/index.tsx
index ee3e8a7752..c0aa8ec27a 100644
--- a/web/src/features/playground/page/context/index.tsx
+++ b/web/src/features/playground/page/context/index.tsx
@@ -539,6 +539,7 @@ async function getChatCompletionWithTools(
tools,
streaming,
});
+
const result = await fetch(
`${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/chatCompletion`,
{
@@ -615,12 +616,20 @@ async function* getChatCompletionStream(
return;
}
+ const hasToolResults = messages.some(
+ (msg) => msg.type === ChatMessageType.ToolResult,
+ );
+
const body = JSON.stringify({
projectId,
messages,
modelParams: getFinalModelParams(modelParams),
streaming: true,
+ // Include empty tools array if there are tool result messages to ensure processing
+ // E.g. if tool call was picked up through traces but not defined
+ ...(hasToolResults && { tools: [] }),
});
+
const result = await fetch(
`${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/chatCompletion`,
{
@@ -667,11 +676,18 @@ async function getChatCompletionNonStreaming(
throw new Error("Project ID is not set");
}
+ const hasToolResults = messages.some(
+ (msg) => msg.type === ChatMessageType.ToolResult,
+ );
+
const body = JSON.stringify({
projectId,
messages,
modelParams: getFinalModelParams(modelParams),
streaming: false,
+ // Include empty tools array if there are tool result messages to ensure processing
+ // E.g. if tool call was picked up through traces but not defined
+ ...(hasToolResults && { tools: [] }),
});
const result = await fetch(
diff --git a/web/src/features/playground/server/chatCompletionHandler.ts b/web/src/features/playground/server/chatCompletionHandler.ts
index 2fb6a7a38a..3a662c9f8a 100644
--- a/web/src/features/playground/server/chatCompletionHandler.ts
+++ b/web/src/features/playground/server/chatCompletionHandler.ts
@@ -58,15 +58,54 @@ export default async function chatCompletionHandler(req: NextRequest) {
config: parsedKey.data.config,
};
- if ((tools && tools.length > 0) || structuredOutputSchema) {
- const { completion } = await fetchLLMCompletion({
+ if (structuredOutputSchema) {
+ const result = await fetchLLMCompletion({
...fetchLLMCompletionParams,
streaming: false,
- tools: tools ?? [],
structuredOutputSchema,
});
+ return NextResponse.json(result.completion);
+ }
+
+ // If messages contain tool results, we include tools in the request
+ const hasToolResults = messages.some((msg) => msg.type === "tool-result");
+
+ if ((tools && tools.length > 0) || hasToolResults) {
+ // Fix empty tool_call_id values by mapping to langgraph IDs
+ const fixedMessages = messages.map((msg) => {
+ if (
+ msg.type === "tool-result" &&
+ (!msg.toolCallId || msg.toolCallId === "")
+ ) {
+ const assistantMessages = messages
+ .filter((m) => m.type === "assistant-tool-call" && m.toolCalls)
+ .reverse();
+
+ // Find the first matching tool call by name
+ // Note: using 'as any' because we filtered for assistant-tool-call messages above
+ for (const prevMsg of assistantMessages) {
+ const matchingToolCall = (prevMsg as any).toolCalls.find(
+ (tc: any) => tc.name === (msg as any)._originalRole,
+ );
+ if (matchingToolCall && matchingToolCall.id) {
+ return {
+ ...msg,
+ toolCallId: matchingToolCall.id,
+ };
+ }
+ }
+ }
+
+ return msg;
+ });
- return NextResponse.json(completion);
+ const result = await (fetchLLMCompletion as any)({
+ ...fetchLLMCompletionParams,
+ messages: fixedMessages,
+ streaming: false,
+ tools: tools ?? [],
+ });
+ return NextResponse.json(result.completion);
}
if (streaming) {