Skip to content

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

feat(trace-ui): render tool calls (#9729)

Nimar4751a156a838
diff --git a/packages/shared/scripts/seeder/utils/framework-traces/google-vertex-tools-2025-09-19.json b/packages/shared/scripts/seeder/utils/framework-traces/google-vertex-tools-langchain-2025-09-19.json
similarity index 100%
rename from packages/shared/scripts/seeder/utils/framework-traces/google-vertex-tools-2025-09-19.json
rename to packages/shared/scripts/seeder/utils/framework-traces/google-vertex-tools-langchain-2025-09-19.json
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 680d5ff728..4fe79989d9 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -53,7 +53,7 @@ importers:
next-auth:
specifier: ^4.24.12
zod:
specifier: ^3.25.62
version: 3.25.62
@@ -236,7 +236,7 @@ importers:
version: 4.1.1
next-auth:
specifier: ^4.24.12
nodemailer:
specifier: ^7.0.10
version: 7.0.10
@@ -623,8 +623,8 @@ importers:
specifier: ^4.17.21
version: 4.17.21
lucide-react:
- specifier: ^0.462.0
- version: 0.462.0([email protected])
+ specifier: ^0.552.0
+ version: 0.552.0([email protected])
nanoid:
specifier: ^3.3.8
version: 3.3.11
@@ -633,7 +633,7 @@ importers:
next-auth:
specifier: ^4.24.12
next-query-params:
specifier: ^5.1.0
@@ -2128,8 +2128,8 @@ packages:
'@codemirror/[email protected]':
resolution: {integrity: sha512-s3n3KisH7dx3vsoeGMxsbRAgKe4O1vbrnKBClm99PU0fWxmxsx5rR2PfqQgIt+2MMJBHbiJ5rfIdLYfB9NNvsA==}
- '@codemirror/[email protected]':
- resolution: {integrity: sha512-te7To1EQHePBQQzasDKWmK2xKINIXpk+xAiSYr9ZN+VB4KaT+/Hi2PEkeErTk5BV3PTz1TLyQL4MtJfPkKZ9sw==}
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-sv3DylBiIyi+xKwRCJAAsBZZZWo82shJ/RTMymLabAdtbkV5cSKwWDeCgtUq3v8flTaXS2y1kKkICuRYtUswyQ==}
'@codemirror/[email protected]':
resolution: {integrity: sha512-rpMgcsh7o0GuCDUXKPvww+muLA1pDJaFrpq/CCHtpQJYz8xopu4D1hPcKRoDD0YlF8gZaqTNIRa4VRBWyhyy7Q==}
@@ -3104,6 +3104,9 @@ packages:
resolution: {integrity: sha512-pu0K1jCIdnQ12aWNaAVU5bzi7Bd1w54J3ECgANPmYLtQKP0HBj2cE/5coBD66MT10xbtIuUr7tg0Shbsvk0mDA==}
+ '@lezer/[email protected]':
+ resolution: {integrity: sha512-yenN5SqAxAPv/qMnpWW0AT7l+SxVrgG+u0tNsRQWqbrz66HIl8DnEbBObvy21J5K7+I1v7gsAnlE2VQ5yYVSeA==}
+
'@marijn/[email protected]':
resolution: {integrity: sha512-l0h88YhZFyKdXIFNfSWpyjStDjGHwZ/U7iobcK1cQQD8sejsONdQtTVU+1wVN1PBw40PiiHB1vA5S7VTfQiP9g==}
@@ -6823,8 +6826,8 @@ packages:
resolution: {integrity: sha512-GM9c0cWWR8Ga7//Ves/9KRgTS8nLausCkP3CGiFLrnwA2CDUluXgaQqvrULoR2Ujrd/mz/lkX87F5BHFsNr5sQ==}
hasBin: true
- resolution: {integrity: sha512-JMWsdF+O8Orq3EMukbUN1QfbLK9mX2CkUmQBcW2T0s8OmdAUL5LLM/6wFwSrqXzlXB13yhyK9gTKS1rIizOduQ==}
+ resolution: {integrity: sha512-616V5YX4bepJFzNyOfce5Fa8fDJMfoxzOIzDCZwaGL8MKVpFrXqfNUoIpRn9YMI5pXf/VKgzjB4htFMsFKKdiQ==}
hasBin: true
@@ -6987,8 +6990,8 @@ packages:
resolution: {integrity: sha512-0rw2fJOmLfnzCRbkm8EyHL8SvI2Apu5UbnQuTsJ0ClgrH8hcwFooJ1s5R0EP8o8aVrFu8++ae29Kt9/gZAZp/Q==}
- resolution: {integrity: sha512-A0QJhug0Ly64Ii3eIqHu5X51ebln3k4yTUkY1j8drqpWHVreg/VLijN48cZ1bYPiqOQuqpkIKnzr/Ul8V+p6Cw==}
+ resolution: {integrity: sha512-Bj5H35MD/ebaOV4iDLqPEtiliTN29qkGtEHCwawWn4cYm+bPJM2NsaP30vtZcnERClMzp52J4+aw2UNbK4o+zw==}
resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==}
@@ -7946,8 +7949,8 @@ packages:
resolution: {integrity: sha512-iUdTQSf7EFXsDdQsp8MwJz5SVk4APEFqXU/S47OtQ0YLqacSwPXdZ5vRlMX3neb07Cy2vgioNuRnWUXFwuslkg==}
- resolution: {integrity: sha512-ZCphxFW3Q1TVhcgS9blfut1PX8lusVi2SvXQgmEEnK4TCmE1JhH2JkjJN+DNt0pJJwfBri5AROBnz2b/C+YU9g==}
+ resolution: {integrity: sha512-OszpBN7xZX4vWMPJwB9illkN/znA8M36GQqQxi6MNy9axWxhOfJyZZJtSLQCpEFLHP2xK33BiWx9aIuIEXVCcw==}
resolution: {integrity: sha512-+cYTcFB1QqD4j4LegwLfpCNxifb6dDFUAwk6RsLusCwIaZI6or2f+q8rs5tTB2YC53HhOlIbEaqHMAAC8IOIwA==}
@@ -10176,10 +10179,10 @@ packages:
resolution: {integrity: sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==}
engines: {node: '>=12'}
- resolution: {integrity: sha512-NTL7EbAao9IFtuSivSZgrAh4fZd09Lr+6MTkqIxuHaH2nnYiYIzXPo06cOxHg9wKLdj6LL8TByG4qpePqwgx/g==}
+ resolution: {integrity: sha512-g9WCjmfwqbexSnZE+2cl21PCfXOcqnGeWeMTNAOGEfpPbm/ZF4YIq77Z8qWrxbu660EKuLB4nSLggoKnCb+isw==}
peerDependencies:
- react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0-rc
+ react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0
resolution: {integrity: sha512-zobTr7akeGHnv7eBOXcRgMeCP6+uyYsczwmeRCauvpvaAltgNyTbLH/+VaEAPUeWBT+1GuNmz4wC/6jtQzbbVA==}
@@ -10791,8 +10794,8 @@ packages:
resolution: {integrity: sha512-cCmFDMSm26S6tQSDpBCg/NR8NENrVPhAJSf+XbxBG4rPFaaonlEoE9wHQmun+cls499TQGSb7ZyPBRlzgKfpeg==}
- resolution: {integrity: sha512-S2M9YimhSjBSvYnlr5/+umAnPHE++ODwt5e2Ij6FoX45HA/s4vHdkDx1eax2pAPeAOqu4s9b7ppahsyEFdVqQA==}
+ resolution: {integrity: sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==}
resolution: {integrity: sha512-Us/Se1WtT0ylXgNFfyFSx4LElllVLJXQjWi2Xz17xWw7amDKO2MLtFnVp1WACy7GkVGs+oBlRopVNUzlrGSw1w==}
@@ -16183,7 +16186,7 @@ snapshots:
'@codemirror/view': 6.38.1
'@lezer/common': 1.3.0
'@lezer/highlight': 1.2.3
- '@lezer/lr': 1.4.2
+ '@lezer/lr': 1.4.3
style-mod: 4.1.3
'@codemirror/[email protected]':
@@ -16192,7 +16195,7 @@ snapshots:
'@codemirror/view': 6.38.1
crelt: 1.0.6
- '@codemirror/[email protected]':
+ '@codemirror/[email protected]':
dependencies:
'@codemirror/state': 6.5.2
'@codemirror/view': 6.38.1
@@ -17391,6 +17394,10 @@ snapshots:
dependencies:
'@lezer/common': 1.2.3
+ '@lezer/[email protected]':
+ dependencies:
+ '@lezer/common': 1.3.0
+
'@marijn/[email protected]': {}
@@ -17596,7 +17603,7 @@ snapshots:
dependencies:
dependencies:
@@ -22072,7 +22079,7 @@ snapshots:
@@ -22156,10 +22163,10 @@ snapshots:
dependencies:
- baseline-browser-mapping: 2.8.20
- caniuse-lite: 1.0.30001751
- electron-to-chromium: 1.5.243
- node-releases: 2.0.26
+ baseline-browser-mapping: 2.8.23
+ caniuse-lite: 1.0.30001753
+ electron-to-chromium: 1.5.244
+ node-releases: 2.0.27
update-browserslist-db: 1.1.4([email protected])
@@ -22267,7 +22274,7 @@ snapshots:
@@ -22481,7 +22488,7 @@ snapshots:
'@codemirror/autocomplete': 6.17.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
'@codemirror/commands': 6.10.0
'@codemirror/language': 6.11.3
- '@codemirror/lint': 6.9.1
+ '@codemirror/lint': 6.9.2
'@codemirror/search': 6.5.6
'@codemirror/state': 6.5.2
'@codemirror/view': 6.38.1
@@ -23289,7 +23296,7 @@ snapshots:
@@ -24189,7 +24196,7 @@ snapshots:
dependencies:
- debug: 4.4.3
+ debug: 4.3.4
get-stream: 5.2.0
yauzl: 2.10.0
optionalDependencies:
@@ -26223,7 +26230,7 @@ snapshots:
dependencies:
react: 19.2.0
@@ -27030,7 +27037,7 @@ snapshots:
dependencies:
type-fest: 2.19.0
dependencies:
'@babel/runtime': 7.28.4
'@panva/hkdf': 1.2.1
@@ -27147,7 +27154,7 @@ snapshots:
diff --git a/web/package.json b/web/package.json
index 2c5f58c740..95cf75952a 100644
--- a/web/package.json
+++ b/web/package.json
@@ -122,7 +122,7 @@
"langchain": "^0.3.30",
"langfuse": "3.38.4",
"lodash": "^4.17.21",
- "lucide-react": "^0.462.0",
+ "lucide-react": "^0.552.0",
"nanoid": "^3.3.8",
"next": "15.5.4",
"next-auth": "^4.24.12",
diff --git a/web/src/components/schemas/ChatMlSchema.ts b/web/src/components/schemas/ChatMlSchema.ts
index 8149fd39aa..a6c82de4bc 100644
--- a/web/src/components/schemas/ChatMlSchema.ts
+++ b/web/src/components/schemas/ChatMlSchema.ts
@@ -104,6 +104,20 @@ export const OpenAIContentSchema = z
.nullable();
export type OpenAIContentSchema = z.infer<typeof OpenAIContentSchema>;
+const ToolDefinitionSchema = z.object({
+ name: z.string(),
+ description: z.string().optional(),
+ parameters: z.record(z.string(), z.any()).optional(),
+});
+
+const ToolCallSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ arguments: z.string(), // JSON string
+ type: z.string().optional(),
+ index: z.number().optional(),
+});
+
export const ChatMlMessageSchema = z
.object({
role: z.string().optional(),
@@ -118,6 +132,9 @@ export const ChatMlMessageSchema = z
.nullish(),
audio: OpenAIOutputAudioSchema.optional(),
additional_kwargs: z.record(z.string(), z.any()).optional(),
+ tools: z.array(ToolDefinitionSchema).optional(),
+ tool_calls: z.array(ToolCallSchema).optional(),
+ tool_call_id: z.string().optional(),
})
.passthrough()
.refine((value) => value.content !== null || value.role !== undefined)
@@ -125,14 +142,29 @@ export const ChatMlMessageSchema = z
...other,
...additional_kwargs,
}))
- .transform(({ role, name, content, audio, type, ...other }) => ({
- role,
- name,
- content,
- audio,
- type,
- ...(Object.keys(other).length === 0 ? {} : { json: other }),
- }));
+ .transform(
+ ({
+ role,
+ name,
+ content,
+ audio,
+ type,
+ tools,
+ tool_calls,
+ tool_call_id,
+ ...other
+ }) => ({
+ role,
+ name,
+ content,
+ audio,
+ type,
+ tools,
+ tool_calls,
+ tool_call_id,
+ ...(Object.keys(other).length === 0 ? {} : { json: other }),
+ }),
+ );
export type ChatMlMessageSchema = z.infer<typeof ChatMlMessageSchema>;
export const ChatMlArraySchema = z.array(ChatMlMessageSchema).min(1);
diff --git a/web/src/components/trace/IOPreview.tsx b/web/src/components/trace/IOPreview.tsx
index d0e95242f7..74cac4e9ee 100644
--- a/web/src/components/trace/IOPreview.tsx
+++ b/web/src/components/trace/IOPreview.tsx
@@ -11,7 +11,10 @@ import type {
} from "@/src/components/schemas/ChatMlSchema";
import { type MediaReturnType } from "@/src/features/media/validation";
import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";
-import { MarkdownJsonView } from "@/src/components/ui/MarkdownJsonView";
+import {
+ MarkdownJsonView,
+ MarkdownJsonViewHeader,
+} from "@/src/components/ui/MarkdownJsonView";
import { SubHeaderLabel } from "@/src/components/layouts/header";
import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
@@ -25,6 +28,10 @@ import {
cleanLegacyOutput,
extractAdditionalInput,
} from "@/src/utils/chatml";
+import { ToolCallDefinitionCard } from "@/src/components/trace/ToolCallDefinitionCard";
+import { ToolCallInvocationsView } from "@/src/components/trace/ToolCallInvocationsView";
+import { ListChevronsDownUp, ListChevronsUpDown } from "lucide-react";
+import { copyTextToClipboard } from "@/src/utils/clipboard";
export const IOPreview: React.FC<{
input?: Prisma.JsonValue;
@@ -71,7 +78,15 @@ export const IOPreview: React.FC<{
const [compensateScrollRef, startPreserveScroll] =
usePreserveRelativeScroll<HTMLDivElement>([selectedView]);
- const { canDisplayAsChat, allMessages, additionalInput } = useMemo(() => {
+ const {
+ canDisplayAsChat,
+ allMessages,
+ additionalInput,
+ allTools,
+ toolCallCounts,
+ messageToToolCallNumbers,
+ toolNameToDefinitionNumber,
+ } = useMemo(() => {
const ctx = { metadata, observationName: props.observationName };
const inResult = normalizeInput(input, ctx);
const outResult = normalizeOutput(output, ctx);
@@ -82,12 +97,63 @@ export const IOPreview: React.FC<{
outputClean,
);
+ // extract all unique tools from messages and assign them sequential numbers
+ const toolsMap = new Map<
+ string,
+ { name: string; description?: string; parameters?: Record<string, any> }
+ >();
+ const toolNameToDefinitionNumber = new Map<string, number>();
+ let toolDefinitionCounter = 0;
+
+ for (const message of messages) {
+ if (message.tools && Array.isArray(message.tools)) {
+ for (const tool of message.tools) {
+ if (!toolsMap.has(tool.name)) {
+ toolsMap.set(tool.name, tool);
+ toolDefinitionCounter++;
+ toolNameToDefinitionNumber.set(tool.name, toolDefinitionCounter);
+ }
+ }
+ }
+ }
+ const uniqueTools = Array.from(toolsMap.values());
+
+ // sequential numbering for tool call invocations
+ let toolCallCounter = 0;
+ const messageToToolCallNumbers = new Map<number, number[]>();
+ const toolCallCounts = new Map<string, number>();
+
+ for (let i = 0; i < messages.length; i++) {
+ const message = messages[i];
+ if (message.tool_calls && Array.isArray(message.tool_calls)) {
+ const messageToolNumbers: number[] = [];
+
+ for (const toolCall of message.tool_calls) {
+ if (toolCall.name && typeof toolCall.name === "string") {
+ toolCallCounter++;
+ messageToolNumbers.push(toolCallCounter);
+ toolCallCounts.set(
+ toolCall.name,
+ (toolCallCounts.get(toolCall.name) || 0) + 1,
+ );
+ }
+ }
+
+ if (messageToolNumbers.length > 0) {
+ messageToToolCallNumbers.set(i, messageToolNumbers);
+ }
+ }
+ }
+
return {
- // display as chat if normalization succeeded AND we have messages to show
canDisplayAsChat:
(inResult.success || outResult.success) && messages.length > 0,
allMessages: messages,
additionalInput: extractAdditionalInput(input),
+ allTools: uniqueTools,
+ toolCallCounts,
+ messageToToolCallNumbers,
+ toolNameToDefinitionNumber,
};
}, [input, output, metadata, props.observationName]);
@@ -110,6 +176,25 @@ export const IOPreview: React.FC<{
// default I/O
return (
<>
+ {/* Show tools at the top if available */}
+ {allTools.length > 0 && (
+ <div className="mb-4 border-b border-border pb-4">
+ <div className="px-1 py-1 text-sm font-medium capitalize">Tools</div>
+ <ToolCallDefinitionCard
+ tools={allTools.sort((a, b) => {
+ const callCountA = toolCallCounts.get(a.name) || 0;
+ const callCountB = toolCallCounts.get(b.name) || 0;
+ // Sort by called status (called first), then by call count descending
+ if (callCountA > 0 && callCountB === 0) return -1;
+ if (callCountA === 0 && callCountB > 0) return 1;
+ return callCountB - callCountA;
+ })}
+ toolCallCounts={toolCallCounts}
+ toolNameToDefinitionNumber={toolNameToDefinitionNumber}
+ />
+ </div>
+ )}
+
{isPrettyViewAvailable && !currentView ? (
<div className="flex w-full flex-row justify-start">
<Tabs
@@ -151,6 +236,7 @@ export const IOPreview: React.FC<{
}
media={media ?? []}
currentView={selectedView}
+ messageToToolCallNumbers={messageToToolCallNumbers}
/>
) : (
<>
@@ -236,6 +322,13 @@ export const IOPreview: React.FC<{
);
};
+// create message title
+const getMessageTitle = (
+ message: z.infer<typeof ChatMlMessageSchema>,
+): string => {
+ return message.name ?? message.role ?? "";
+};
+
export const OpenAiMessageView: React.FC<{
messages: z.infer<typeof ChatMlArraySchema>;
title?: string;
@@ -245,6 +338,7 @@ export const OpenAiMessageView: React.FC<{
additionalInput?: Record<string, unknown>;
projectIdForPromptButtons?: string;
currentView?: "pretty" | "json";
+ messageToToolCallNumbers?: Map<number, number[]>;
}> = ({
title,
messages,
@@ -254,18 +348,43 @@ export const OpenAiMessageView: React.FC<{
additionalInput,
projectIdForPromptButtons,
currentView = "json",
+ messageToToolCallNumbers,
}) => {
const COLLAPSE_THRESHOLD = 3;
- const [isCollapsed, setCollapsed] = useState(
- collapseLongHistory && messages.length > COLLAPSE_THRESHOLD ? true : null,
- );
+
+ // stores which messages should show table view (json) instead of pretty view
+ const [showTableView, setShowTableView] = useState<Set<number>>(new Set());
+
+ const toggleTableView = (index: number) => {
+ setShowTableView((prev) => {
+ const next = new Set(prev);
+ if (next.has(index)) {
+ next.delete(index);
+ } else {
+ next.add(index);
+ }
+ return next;
+ });
+ };
const shouldRenderContent = (message: ChatMlMessageSchema) => {
- return message.content != null || !!message.audio;
+ // Don't render if content is empty string or null/undefined in ChatML view
+ // happens e.g. if an LLM only uses a tool
+ const hasContent = message.content != null && message.content !== "";
+ return hasContent || !!message.audio;
};
- const shouldRenderJson = (message: ChatMlMessageSchema) => {
- return !!message.json;
+ // TODO: removed for now, we never show additional JSON alongside the ChatML content
+ // because we now have a switch to display it. We re-add this depending on user feedback.
+ // const shouldRenderJson = (message: ChatMlMessageSchema) => {
+ // return !!message.json;
+ // };
+ const hasAdditionalData = (message: ChatMlMessageSchema) => {
+ // if anything more than role & content exists, we show the button
+ const messageKeys = Object.keys(message).filter(
+ (key) => key !== "role" && key !== "content",
+ );
+ return messageKeys.length > 0;
};
const isPlaceholderMessage = (message: ChatMlMessageSchema) => {
@@ -277,56 +396,48 @@ export const OpenAiMessageView: React.FC<{
messages.filter(
(message) =>
shouldRenderContent(message) ||
- shouldRenderJson(message) ||
+ // shouldRenderJson(message) ||
+ hasAdditionalData(message) ||
isPlaceholderMessage(message),
),
[messages],
);
+ // Initialize collapsed state based on filtered messages, we only want to show
+ // "Show X more..." if there actually are more messages to show
+ const [isCollapsed, setCollapsed] = useState(
+ collapseLongHistory && messagesToRender.length > COLLAPSE_THRESHOLD
+ ? true
+ : null,
+ );
+
return (
<div className="flex max-h-full min-h-0 flex-col gap-2">
{title && <SubHeaderLabel title={title} className="mt-1" />}
<div className="flex max-h-full min-h-0 flex-col gap-2">
<div className="flex flex-col gap-2">
{messagesToRender
+ .map((message, originalIndex) => ({ message, originalIndex }))
.filter(
- (_, i) =>
+ ({ originalIndex }) =>
// show all if not collapsed or null; show first and last n if collapsed
!isCollapsed ||
- i == 0 ||
- i > messagesToRender.length - COLLAPSE_THRESHOLD,
+ originalIndex == 0 ||
+ originalIndex > messagesToRender.length - COLLAPSE_THRESHOLD,
)
- .map((message, index) => (
- <Fragment key={index}>
- {isPlaceholderMessage(message) ? (
- <>
- <div
- style={{
- display: shouldRenderMarkdown ? "block" : "none",
- }}
- >
- <MarkdownJsonView
- title="Placeholder"
- content={message.name || "Unnamed placeholder"}
- customCodeHeaderClassName={cn("bg-primary-foreground")}
- />
- </div>
- <div
- style={{
- display: shouldRenderMarkdown ? "none" : "block",
- }}
- >
- <PrettyJsonView
- title="Placeholder"
- json={message.name || "Unnamed placeholder"}
- projectIdForPromptButtons={projectIdForPromptButtons}
- currentView={currentView}
- />
- </div>
- </>
- ) : (
- <>
- {shouldRenderContent(message) && (
+ .map(({ message, originalIndex }) => {
+ // Check if user toggled to table view
+ const isShowingTable = showTableView.has(originalIndex);
+ return (
+ <>
+ <div
+ key={originalIndex}
+ className={cn(
+ "transition-colors hover:bg-muted",
+ !isShowingTable && "group",
+ )}
+ >
+ {isPlaceholderMessage(message) ? (
<>
<div
style={{
@@ -334,19 +445,11 @@ export const OpenAiMessageView: React.FC<{
}}
>
<MarkdownJsonView
- title={message.name ?? message.role}
- content={message.content || '""'}
- className={cn(
- !!message.json &&
- !isPlaceholderMessage(message) &&
- "rounded-b-none",
- )}
+ title="Placeholder"
+ content={message.name || "Unnamed placeholder"}
customCodeHeaderClassName={cn(
- message.role === "assistant" && "bg-secondary",
- message.role === "system" &&
- "bg-primary-foreground",
+ "bg-primary-foreground",
)}
- audio={message.audio}
/>
</div>
<div
@@ -355,52 +458,187 @@ export const OpenAiMessageView: React.FC<{
}}
>
<PrettyJsonView
- title={message.name ?? message.role}
- json={message.content}
+ title="Placeholder"
+ json={message.name || "Unnamed placeholder"}
projectIdForPromptButtons={
projectIdForPromptButtons
}
- className={cn(
- !!message.json &&
- !isPlaceholderMessage(message) &&
- "rounded-b-none",
- )}
currentView={currentView}
/>
</div>
</>
- )}
- {shouldRenderJson(message) &&
- !isPlaceholderMessage(message) && (
- <PrettyJsonView
- title={
- message.content
- ? undefined
- : (message.name ?? message.role)
- }
- json={message.json}
- projectIdForPromptButtons={projectIdForPromptButtons}
- className={cn(
- !!message.content && "rounded-t-none border-t-0",
+ ) : (
+ <>
+ {shouldRenderContent(message) &&
+ !showTableView.has(originalIndex) && (
+ <>
+ <div
+ style={{
+ display: shouldRenderMarkdown
+ ? "block"
+ : "none",
+ }}
+ >
+ <MarkdownJsonView
+ title={getMessageTitle(message)}
+ content={message.content || '""'}
+ customCodeHeaderClassName={cn(
+ message.role === "assistant" &&
+ "bg-secondary",
+ message.role === "system" &&
+ "bg-primary-foreground",
+ )}
+ audio={message.audio}
+ controlButtons={
+ hasAdditionalData(message) ? (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ onClick={() =>
+ toggleTableView(originalIndex)
+ }
+ title="Show full message data"
+ className="-mr-2 hover:bg-border"
+ >
+ <ListChevronsUpDown className="h-3 w-3" />
+ </Button>
+ ) : undefined
+ }
+ />
+ {message.tool_calls &&
+ Array.isArray(message.tool_calls) &&
+ message.tool_calls.length > 0 && (
+ <div className="mt-2">
+ <ToolCallInvocationsView
+ message={message}
+ toolCallNumbers={messageToToolCallNumbers?.get(
+ originalIndex,
+ )}
+ />
+ </div>
+ )}
+ </div>
+ <div
+ style={{
+ display: shouldRenderMarkdown
+ ? "none"
+ : "block",
+ }}
+ >
+ <PrettyJsonView
+ title={getMessageTitle(message)}
+ json={message.content}
+ projectIdForPromptButtons={
+ projectIdForPromptButtons
+ }
+ currentView={currentView}
+ controlButtons={
+ hasAdditionalData(message) ? (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ onClick={() =>
+ toggleTableView(originalIndex)
+ }
+ title="Show full message data"
+ className="-mr-2 hover:bg-border"
+ >
+ <ListChevronsUpDown className="h-3 w-3" />
+ </Button>
+ ) : undefined
+ }
+ />
+ {message.tool_calls &&
+ Array.isArray(message.tool_calls) &&
+ message.tool_calls.length > 0 && (
+ <div className="mt-2">
+ <ToolCallInvocationsView
+ message={message}
+ toolCallNumbers={messageToToolCallNumbers?.get(
+ originalIndex,
+ )}
+ />
+ </div>
+ )}
+ </div>
+ </>
)}
- currentView={shouldRenderMarkdown ? "pretty" : "json"}
- />
- )}
- </>
- )}
- {isCollapsed !== null && index === 0 ? (
- <Button
- variant="ghost"
- size="xs"
- onClick={() => setCollapsed((v) => !v)}
- >
- {isCollapsed
- ? `Show ${messagesToRender.length - COLLAPSE_THRESHOLD} more ...`
- : "Hide history"}
- </Button>
- ) : null}
- </Fragment>
- ))}
+ {isShowingTable ? (
+ // User clicked toggle - show full JSON
+ <PrettyJsonView
+ title={getMessageTitle(message)}
+ json={message}
+ projectIdForPromptButtons={
+ projectIdForPromptButtons
+ }
+ currentView="pretty"
+ controlButtons={
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ onClick={() => toggleTableView(originalIndex)}
+ title="Show formatted view"
+ className="-mr-2 hover:bg-border"
+ >
+ <ListChevronsDownUp className="h-3 w-3 text-primary" />
+ </Button>
+ }
+ />
+ ) : !shouldRenderContent(message) &&
+ message.tool_calls &&
+ Array.isArray(message.tool_calls) &&
+ message.tool_calls.length > 0 ? (
+ // No content but has tool_calls - show tool invocations
+ <div>
+ <MarkdownJsonViewHeader
+ title={getMessageTitle(message)}
+ handleOnValueChange={() => {}}
+ handleOnCopy={() => {
+ const rawText = JSON.stringify(
+ message,
+ null,
+ 2,
+ );
+ void copyTextToClipboard(rawText);
+ }}
+ controlButtons={
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ onClick={() => toggleTableView(originalIndex)}
+ title="Show full message data"
+ className="-mr-2 hover:bg-border"
+ >
+ <ListChevronsUpDown className="h-3 w-3" />
+ </Button>
+ }
+ />
+ <ToolCallInvocationsView
+ message={message}
+ toolCallNumbers={messageToToolCallNumbers?.get(
+ originalIndex,
+ )}
+ />
+ </div>
+ ) : null}
+ </>
+ )}
+ </div>
+ {isCollapsed !== null && originalIndex === 0 ? (
+ <Button
+ variant="ghost"
+ size="xs"
+ onClick={() => setCollapsed((v) => !v)}
+ className="underline"
+ >
+ {isCollapsed
+ ? `Show ${messagesToRender.length - COLLAPSE_THRESHOLD} more ...`
+ : "Hide history"}
+ </Button>
+ ) : null}
+ </>
+ );
+ })}
</div>
{additionalInput && (
<PrettyJsonView
diff --git a/web/src/components/trace/ObservationPreview.tsx b/web/src/components/trace/ObservationPreview.tsx
index d5699e98e3..5e47da9bda 100644
--- a/web/src/components/trace/ObservationPreview.tsx
+++ b/web/src/components/trace/ObservationPreview.tsx
@@ -420,6 +420,7 @@ export const ObservationPreview = ({
<div>
<IOPreview
key={preloadedObservation.id + "-input"}
+ observationName={preloadedObservation.name ?? undefined}
input={observationWithInputAndOutput.data?.input ?? undefined}
output={
observationWithInputAndOutput.data?.output ?? undefined
diff --git a/web/src/components/trace/ToolCallDefinitionCard.tsx b/web/src/components/trace/ToolCallDefinitionCard.tsx
new file mode 100644
index 0000000000..1d2cb61965
--- /dev/null
+++ b/web/src/components/trace/ToolCallDefinitionCard.tsx
@@ -0,0 +1,176 @@
+import { ChevronRight, ChevronDown, Wrench } from "lucide-react";
+import { Badge } from "@/src/components/ui/badge";
+import { cn } from "@/src/utils/tailwind";
+import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";
+import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
+import useLocalStorage from "@/src/components/useLocalStorage";
+import { useState } from "react";
+
+interface ToolDefinition {
+ name: string;
+ description?: string;
+ parameters?: Record<string, any>;
+}
+
+interface ToolCallDefinitionCardProps {
+ tools: ToolDefinition[];
+ toolCallCounts: Map<string, number>;
+ toolNameToDefinitionNumber?: Map<string, number>;
+ className?: string;
+}
+
+export function ToolCallDefinitionCard({
+ tools,
+ toolCallCounts,
+ toolNameToDefinitionNumber,
+ className,
+}: ToolCallDefinitionCardProps) {
+ const [expandedIndex, setExpandedIndex] = useState<number | null>(null);
+ const [currentView, setCurrentView] = useLocalStorage<"formatted" | "json">(
+ "toolCallPillViewPreference",
+ "formatted",
+ );
+
+ if (!tools || tools.length === 0) {
+ return null;
+ }
+
+ return (
+ <div className={cn("flex flex-col gap-2", className)}>
+ {tools.map((tool, index) => {
+ const isExpanded = expandedIndex === index;
+ const callCount = toolCallCounts.get(tool.name) || 0;
+ const isCalled = callCount > 0;
+ const toolDefinitionNumber = toolNameToDefinitionNumber?.get(tool.name);
+ const statusText =
+ callCount === 0
+ ? "not called"
+ : callCount === 1
+ ? "called"
+ : `called ${callCount}x`;
+
+ return (
+ <div
+ key={`${tool.name}-${index}`}
+ className="w-full overflow-hidden rounded-sm border"
+ >
+ {/* Card header */}
+ <div
+ className="flex w-full cursor-pointer items-center justify-between gap-2 px-3 py-1.5 hover:bg-muted/20"
+ onClick={() => {
+ setExpandedIndex(isExpanded ? null : index);
+ }}
+ >
+ {/* Left: Tool icon + definition number + name */}
+ <div className="flex items-center gap-2">
+ <Wrench className="h-3.5 w-3.5 text-muted-foreground" />
+ <span className="font-mono text-xs font-medium text-foreground">
+ {toolDefinitionNumber !== undefined && (
+ <span className="mr-1">{toolDefinitionNumber}.</span>
+ )}
+ {tool.name}
+ </span>
+ </div>
+
+ {/* Right: Status badge + chevron indicator */}
+ <div className="flex items-center gap-1.5">
+ <Badge
+ variant={isCalled ? undefined : "secondary"}
+ className={cn(
+ "text-xs font-medium",
+ isCalled &&
+ "border-transparent bg-light-green text-dark-green hover:bg-light-green",
+ )}
+ >
+ {statusText}
+ </Badge>
+
+ {/* Chevron indicator */}
+ {isExpanded ? (
+ <ChevronDown className="h-3.5 w-3.5 text-muted-foreground" />
+ ) : (
+ <ChevronRight className="h-3.5 w-3.5 text-muted-foreground" />
+ )}
+ </div>
+ </div>
+
+ {/* Expanded details view */}
+ {isExpanded && (
+ <div className="relative border-t border-border bg-muted/30 px-4 py-3">
+ {/* View toggle tabs - positioned top right */}
+ <div className="absolute right-4 top-1">
+ <Tabs
+ className="h-fit py-0.5"
+ value={currentView}
+ onValueChange={(value) =>
+ setCurrentView(value as "formatted" | "json")
+ }
+ >
+ <TabsList className="h-fit p-0.5">
+ <TabsTrigger
+ value="formatted"
+ className="h-fit px-1 text-xs"
+ >
+ Formatted
+ </TabsTrigger>
+ <TabsTrigger value="json" className="h-fit px-1 text-xs">
+ JSON
+ </TabsTrigger>
+ </TabsList>
+ </Tabs>
+ </div>
+
+ {/* Formatted view */}
+ {currentView === "formatted" && (
+ <div className="space-y-4">
+ {/* Description */}
+ {tool.description && (
+ <div>
+ <div className="mb-1.5 text-xs font-medium text-muted-foreground">
+ Description
+ </div>
+ <div className="text-sm text-foreground">
+ {tool.description}
+ </div>
+ </div>
+ )}
+
+ {/* Parameters */}
+ {tool.parameters && (
+ <div>
+ <div className="mb-1.5 text-xs font-medium text-muted-foreground">
+ Parameters
+ </div>
+ <PrettyJsonView
+ json={tool.parameters}
+ currentView="pretty"
+ codeClassName="text-xs"
+ />
+ </div>
+ )}
+
+ {/* Show message if no additional details */}
+ {!tool.description && !tool.parameters && (
+ <div className="text-sm text-muted-foreground">
+ No additional details available
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* JSON view - full tool object */}
+ {currentView === "json" && (
+ <PrettyJsonView
+ json={tool}
+ currentView="json"
+ codeClassName="text-xs"
+ />
+ )}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/web/src/components/trace/ToolCallInvocationsView.tsx b/web/src/components/trace/ToolCallInvocationsView.tsx
new file mode 100644
index 0000000000..f4f5b5528b
--- /dev/null
+++ b/web/src/components/trace/ToolCallInvocationsView.tsx
@@ -0,0 +1,87 @@
+import { Wrench } from "lucide-react";
+import { cn } from "@/src/utils/tailwind";
+import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";
+import type { z } from "zod/v4";
+import type { ChatMlMessageSchema } from "@/src/components/schemas/ChatMlSchema";
+
+interface ToolCallInvocationsViewProps {
+ message: z.infer<typeof ChatMlMessageSchema>;
+ toolCallNumbers?: number[];
+ className?: string;
+}
+
+export function ToolCallInvocationsView({
+ message,
+ toolCallNumbers,
+ className,
+}: ToolCallInvocationsViewProps) {
+ const toolCalls = message.tool_calls;
+
+ if (!toolCalls || !Array.isArray(toolCalls) || toolCalls.length === 0) {
+ return null;
+ }
+
+ return (
+ <div className={cn("flex flex-col gap-2", className)}>
+ {toolCalls.map((toolCall, index) => {
+ const invocationNumber = toolCallNumbers?.[index];
+ // Parse arguments if they're a JSON string
+ let parsedArguments = toolCall.arguments;
+ if (typeof toolCall.arguments === "string") {
+ try {
+ parsedArguments = JSON.parse(toolCall.arguments);
+ } catch {
+ // Keep as string if parsing fails
+ parsedArguments = toolCall.arguments;
+ }
+ }
+
+ return (
+ <div
+ key={`${toolCall.id}-${index}`}
+ className={cn(
+ "w-full border-t px-1 py-2",
+ (message.role === "assistant" ||
+ message.name === "Output" ||
+ message.name === "Model") &&
+ "bg-accent-light-green",
+ )}
+ >
+ {/* Card header */}
+ <div className="flex w-full items-center justify-between gap-2 py-1">
+ {/* Left: Tool icon + number + name */}
+ <div className="flex items-center gap-2">
+ <Wrench className="h-3.5 w-3.5 text-muted-foreground" />
+ <span className="font-mono text-xs font-medium text-foreground">
+ {invocationNumber !== undefined && (
+ <span className="mr-1">{invocationNumber}.</span>
+ )}
+ {toolCall.name}
+ </span>
+ </div>
+
+ {/* Right: Call ID if available */}
+ {toolCall.id && (
+ <span className="font-mono text-xs text-muted-foreground">
+ {toolCall.id}
+ </span>
+ )}
+ </div>
+
+ {/* Arguments view */}
+ <div className="py-2">
+ <div className="mb-1.5 text-xs font-medium text-muted-foreground">
+ Arguments
+ </div>
+ <PrettyJsonView
+ json={parsedArguments}
+ currentView="pretty"
+ codeClassName="text-xs"
+ />
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/web/src/components/ui/CodeJsonViewer.tsx b/web/src/components/ui/CodeJsonViewer.tsx
index 74bfad0d9a..3e7f1f6db1 100644
--- a/web/src/components/ui/CodeJsonViewer.tsx
+++ b/web/src/components/ui/CodeJsonViewer.tsx
@@ -111,6 +111,7 @@ export function JSONView(props: {
src={parsedJson}
theme="github"
dark={resolvedTheme === "dark"}
+ collapsed={isCollapsed ? 1 : false}
collapseObjectsAfterLength={isCollapsed ? 0 : 20}
collapseStringsAfterLength={collapseStringsAfterLength}
collapseStringMode="word"
diff --git a/web/src/components/ui/MarkdownJsonView.tsx b/web/src/components/ui/MarkdownJsonView.tsx
index 966c959a31..c74402047b 100644
--- a/web/src/components/ui/MarkdownJsonView.tsx
+++ b/web/src/components/ui/MarkdownJsonView.tsx
@@ -14,6 +14,7 @@ import { MARKDOWN_RENDER_CHARACTER_LIMIT } from "@/src/utils/constants";
type MarkdownJsonViewHeaderProps = {
title: string;
+ titleIcon?: React.ReactNode;
handleOnValueChange: () => void;
handleOnCopy: (event?: React.MouseEvent<HTMLButtonElement>) => void;
canEnableMarkdown?: boolean;
@@ -22,6 +23,7 @@ type MarkdownJsonViewHeaderProps = {
export function MarkdownJsonViewHeader({
title,
+ titleIcon,
handleOnValueChange: _handleOnValueChange,
handleOnCopy,
canEnableMarkdown: _canEnableMarkdown = true,
@@ -30,8 +32,11 @@ export function MarkdownJsonViewHeader({
const [isCopied, setIsCopied] = useState(false);
return (
- <div className="flex flex-row items-center justify-between px-1 py-1 text-sm font-medium capitalize">
- {title}
+ <div className="flex flex-row items-center justify-between px-1 py-1 text-sm font-medium capitalize transition-colors group-hover:bg-muted/80">
+ <div className="flex items-center gap-2">
+ {titleIcon}
+ {title}
+ </div>
<div className="mr-1 flex min-w-0 flex-shrink flex-row items-center gap-1">
{controlButtons}
<Button
@@ -77,17 +82,21 @@ const isSupportedMarkdownFormat = (
export function MarkdownJsonView({
content,
title,
+ titleIcon,
className,
customCodeHeaderClassName,
audio,
media,
+ controlButtons,
}: {
content?: unknown;
title?: string;
+ titleIcon?: React.ReactNode;
className?: string;
customCodeHeaderClassName?: string;
audio?: OpenAIOutputAudioType;
media?: MediaReturnType[];
+ controlButtons?: React.ReactNode;
}) {
const stringOrValidatedMarkdown = useMemo(
() => StringOrMarkdownSchema.safeParse(content),
@@ -109,17 +118,21 @@ export function MarkdownJsonView({
<MarkdownView
markdown={stringOrValidatedMarkdown.data ?? content}
title={title}
+ titleIcon={titleIcon}
customCodeHeaderClassName={customCodeHeaderClassName}
audio={audio}
media={media}
+ controlButtons={controlButtons}
/>
) : (
<PrettyJsonView
json={content ?? (audio ? { audio } : null)}
title={title}
+ titleIcon={titleIcon}
className={className}
media={media}
currentView="pretty"
+ controlButtons={controlButtons}
/>
)}
</>
diff --git a/web/src/components/ui/MarkdownViewer.tsx b/web/src/components/ui/MarkdownViewer.tsx
index 2aab88dfb1..4a9e18bc8c 100644
--- a/web/src/components/ui/MarkdownViewer.tsx
+++ b/web/src/components/ui/MarkdownViewer.tsx
@@ -313,17 +313,21 @@ const parseOpenAIContentParts = (
export function MarkdownView({
markdown,
title,
+ titleIcon,
customCodeHeaderClassName,
audio,
media,
className,
+ controlButtons,
}: {
markdown: string | z.infer<typeof OpenAIContentSchema>;
title?: string;
+ titleIcon?: React.ReactNode;
customCodeHeaderClassName?: string;
audio?: OpenAIOutputAudioType;
media?: MediaReturnType[];
className?: string;
+ controlButtons?: React.ReactNode;
}) {
const capture = usePostHogClientCapture();
const { resolvedTheme: theme } = useTheme();
@@ -349,15 +353,17 @@ export function MarkdownView({
{title ? (
<MarkdownJsonViewHeader
title={title}
+ titleIcon={titleIcon}
handleOnValueChange={handleOnValueChange}
handleOnCopy={handleOnCopy}
+ controlButtons={controlButtons}
/>
) : null}
<div
className={cn(
- "grid grid-flow-row gap-2 rounded-sm border p-3",
- title === "assistant" || title === "Output"
- ? "bg-accent-light-green dark:border-accent-dark-green"
+ "grid grid-flow-row gap-2 border-t px-1 py-3",
+ title === "assistant" || title === "Output" || title === "Model"
+ ? "bg-accent-light-green"
: "",
title === "system" || title === "Input"
? "bg-primary-foreground"
diff --git a/web/src/components/ui/PrettyJsonView.tsx b/web/src/components/ui/PrettyJsonView.tsx
index 4e9c33c4f2..3320b9983e 100644
--- a/web/src/components/ui/PrettyJsonView.tsx
+++ b/web/src/components/ui/PrettyJsonView.tsx
@@ -695,6 +695,7 @@ function JsonPrettyTable({
export function PrettyJsonView(props: {
json?: unknown;
title?: string;
+ titleIcon?: React.ReactNode;
className?: string;
isLoading?: boolean;
codeClassName?: string;
@@ -1154,12 +1155,12 @@ export function PrettyJsonView(props: {
{props.title ? (
<MarkdownJsonViewHeader
title={props.title}
+ titleIcon={props.titleIcon}
canEnableMarkdown={false}
handleOnValueChange={() => {}} // No-op, parent handles state
handleOnCopy={handleOnCopy}
controlButtons={
<>
- {props.controlButtons}
{shouldUseTableView && (
<Button
variant="ghost"
@@ -1177,7 +1178,7 @@ export function PrettyJsonView(props: {
)}
</Button>
)}
- {!isPrettyView && (
+ {!shouldUseTableView && !isMarkdownMode && (
<Button
variant="ghost"
size="icon-xs"
@@ -1192,6 +1193,7 @@ export function PrettyJsonView(props: {
)}
</Button>
)}
+ {props.controlButtons}
</>
}
/>
diff --git a/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx b/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
index 656ad505bf..768d8b3196 100644
--- a/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
+++ b/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
@@ -258,7 +258,7 @@ const parseGeneration = (
if (!isGenerationLike(generation.type)) return null;
let modelParams = parseModelParams(generation, modelToProviderMap);
- const tools = parseTools(generation.input);
+ const tools = parseTools(generation.input, generation.metadata);
const structuredOutputSchema = parseStructuredOutputSchema(generation);
const providerOptions = parseLitellmMetadataFromGeneration(generation);
@@ -400,12 +400,16 @@ function parseModelParams(
return modelParams;
}
-function parseTools(inputString: string | null): PlaygroundTool[] {
- if (!inputString) return [];
+function parseTools(
+ inputString: string | null,
+ metadataString: string | null,
+): PlaygroundTool[] {
+ if (!inputString && !metadataString) return [];
try {
- const input = JSON.parse(inputString);
- return extractTools(input);
+ const input = inputString ? JSON.parse(inputString) : null;
+ const metadata = metadataString ? JSON.parse(metadataString) : null;
+ return extractTools(input, metadata);
} catch {
return [];
}
diff --git a/web/src/utils/chatml/adapters/gemini.clienttest.ts b/web/src/utils/chatml/adapters/gemini.clienttest.ts
index b6ef67fcb6..e6ea8e6b84 100644
--- a/web/src/utils/chatml/adapters/gemini.clienttest.ts
+++ b/web/src/utils/chatml/adapters/gemini.clienttest.ts
@@ -1,5 +1,6 @@
import { geminiAdapter } from "./gemini";
import type { NormalizerContext } from "../types";
+import { normalizeInput } from "./index";
describe("geminiAdapter", () => {
describe("detect", () => {
@@ -24,25 +25,6 @@ describe("geminiAdapter", () => {
expect(geminiAdapter.detect(ctx as NormalizerContext)).toBe(true);
});
- it("should detect via structural analysis (tool definitions in messages)", () => {
- const ctx: NormalizerContext = {
- metadata: {
- messages: [
- { role: "system", content: "System prompt" },
- {
- role: "tool",
- content: {
- type: "function",
- function: { name: "get_weather", description: "Get weather" },
- },
- },
- ],
- },
- };
-
- expect(geminiAdapter.detect(ctx)).toBe(true);
- });
-
it("should not detect non-Gemini formats", () => {
expect(
geminiAdapter.detect({ metadata: { ls_provider: "openai" } }),
@@ -51,52 +33,26 @@ describe("geminiAdapter", () => {
false,
);
expect(geminiAdapter.detect({})).toBe(false);
- });
- });
- describe("preprocess", () => {
- it("should filter tool definitions and normalize structured content", () => {
- const input = [
- { role: "system", content: "System prompt" },
- {
- role: "assistant",
- content: [
- { type: "text", text: "Hello! " },
- { type: "text", text: "How can I help?" },
- ],
- },
- {
- role: "tool",
- content: {
- type: "function",
- function: {
- name: "get_weather",
- description: "Get weather",
- parameters: {},
+ // Should reject Microsoft Agent format (parts without contents wrapper)
+ expect(
+ geminiAdapter.detect({
+ metadata: [
+ {
+ role: "user",
+ parts: [{ type: "text", content: "Hello" }],
},
- },
- },
- {
- role: "user",
- content: [{ type: "text", text: "What's the weather?" }],
- },
- ];
-
- const result = geminiAdapter.preprocess(input, "input", {}) as any[];
-
- // Tool definition filtered out
- expect(result.length).toBe(3);
-
- // Content normalized from structured to plain text
- expect(result[0].content).toBe("System prompt");
- expect(result[1].content).toBe("Hello! How can I help?");
- expect(result[2].content).toBe("What's the weather?");
+ ],
+ }),
+ ).toBe(false);
});
+ });
+ describe("preprocess", () => {
it("should preserve tool result messages (not filter them)", () => {
const input = [
{
- role: "assistant",
+ role: "model",
content: [{ type: "text", text: "Let me check." }],
},
{
@@ -117,7 +73,7 @@ describe("geminiAdapter", () => {
it("should stringify object content in tool result messages", () => {
const input = [
{
- role: "assistant",
+ role: "model",
content: [{ type: "text", text: "Let me check." }],
},
{
@@ -147,37 +103,10 @@ describe("geminiAdapter", () => {
expect(result[1].tool_call_id).toBe("call_xyz789");
});
- it("should handle input wrapped in messages field", () => {
- const input = {
- messages: [
- { role: "system", content: "System" },
- {
- role: "tool",
- content: {
- type: "function",
- function: { name: "tool1", description: "Tool 1" },
- },
- },
- {
- role: "user",
- content: [{ type: "text", text: "User message" }],
- },
- ],
- extra: "metadata",
- };
-
- const result = geminiAdapter.preprocess(input, "input", {}) as any;
-
- expect(result.messages.length).toBe(2);
- expect(result.messages[0].content).toBe("System");
- expect(result.messages[1].content).toBe("User message");
- expect(result.extra).toBe("metadata");
- });
-
- it("should normalize tool_calls from Gemini format to OpenAI format", () => {
+ it("should normalize tool_calls from Gemini format to flat ChatML format", () => {
const input = [
{
- role: "assistant",
+ role: "model",
content: "",
tool_calls: [
{
@@ -196,24 +125,105 @@ describe("geminiAdapter", () => {
const result = geminiAdapter.preprocess(input, "input", {}) as any[];
expect(result.length).toBe(1);
- expect(result[0].role).toBe("assistant");
+ expect(result[0].role).toBe("model");
expect(result[0].tool_calls).toBeDefined();
expect(result[0].tool_calls.length).toBe(1);
// Should be normalized to our ChatML format
const toolCall = result[0].tool_calls[0];
expect(toolCall.id).toBe("call_abc123");
+ // previous, before flattinging
+ // TODO: remove
+ // expect(toolCall.function).toBeDefined();
+ // expect(toolCall.function.name).toBe("get_weather");
+ // expect(typeof toolCall.function.arguments).toBe("string");
expect(toolCall.type).toBe("function");
- expect(toolCall.function).toBeDefined();
- expect(toolCall.function.name).toBe("get_weather");
- expect(typeof toolCall.function.arguments).toBe("string");
- expect(toolCall.function.arguments).toBe(
+ expect(toolCall.name).toBe("get_weather");
+ expect(typeof toolCall.arguments).toBe("string");
+ expect(toolCall.arguments).toBe(
JSON.stringify({ location: "San Francisco", unit: "celsius" }),
);
// Old fields should be removed
- expect(toolCall.name).toBeUndefined();
expect(toolCall.args).toBeUndefined();
});
+
+ it("should handle Google ADK format with tool calls and function responses", () => {
+ // This is the format from google-adk-2025-08-28.json
+ const input = {
+ model: "gemini-2.0-flash",
+ config: {
+ system_instruction: "Always greet using the say_hello tool.",
+ tools: [
+ {
+ function_declarations: [
+ {
+ name: "say_hello",
+ description: "Greet the user",
+ },
+ ],
+ },
+ ],
+ },
+ contents: [
+ {
+ parts: [{ text: "hi" }],
+ role: "user",
+ },
+ {
+ parts: [
+ {
+ function_call: {
+ args: {},
+ name: "say_hello",
+ },
+ },
+ ],
+ role: "model",
+ },
+ {
+ parts: [
+ {
+ function_response: {
+ name: "say_hello",
+ response: {
+ greeting: "Hello Langfuse 👋",
+ },
+ },
+ },
+ ],
+ role: "user",
+ },
+ ],
+ };
+
+ const result = normalizeInput(input, { framework: "gemini" });
+ expect(result.success).toBe(true);
+ expect(result.data).toHaveLength(4);
+
+ // First message: system instruction
+ expect(result.data?.[0].role).toBe("system");
+ expect(result.data?.[0].content).toBe(
+ "Always greet using the say_hello tool.",
+ );
+ expect(result.data?.[0].tools).toBeDefined();
+ expect(result.data?.[0].tools?.[0].name).toBe("say_hello");
+
+ // Second message: user text
+ expect(result.data?.[1].role).toBe("user");
+ expect(result.data?.[1].content).toBe("hi");
+ expect(result.data?.[1].tools).toBeDefined();
+ expect(result.data?.[1].tools?.[0].name).toBe("say_hello");
+
+ // Third message: assistant with tool_call, not normalized
+ expect(result.data?.[2].role).toBe("model");
+ expect(result.data?.[2].tool_calls).toBeDefined();
+ expect(result.data?.[2].tool_calls?.[0].name).toBe("say_hello");
+ expect(result.data?.[2].tool_calls?.[0].arguments).toBe("{}");
+
+ // Fourth message: tool result
+ expect(result.data?.[3].role).toBe("user");
+ expect(result.data?.[3].content).toBeDefined();
+ });
});
});
diff --git a/web/src/utils/chatml/adapters/gemini.ts b/web/src/utils/chatml/adapters/gemini.ts
index bbd3db7738..3ef48bd844 100644
--- a/web/src/utils/chatml/adapters/gemini.ts
+++ b/web/src/utils/chatml/adapters/gemini.ts
@@ -1,111 +1,281 @@
import type { NormalizerContext, ProviderAdapter } from "../types";
import { parseMetadata, stringifyToolResultContent } from "../helpers";
+import { z } from "zod/v4";
-export function isGeminiToolDefinition(msg: unknown): boolean {
- if (!msg || typeof msg !== "object") return false;
+/**
+ * Detection schemas for Gemini/VertexAI formats
+ *
+ * Two main format families (inner structure is identical):
+ * 1. Raw Gemini API (Vertex): {candidates: [{content: {parts, role}}]}
+ * 2. Google ADK: {content: {parts, role}} or {config, contents: [{parts, role}]}
+ */
- const message = msg as Record<string, unknown>;
+// Raw Gemini API response: {candidates: [{content: {...}}]}
+const GeminiRawAPISchema = z.looseObject({
+ candidates: z.array(
+ z.looseObject({
+ content: z.looseObject({
+ parts: z.array(z.any()).optional(),
+ role: z.string().optional(),
+ }),
+ }),
+ ),
+});
- // Gemini tool definitions have:
- // - role: "tool"
- // - content.type: "function"
- // - content.function: {name, description, parameters}
- return (
- message.role === "tool" &&
- typeof message.content === "object" &&
- message.content !== null &&
- !Array.isArray(message.content) &&
- (message.content as Record<string, unknown>).type === "function" &&
- !!(message.content as Record<string, unknown>).function
- );
-}
+// ADK output format: {content: {parts: [...], role: "..."}}
+const GeminiADKOutputSchema = z.looseObject({
+ content: z.looseObject({
+ parts: z.array(z.any()),
+ role: z.string(),
+ }),
+});
-export function extractGeminiToolDefinitions(messages: unknown[]): Array<{
- name: string;
- description: string;
- parameters: Record<string, unknown>;
-}> {
- return messages.filter(isGeminiToolDefinition).map((msg) => {
- const message = msg as Record<string, unknown>;
- const func = (message.content as Record<string, unknown>)
- .function as Record<string, unknown>;
- return {
- name: (func.name as string) || "",
- description: (func.description as string) || "",
- parameters: (func.parameters as Record<string, unknown>) || {},
- };
- });
+// ADK input format: {config: {tools, system_instruction}, contents: [...]}
+const GeminiADKInputSchema = z.looseObject({
+ config: z.looseObject({
+ tools: z.array(z.any()).optional(),
+ system_instruction: z.string().optional(),
+ }),
+ contents: z.array(z.any()),
+});
+
+// Simple request format: {contents: [{parts: [...], role: "..."}]}
+const GeminiRequestSchema = z.looseObject({
+ contents: z.array(
+ z.looseObject({
+ parts: z.array(z.any()),
+ role: z.string().optional(),
+ }),
+ ),
+});
+
+/**
+ * Case-insensitive field accessor
+ * Handles both snake_case and camelCase (e.g., function_call OR functionCall)
+ */
+function getField(obj: unknown, snakeName: string, camelName: string): unknown {
+ if (!obj || typeof obj !== "object") return undefined;
+ const o = obj as Record<string, unknown>;
+ return o[snakeName] ?? o[camelName];
}
-function normalizeToolCall(toolCall: unknown): Record<string, unknown> {
- if (!toolCall || typeof toolCall !== "object") return {};
+// Note: Gemini tools come from config.tools with function_declarations, not from messages
+// The format {role: "tool", content: {type: "function"}} is LangGraph, handled by langgraph adapter
- const tc = toolCall as Record<string, unknown>;
+/**
+ * Extract both tool calls and text from parts array
+ * Handles: function_call/functionCall, text, function_response/functionResponse
+ * snake_case is from python SDK while camelCase is from JavaScript SDK / REST
+ */
+function extractFromParts(parts: unknown[]): {
+ toolCalls: Array<Record<string, unknown>>;
+ text: string;
+} {
+ const toolCalls: Array<Record<string, unknown>> = [];
+ const textParts: string[] = [];
- // is Gemini format?: {name, args, id, type: "tool_call"}
- if (tc.type === "tool_call" && tc.name && "args" in tc) {
- // Convert to our ChatML / OpenAI format: {id, type: "function", function: {name, arguments}}
- return {
- id: tc.id,
- type: "function",
- function: {
- name: tc.name,
+ for (const part of parts) {
+ if (typeof part === "string") {
+ textParts.push(part);
+ continue;
+ }
+ if (!part || typeof part !== "object") continue;
+
+ const p = part as Record<string, unknown>;
+
+ // Check for function_call OR functionCall (case-insensitive)
+ const fc = getField(p, "function_call", "functionCall");
+ if (fc && typeof fc === "object") {
+ const functionCall = fc as Record<string, unknown>;
+ toolCalls.push({
+ id: functionCall.id || "",
+ name: functionCall.name,
arguments:
- typeof tc.args === "string" ? tc.args : JSON.stringify(tc.args ?? {}),
- },
- };
+ typeof functionCall.args === "string"
+ ? functionCall.args
+ : JSON.stringify(functionCall.args ?? {}),
+ type: "function",
+ });
+ continue;
+ }
+
+ // {text: "..."} or {type: "text", text: "..."}
+ if (typeof p.text === "string") {
+ textParts.push(p.text);
+ continue;
+ }
+
+ // {function_response: {name, response}} OR {functionResponse: {name, response}}
+ const fr = getField(p, "function_response", "functionResponse");
+ if (fr && typeof fr === "object") {
+ const functionResponse = fr as Record<string, unknown>;
+ textParts.push(JSON.stringify(functionResponse.response || {}));
+ }
}
- return tc;
+ return {
+ toolCalls,
+ text: textParts.join(""),
+ };
}
+/**
+ * Extract tool declarations from Google ADK tools array
+ * Handles: {function_declarations: [{name, description, parameters}]}
+ */
+function extractToolDeclarations(tools: unknown[]): Array<{
+ name: string;
+ description?: string;
+ parameters?: Record<string, unknown>;
+}> {
+ const declarations: Array<{
+ name: string;
+ description?: string;
+ parameters?: Record<string, unknown>;
+ }> = [];
+
+ for (const tool of tools) {
+ if (!tool || typeof tool !== "object") continue;
+ const t = tool as Record<string, unknown>;
+
+ // Check for function_declarations OR functionDeclarations
+ const fd = getField(t, "function_declarations", "functionDeclarations");
+ if (fd && Array.isArray(fd)) {
+ for (const decl of fd as Array<Record<string, unknown>>) {
+ const toolDef: Record<string, unknown> = {
+ name: (decl.name as string) || "",
+ };
+ if (decl.description !== null && decl.description !== undefined) {
+ toolDef.description = decl.description;
+ }
+ if (decl.parameters !== null && decl.parameters !== undefined) {
+ toolDef.parameters = decl.parameters;
+ }
+ declarations.push(
+ toolDef as {
+ name: string;
+ description?: string;
+ parameters?: Record<string, unknown>;
+ },
+ );
+ }
+ }
+ }
+
+ return declarations;
+}
+
+// normalize a single Gemini message to ChatML format
function normalizeGeminiMessage(msg: unknown): Record<string, unknown> {
if (!msg || typeof msg !== "object") return {};
const message = msg as Record<string, unknown>;
- const normalized = { ...message };
+ let normalized = { ...message };
+
+ // convert Gemini "model" role → "assistant"
+ // if (message.role === "model") {
+ // normalized.role = "assistant";
+ // }
+
+ // handle direct tool call message format
+ // {type: "tool_call", name: "...", args: {...}} → {role: "assistant", tool_calls: [...]}
+ if (
+ normalized.type === "tool_call" &&
+ normalized.name &&
+ typeof normalized.name === "string"
+ ) {
+ const toolCall: Record<string, unknown> = {
+ id: normalized.id || "",
+ name: normalized.name,
+ arguments:
+ typeof normalized.args === "string"
+ ? normalized.args
+ : JSON.stringify(normalized.args ?? {}),
+ type: "function",
+ };
+
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const { type: _type, name: _name, args: _args, ...rest } = normalized;
+ normalized = {
+ ...rest,
+ role: rest.role || "assistant",
+ tool_calls: [toolCall],
+ };
+ }
+ // normalize existing tool_calls array
if (normalized.tool_calls && Array.isArray(normalized.tool_calls)) {
- normalized.tool_calls = normalized.tool_calls.map(normalizeToolCall);
+ normalized.tool_calls = normalized.tool_calls.map((tc) => {
+ if (!tc || typeof tc !== "object") return {};
+ const toolCall = tc as Record<string, unknown>;
+
+ // Convert Gemini format {type: "tool_call", name, args} → flat format
+ if (toolCall.type === "tool_call" && "args" in toolCall) {
+ return {
+ id: toolCall.id || "",
+ name: toolCall.name,
+ arguments:
+ typeof toolCall.args === "string"
+ ? toolCall.args
+ : JSON.stringify(toolCall.args ?? {}),
+ type: "function",
+ };
+ }
+
+ return toolCall;
+ });
}
- // Gemini structured content: content: [{type: "text", text: "..."}]
- // Convert to plain string for ChatML compatibility
- if (Array.isArray(message.content)) {
- const textParts = message.content
- .map((part: unknown) => {
- if (typeof part === "object" && part !== null) {
- const p = part as Record<string, unknown>;
- // Gemini format: {type: "text", text: "..."}
- if (p.type === "text" && typeof p.text === "string") {
- return p.text;
- }
- // Fallback: {text: "..."}
- if (typeof p.text === "string") {
- return p.text;
- }
- }
- // If part is already a string
- if (typeof part === "string") {
- return part;
- }
- return "";
- })
- .filter((text: unknown) => text !== "")
- .join("");
+ // process top-level parts array
+ // Gemini format: {parts: [{function_call/text/function_response}], role: "..."}
+ if (normalized.parts && Array.isArray(normalized.parts)) {
+ const { toolCalls, text } = extractFromParts(normalized.parts);
+ if (toolCalls.length > 0) {
+ normalized.tool_calls = toolCalls;
+ }
+ if (text) {
+ normalized.content = text;
+ // Remove parts to avoid showing in passthrough
+ delete normalized.parts;
+ }
+ }
+
+ // process nested content.parts[]
+ // Gemini format: {content: {parts: [{function_call: {...}}], role: "model"}}
+ if (
+ normalized.content &&
+ typeof normalized.content === "object" &&
+ !Array.isArray(normalized.content) &&
+ "parts" in normalized.content
+ ) {
+ const content = normalized.content as Record<string, unknown>;
+ if (Array.isArray(content.parts)) {
+ const { toolCalls } = extractFromParts(content.parts);
+ if (toolCalls.length > 0) {
+ normalized.tool_calls = toolCalls;
+ }
+
+ // Extract role if nested
+ if (content.role && typeof content.role === "string") {
+ normalized.role = content.role;
+ }
+ }
+ }
- if (textParts) {
- normalized.content = textParts;
+ // process content as array (structured content format)
+ // Gemini format: {content: [{type: "text", text: "..."}]}
+ if (Array.isArray(normalized.content)) {
+ const { text } = extractFromParts(normalized.content);
+ if (text) {
+ normalized.content = text;
}
}
- // Stringify object content for tool result messages, results should be strings in playground
- // NOTE: this will probably change down the line as we introduce structured tool results
+ // stringify object content for tool result messages
if (
normalized.role === "tool" &&
typeof normalized.content === "object" &&
- !Array.isArray(normalized.content) &&
- !isGeminiToolDefinition(msg)
+ !Array.isArray(normalized.content)
) {
normalized.content = stringifyToolResultContent(normalized.content);
}
@@ -113,27 +283,116 @@ function normalizeGeminiMessage(msg: unknown): Record<string, unknown> {
return normalized;
}
-function filterAndNormalizeMessages(data: unknown[]): unknown[] {
- return data
- .filter((msg) => !isGeminiToolDefinition(msg))
- .map(normalizeGeminiMessage);
+// normalize messages
+function normalizeMessages(data: unknown[]): unknown[] {
+ return data.map(normalizeGeminiMessage);
}
+// unwrap outer wrappers first then normalize inner structure
function preprocessData(data: unknown): unknown {
if (!data) return data;
- // Array of messages - filter tool definitions and normalize content
+ // ========================================
+ // STEP 1: Unwrap Raw Gemini API format
+ // ========================================
+ // {candidates: [{content: {parts, role}}]} → {parts, role, ...otherFields}
+ if (GeminiRawAPISchema.safeParse(data).success) {
+ const obj = data as Record<string, unknown>;
+ const candidates = obj.candidates as Array<Record<string, unknown>>;
+ if (candidates[0]?.content) {
+ // Unwrap: merge first candidate's content with other top-level fields
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const { candidates: _candidates, ...otherFields } = obj;
+ return normalizeGeminiMessage({
+ ...candidates[0].content,
+ ...otherFields,
+ });
+ }
+ }
+
+ // ========================================
+ // STEP 2: Unwrap ADK output format
+ // ========================================
+ // {content: {parts, role}, finish_reason: "..."} → {parts, role, finish_reason: "..."}
+ if (GeminiADKOutputSchema.safeParse(data).success) {
+ const obj = data as Record<string, unknown>;
+ const content = obj.content as Record<string, unknown>;
+ if ("parts" in content && Array.isArray(content.parts)) {
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const { content: _content, ...otherFields } = obj;
+ return normalizeGeminiMessage({ ...content, ...otherFields });
+ }
+ }
+
+ // ========================================
+ // STEP 3: Handle ADK input format
+ // ========================================
+ // {config: {tools, system_instruction}, contents: [...]}
+ if (GeminiADKInputSchema.safeParse(data).success) {
+ const obj = data as Record<string, unknown>;
+ const config = obj.config as Record<string, unknown> | undefined;
+ const contents = obj.contents;
+
+ if (config && Array.isArray(contents)) {
+ const messages: unknown[] = [];
+
+ // Extract system_instruction from config and prepend as system message
+ const systemInstruction = getField(
+ config,
+ "system_instruction",
+ "systemInstruction",
+ );
+ if (systemInstruction && typeof systemInstruction === "string") {
+ messages.push({
+ role: "system",
+ content: systemInstruction,
+ });
+ }
+
+ messages.push(...contents);
+
+ // Extract and attach tools if present
+ if ("tools" in config && Array.isArray(config.tools)) {
+ const extractedTools = extractToolDeclarations(config.tools);
+
+ if (extractedTools.length > 0) {
+ return normalizeMessages(messages).map((msg) => ({
+ ...(msg as Record<string, unknown>),
+ tools: extractedTools,
+ }));
+ }
+ }
+
+ // No tools, just normalize messages
+ return normalizeMessages(messages);
+ }
+ }
+
+ // ========================================
+ // STEP 4: Handle simple request format
+ // ========================================
+ // {contents: [{parts, role}], model: "..."}
+ if (GeminiRequestSchema.safeParse(data).success) {
+ const obj = data as Record<string, unknown>;
+ return normalizeMessages(obj.contents as unknown[]);
+ }
+
+ // ========================================
+ // STEP 5: Handle arrays
+ // ========================================
if (Array.isArray(data)) {
- return filterAndNormalizeMessages(data);
+ return normalizeMessages(data);
}
- // Object with messages key
+ // ========================================
+ // STEP 6: Handle messages wrapper
+ // ========================================
if (typeof data === "object" && "messages" in data) {
const obj = data as Record<string, unknown>;
return {
...obj,
messages: Array.isArray(obj.messages)
- ? filterAndNormalizeMessages(obj.messages)
+ ? normalizeMessages(obj.messages)
: obj.messages,
};
}
@@ -147,30 +406,37 @@ export const geminiAdapter: ProviderAdapter = {
detect(ctx: NormalizerContext): boolean {
const meta = parseMetadata(ctx.metadata);
- // Explicit framework override
+ // HINTS: Fast checks for explicit Gemini indicators
if (ctx.framework === "gemini") return true;
-
- // LangSmith metadata for Google VertexAI
- if (meta?.ls_provider === "google_vertexai") return true;
-
- // Observation name hint
if (ctx.observationName?.toLowerCase().includes("gemini")) return true;
if (ctx.observationName?.toLowerCase().includes("vertex")) return true;
+ if (meta?.ls_provider === "google_vertexai") return true;
- // Structural: check if data contains Gemini tool definition messages
- // This is a last-resort detection for unlabeled Gemini traces
- if (
- typeof ctx.metadata === "object" &&
- ctx.metadata !== null &&
- "messages" in ctx.metadata
- ) {
- const messages = (ctx.metadata as Record<string, unknown>).messages;
- if (Array.isArray(messages)) {
- const hasGeminiTools = messages.some(isGeminiToolDefinition);
- if (hasGeminiTools) return true;
+ // Metadata attributes check
+ if (meta && typeof meta === "object" && "attributes" in meta) {
+ const attributes = (meta as Record<string, unknown>).attributes;
+ if (
+ attributes &&
+ typeof attributes === "object" &&
+ (attributes as Record<string, unknown>)["gen_ai.system"] ===
+ "gcp.vertex.agent"
+ ) {
+ return true;
}
}
+ // STRUCTURAL: Schema-based detection on metadata (check metadata first for performance)
+ if (GeminiRequestSchema.safeParse(ctx.metadata).success) return true;
+ if (GeminiADKInputSchema.safeParse(ctx.metadata).success) return true;
+ if (GeminiRawAPISchema.safeParse(ctx.metadata).success) return true;
+ if (GeminiADKOutputSchema.safeParse(ctx.metadata).success) return true;
+
+ // Schema-based detection on data (slower, do last)
+ if (GeminiRequestSchema.safeParse(ctx.data).success) return true;
+ if (GeminiADKInputSchema.safeParse(ctx.data).success) return true;
+ if (GeminiRawAPISchema.safeParse(ctx.data).success) return true;
+ if (GeminiADKOutputSchema.safeParse(ctx.data).success) return true;
+
return false;
},
diff --git a/web/src/utils/chatml/adapters/generic.clienttest.ts b/web/src/utils/chatml/adapters/generic.clienttest.ts
index d5fd4d25a7..72578aa18b 100644
--- a/web/src/utils/chatml/adapters/generic.clienttest.ts
+++ b/web/src/utils/chatml/adapters/generic.clienttest.ts
@@ -78,4 +78,23 @@ describe("Generic Adapter", () => {
expect(inResult.success).toBe(false);
expect(allMessages).toHaveLength(0);
});
+
+ it("should extract content from Microsoft Agent parts with content field", () => {
+ const input = [
+ {
+ role: "user",
+ parts: [
+ // space behind hello - unsure if it should be added regardless
+ { type: "text", content: "Hello " },
+ { type: "text", content: "World" },
+ ],
+ },
+ ];
+
+ const preprocessed = genericAdapter.preprocess(input, "input", {});
+ expect(Array.isArray(preprocessed)).toBe(true);
+ const messages = preprocessed as any[];
+ expect(messages[0].content).toBe("Hello World");
+ expect(messages[0].parts).toBeUndefined();
+ });
});
diff --git a/web/src/utils/chatml/adapters/index.ts b/web/src/utils/chatml/adapters/index.ts
index f399dd3518..88f94c5c36 100644
--- a/web/src/utils/chatml/adapters/index.ts
+++ b/web/src/utils/chatml/adapters/index.ts
@@ -3,12 +3,14 @@ import { mapToChatMl, mapOutputToChatMl } from "../core";
import { langgraphAdapter } from "./langgraph";
import { openAIAdapter } from "./openai";
import { geminiAdapter } from "./gemini";
+import { microsoftAgentAdapter } from "./microsoft-agent";
import { genericAdapter } from "./generic";
const adapters: ProviderAdapter[] = [
langgraphAdapter, // Must be before openAI (both use langfuse-sdk scope)
- openAIAdapter,
+ openAIAdapter, // OpenAI (Chat Completions & Responses API)
geminiAdapter, // Gemini/VertexAI format
+ microsoftAgentAdapter, // Microsoft Agent Framework
// Add more adapters here as needed
genericAdapter, // Always last (fallback)
];
@@ -31,13 +33,21 @@ function selectAdapter(ctx: NormalizerContext): ProviderAdapter {
}
export function normalizeInput(input: unknown, ctx: NormalizerContext = {}) {
- const adapter = selectAdapter({ ...ctx, metadata: ctx.metadata ?? input });
+ const adapter = selectAdapter({
+ ...ctx,
+ metadata: ctx.metadata ?? input,
+ data: input,
+ });
const preprocessed = adapter.preprocess(input, "input", ctx);
return mapToChatMl(preprocessed);
}
export function normalizeOutput(output: unknown, ctx: NormalizerContext = {}) {
- const adapter = selectAdapter({ ...ctx, metadata: ctx.metadata ?? output });
+ const adapter = selectAdapter({
+ ...ctx,
+ metadata: ctx.metadata ?? output,
+ data: output,
+ });
const preprocessed = adapter.preprocess(output, "output", ctx);
return mapOutputToChatMl(preprocessed);
}
diff --git a/web/src/utils/chatml/adapters/langgraph.clienttest.ts b/web/src/utils/chatml/adapters/langgraph.clienttest.ts
index 96b2feb8a0..89911f8351 100644
--- a/web/src/utils/chatml/adapters/langgraph.clienttest.ts
+++ b/web/src/utils/chatml/adapters/langgraph.clienttest.ts
@@ -90,10 +90,12 @@ describe("LangGraph Adapter", () => {
expect(result.data[1].role).toBe("assistant");
expect(result.data[1].json?.json?._originalType).toBe("ai");
- const toolCalls = result.data[1].json?.json?.tool_calls;
+ // Tool calls should be in validated tool_calls field with flat format
+ const toolCalls = result.data[1].tool_calls;
expect(toolCalls).toBeDefined();
expect(toolCalls?.[0].id).toBe("call_abc");
- expect(toolCalls?.[0].function.arguments).toEqual({ query: "example" });
+ expect(toolCalls?.[0].name).toBe("Web-Search");
+ expect(toolCalls?.[0].arguments).toBe('{"query":"example"}');
expect(result.data[2].role).toBe("tool");
expect(typeof result.data[2].content).toBe("string");
@@ -101,4 +103,189 @@ describe("LangGraph Adapter", () => {
'{"temperature":72,"conditions":"sunny"}',
);
});
+
+ it("should filter out tool definitions and attach them to messages", () => {
+ // This is the format from langgraph-2025-08-22.json
+ const input = [
+ {
+ role: "user",
+ content: "Be helpful!",
+ },
+ {
+ role: "user",
+ content: "Search the web for 'example' and summarize.",
+ },
+ {
+ role: "tool",
+ content: {
+ type: "function",
+ function: {
+ name: "Web-Search",
+ description: "Dummy web search tool.",
+ parameters: {
+ properties: {
+ query: {
+ type: "string",
+ },
+ },
+ required: ["query"],
+ type: "object",
+ },
+ },
+ },
+ },
+ ];
+
+ const result = normalizeInput(input, { framework: "langgraph" });
+ expect(result.success).toBe(true);
+
+ // Tool definition should be filtered out
+ expect(result.data).toHaveLength(2);
+
+ // Both messages should have tools attached
+ expect(result.data?.[0].role).toBe("user");
+ expect(result.data?.[0].content).toBe("Be helpful!");
+ expect(result.data?.[0].tools).toBeDefined();
+ expect(result.data?.[0].tools?.[0].name).toBe("Web-Search");
+ expect(result.data?.[0].tools?.[0].description).toBe(
+ "Dummy web search tool.",
+ );
+
+ expect(result.data?.[1].role).toBe("user");
+ expect(result.data?.[1].content).toBe(
+ "Search the web for 'example' and summarize.",
+ );
+ expect(result.data?.[1].tools).toBeDefined();
+ expect(result.data?.[1].tools?.[0].name).toBe("Web-Search");
+ });
+
+ it("should clean up additional_kwargs with null values", () => {
+ const output = {
+ role: "assistant",
+ content: "",
+ additional_kwargs: {
+ tool_calls: [
+ {
+ id: "call_123",
+ function: {
+ name: "Web-Search",
+ arguments: { query: "example" },
+ },
+ type: "function",
+ },
+ ],
+ refusal: null,
+ },
+ };
+
+ const result = normalizeInput(output, { framework: "langgraph" });
+ expect(result.success).toBe(true);
+
+ // Tool calls should be extracted and flattened
+ expect(result.data?.[0].tool_calls).toBeDefined();
+ expect(result.data?.[0].tool_calls?.[0].name).toBe("Web-Search");
+ expect(result.data?.[0].tool_calls?.[0].arguments).toBe(
+ '{"query":"example"}',
+ );
+
+ // additional_kwargs should be removed entirely (only had tool_calls and null refusal)
+ expect(result.data?.[0].json?.json?.additional_kwargs).toBeUndefined();
+ });
+
+ it("should not mutate original object during normalization", () => {
+ const additionalKwargs = {
+ tool_calls: [{ id: "call_123", function: { name: "Web-Search" } }],
+ };
+ const output = {
+ role: "assistant",
+ content: "",
+ additional_kwargs: additionalKwargs,
+ };
+
+ normalizeInput(output, { framework: "langgraph" });
+
+ // Original must be unchanged (JSON view depends on it)
+ expect(additionalKwargs).toEqual({
+ tool_calls: [{ id: "call_123", function: { name: "Web-Search" } }],
+ });
+ });
+
+ it("should filter tool definitions from google vertex langchain trace", () => {
+ // Format from google-vertex-tools-langchain-2025-09-19.json
+ const input = [
+ {
+ role: "system",
+ content: "You are a helpful assistant.",
+ },
+ {
+ role: "user",
+ content: "Hello, I'm interested in learning more.",
+ },
+ {
+ role: "tool",
+ content: {
+ type: "function",
+ function: {
+ name: "transition_to_service_a",
+ description: "Transition to Service A",
+ parameters: {
+ properties: {
+ reason: {
+ description: "Reason for transition",
+ type: "string",
+ },
+ },
+ required: ["reason"],
+ type: "object",
+ },
+ },
+ },
+ },
+ {
+ role: "tool",
+ content: {
+ type: "function",
+ function: {
+ name: "get_customer_info",
+ description: "Retrieve customer info",
+ parameters: {
+ type: "object",
+ properties: {
+ customer_id: {
+ type: "string",
+ },
+ },
+ },
+ },
+ },
+ },
+ {
+ role: "assistant",
+ content: "How can I help you today?",
+ },
+ ];
+
+ const ctx = {
+ metadata: {
+ ls_provider: "google_vertexai",
+ },
+ };
+
+ const result = normalizeInput(input, ctx);
+
+ expect(result.success).toBe(true);
+
+ // Tool definitions should be filtered out - only 3 messages remain
+ expect(result.data).toHaveLength(3);
+
+ // Check no tool definition messages remain
+ const toolMessages = result.data?.filter((msg: any) => msg.role === "tool");
+ expect(toolMessages).toHaveLength(0);
+
+ // Tools should be attached to messages
+ expect(result.data?.[0].tools).toBeDefined();
+ expect(result.data?.[0].tools).toHaveLength(2);
+ expect(result.data?.[0].tools?.[0].name).toBe("transition_to_service_a");
+ expect(result.data?.[0].tools?.[1].name).toBe("get_customer_info");
+ });
});
diff --git a/web/src/utils/chatml/adapters/langgraph.ts b/web/src/utils/chatml/adapters/langgraph.ts
index 1110fa0763..1fa49e46a3 100644
--- a/web/src/utils/chatml/adapters/langgraph.ts
+++ b/web/src/utils/chatml/adapters/langgraph.ts
@@ -1,10 +1,101 @@
import type { NormalizerContext, ProviderAdapter } from "../types";
import {
removeNullFields,
- // stringifyToolCallArgs,
stringifyToolResultContent,
parseMetadata,
} from "../helpers";
+import { z } from "zod/v4";
+
+// Detection schemas for LangChain/LangGraph formats
+
+// LangChain message with type field (no role)
+const LangChainMessageSchema = z.array(
+ z.looseObject({
+ type: z.enum(["human", "ai", "tool", "system"]),
+ content: z.any(),
+ }),
+);
+
+// LangGraph message with additional_kwargs
+const LangGraphMessageSchema = z
+ .array(
+ z.looseObject({
+ role: z.string().optional(),
+ additional_kwargs: z
+ .looseObject({
+ tool_calls: z.array(z.any()).optional(),
+ })
+ .optional(),
+ }),
+ )
+ .refine(
+ (data) => {
+ // Reject if any message has top-level parts (Microsoft Agent/Gemini format)
+ return !data.some(
+ (msg) =>
+ typeof msg === "object" &&
+ msg !== null &&
+ "parts" in msg &&
+ Array.isArray((msg as Record<string, unknown>).parts),
+ );
+ },
+ { message: "Messages with top-level parts are not LangGraph format" },
+ );
+
+// Wrapped messages format
+const LangGraphWrappedSchema = z.looseObject({
+ messages: z.array(z.any()),
+});
+
+/**
+ * Detect if a message is a tool definition (not a tool result)
+ * LangGraph format: {role: "tool", content: {type: "function", function: {...}}}
+ * Tool results have tool_call_id, tool definitions do not
+ */
+function isLangGraphToolDefinition(msg: unknown): boolean {
+ if (!msg || typeof msg !== "object") return false;
+
+ const message = msg as Record<string, unknown>;
+
+ return (
+ message.role === "tool" &&
+ typeof message.content === "object" &&
+ message.content !== null &&
+ !Array.isArray(message.content) &&
+ (message.content as Record<string, unknown>).type === "function" &&
+ !!(message.content as Record<string, unknown>).function &&
+ !message.tool_call_id // Tool definitions don't have tool_call_id
+ );
+}
+
+// extract tool definitions from messages array
+function extractToolDefinitions(messages: unknown[]): Array<{
+ name: string;
+ description?: string;
+ parameters?: Record<string, unknown>;
+}> {
+ return messages.filter(isLangGraphToolDefinition).map((msg) => {
+ const message = msg as Record<string, unknown>;
+ const func = (message.content as Record<string, unknown>)
+ .function as Record<string, unknown>;
+
+ const toolDef: Record<string, unknown> = {
+ name: (func.name as string) || "",
+ };
+ if (func.description !== null && func.description !== undefined) {
+ toolDef.description = func.description;
+ }
+ if (func.parameters !== null && func.parameters !== undefined) {
+ toolDef.parameters = func.parameters;
+ }
+
+ return toolDef as {
+ name: string;
+ description?: string;
+ parameters?: Record<string, unknown>;
+ };
+ });
+}
function normalizeMessage(msg: unknown): Record<string, unknown> {
if (!msg || typeof msg !== "object") return {};
@@ -35,23 +126,69 @@ function normalizeMessage(msg: unknown): Record<string, unknown> {
string,
unknown
>;
- if (additionalKwargs.tool_calls && !normalized.tool_calls) {
- normalized.tool_calls = additionalKwargs.tool_calls;
+
+ // Handle tool_calls from additional_kwargs
+ if (additionalKwargs.tool_calls) {
+ if (!normalized.tool_calls) {
+ // No top-level tool_calls, extract from additional_kwargs
+ normalized.tool_calls = additionalKwargs.tool_calls;
+ }
+ // IMPORTANT: Always remove tool_calls from additional_kwargs to prevent
+ // ChatMlSchema from overwriting our processed version when it spreads additional_kwargs
+ // This handles both cases:
+ // 1. LangGraph format: tool_calls extracted from additional_kwargs
+ // 2. LangChain format: top-level tool_calls already exists, prevent overwrite
+ // Don't mutate original object - JSON view needs to show original data
+ // Filter out null fields to prevent them from creating extra json blocks in UI
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const { tool_calls: _removed, ...restKwargs } = additionalKwargs;
+ normalized.additional_kwargs = removeNullFields(restKwargs);
}
+
+ // Keep other fields in additional_kwargs (non-null values) for JSON view
+ // ChatMlSchema will spread these into passthrough json field
}
- // Stringify tool_calls arguments
- // if (normalized.tool_calls && Array.isArray(normalized.tool_calls)) {
- // normalized.tool_calls = (
- // normalized.tool_calls as Record<string, unknown>[]
- // ).map(stringifyToolCallArgs);
- // }
+ // Flatten nested tool_calls format to flat ChatML format
+ // LangGraph can have OpenAI-style nested format: {id, type, function: {name, arguments}}
+ // Convert to flat format: {id, name, arguments, type}
+ if (normalized.tool_calls && Array.isArray(normalized.tool_calls)) {
+ normalized.tool_calls = (
+ normalized.tool_calls as Record<string, unknown>[]
+ ).map((tc) => {
+ // If nested format (has function.name), flatten it
+ if (tc.function && typeof tc.function === "object") {
+ const func = tc.function as Record<string, unknown>;
+ return {
+ id: tc.id,
+ name: func.name,
+ arguments:
+ typeof func.arguments === "string"
+ ? func.arguments
+ : JSON.stringify(func.arguments ?? {}),
+ type: tc.type || "function",
+ ...(tc.index !== undefined ? { index: tc.index } : {}),
+ };
+ }
+ // Already flat format - handle both 'args' (LangChain) and 'arguments' (OpenAI)
+ // LangChain uses 'args', OpenAI uses 'arguments'
+ const argsValue = tc.args ?? tc.arguments;
+ return {
+ ...tc,
+ name: tc.name,
+ arguments:
+ typeof argsValue === "string"
+ ? argsValue
+ : JSON.stringify(argsValue ?? {}),
+ };
+ });
+ }
- // Stringify object content for tool messages
+ // Stringify object/array content for tool messages
if (
normalized.role === "tool" &&
typeof normalized.content === "object" &&
- !Array.isArray(normalized.content)
+ normalized.content !== null
) {
normalized.content = stringifyToolResultContent(normalized.content);
}
@@ -59,28 +196,58 @@ function normalizeMessage(msg: unknown): Record<string, unknown> {
return normalized;
}
+function filterAndNormalizeMessages(data: unknown[]): unknown[] {
+ return data
+ .filter((msg) => !isLangGraphToolDefinition(msg))
+ .map(normalizeMessage);
+}
+
function preprocessData(data: unknown): unknown {
if (!data) return data;
// Array of messages
if (Array.isArray(data)) {
- return data.map(normalizeMessage);
+ const extractedTools = extractToolDefinitions(data);
+ const normalizedMessages = filterAndNormalizeMessages(data);
+
+ if (extractedTools.length > 0) {
+ // Attach tools to all messages
+ return normalizedMessages.map((msg) => ({
+ ...(msg as Record<string, unknown>),
+ tools: extractedTools,
+ }));
+ }
+
+ return normalizedMessages;
}
// Object with messages key
if (typeof data === "object" && "messages" in data) {
const obj = data as Record<string, unknown>;
- return {
- ...obj,
- messages: Array.isArray(obj.messages)
- ? obj.messages.map(normalizeMessage)
- : obj.messages,
- };
+ if (Array.isArray(obj.messages)) {
+ const extractedTools = extractToolDefinitions(obj.messages);
+ const normalizedMessages = filterAndNormalizeMessages(obj.messages);
+
+ if (extractedTools.length > 0) {
+ return {
+ ...obj,
+ messages: normalizedMessages.map((msg) => ({
+ ...(msg as Record<string, unknown>),
+ tools: extractedTools,
+ })),
+ };
+ }
+
+ return {
+ ...obj,
+ messages: normalizedMessages,
+ };
+ }
}
- // Single message
+ // Single message - wrap in array for consistency
if (typeof data === "object" && ("role" in data || "type" in data)) {
- return normalizeMessage(data);
+ return [normalizeMessage(data)];
}
return data;
@@ -92,57 +259,56 @@ export const langgraphAdapter: ProviderAdapter = {
detect(ctx: NormalizerContext): boolean {
const meta = parseMetadata(ctx.metadata);
+ // EXPLICIT: Framework hint
if (ctx.framework === "langgraph") return true;
- // Check for LangGraph-specific metadata
+ // HINTS: LangGraph/LangChain-specific metadata markers
if (meta && typeof meta === "object") {
+ // LangGraph markers
if (
"langgraph_step" in meta ||
"langgraph_node" in meta ||
"langgraph_path" in meta ||
- "langgraph_checkpoint_ns" in meta
+ "langgraph_checkpoint_ns" in meta ||
+ meta.framework === "langgraph" ||
+ (Array.isArray(meta.tags) && meta.tags.includes("langgraph"))
) {
return true;
}
- if (meta.framework === "langgraph") return true;
-
- if (Array.isArray(meta.tags) && meta.tags.includes("langgraph")) {
+ // LangSmith/LangChain markers (ls_ prefix indicates LangChain ecosystem)
+ const hasLangChainMarkers = Object.keys(meta).some((key) =>
+ key.startsWith("ls_"),
+ );
+ if (hasLangChainMarkers) {
return true;
}
}
- // Check for LangChain/LangGraph message structure
- if (
- typeof ctx.metadata === "object" &&
- ctx.metadata !== null &&
- "messages" in ctx.metadata
- ) {
- const messages = (ctx.metadata as Record<string, unknown>).messages;
- if (Array.isArray(messages) && messages.length > 0) {
- const hasLangChainStructure = messages.some((msg: unknown) => {
- const message = msg as Record<string, unknown>;
- // LangChain type field without role
- if (
- message.type &&
- typeof message.type === "string" &&
- ["human", "ai", "tool", "system"].includes(message.type) &&
- !("role" in message)
- ) {
- return true;
- }
- // LangChain tool_calls in additional_kwargs
- if (
- message.additional_kwargs &&
- typeof message.additional_kwargs === "object"
- ) {
- const kwargs = message.additional_kwargs as Record<string, unknown>;
- if (kwargs.tool_calls) return true;
- }
- return false;
- });
- if (hasLangChainStructure) return true;
- }
+ // STRUCTURAL: Schema-based detection on metadata
+ if (LangChainMessageSchema.safeParse(ctx.metadata).success) return true;
+ if (LangGraphMessageSchema.safeParse(ctx.metadata).success) return true;
+
+ // Check wrapped messages format
+ if (LangGraphWrappedSchema.safeParse(ctx.metadata).success) {
+ const wrapped = ctx.metadata as { messages: unknown[] };
+ if (LangChainMessageSchema.safeParse(wrapped.messages).success)
+ return true;
+ if (LangGraphMessageSchema.safeParse(wrapped.messages).success)
+ return true;
+ }
+
+ // finally Schema-based detection on data b/c of performance
+ if (LangChainMessageSchema.safeParse(ctx.data).success) return true;
+ if (LangGraphMessageSchema.safeParse(ctx.data).success) return true;
+
+ // Check wrapped messages format on data
+ if (LangGraphWrappedSchema.safeParse(ctx.data).success) {
+ const wrapped = ctx.data as { messages: unknown[] };
+ if (LangChainMessageSchema.safeParse(wrapped.messages).success)
+ return true;
+ if (LangGraphMessageSchema.safeParse(wrapped.messages).success)
+ return true;
}
return false;
diff --git a/web/src/utils/chatml/adapters/microsoft-agent.clienttest.ts b/web/src/utils/chatml/adapters/microsoft-agent.clienttest.ts
new file mode 100644
index 0000000000..c98e4d35d4
--- /dev/null
+++ b/web/src/utils/chatml/adapters/microsoft-agent.clienttest.ts
@@ -0,0 +1,236 @@
+jest.mock("@langfuse/shared", () => ({
+ ChatMessageRole: {
+ System: "system",
+ Developer: "developer",
+ User: "user",
+ Assistant: "assistant",
+ Tool: "tool",
+ Model: "model",
+ },
+}));
+
+import { normalizeInput, normalizeOutput } from "./index";
+import { microsoftAgentAdapter } from "./microsoft-agent";
+
+describe("Microsoft Agent Framework Adapter", () => {
+ describe("detection", () => {
+ it("should detect Microsoft Agent Framework by provider name", () => {
+ expect(
+ microsoftAgentAdapter.detect({
+ metadata: {
+ attributes: {
+ "gen_ai.provider.name": "microsoft.agent_framework",
+ },
+ },
+ }),
+ ).toBe(true);
+ });
+
+ it("should detect by framework override", () => {
+ expect(
+ microsoftAgentAdapter.detect({ framework: "microsoft-agent" }),
+ ).toBe(true);
+ });
+
+ it("should detect Microsoft Agent format with parts array", () => {
+ const input = [
+ {
+ role: "user",
+ parts: [{ type: "text", content: "What's the weather like?" }],
+ },
+ ];
+
+ expect(microsoftAgentAdapter.detect({ data: input })).toBe(true);
+ });
+
+ it("should not detect OpenAI format without parts", () => {
+ expect(
+ microsoftAgentAdapter.detect({
+ data: { role: "user", content: "Hello" },
+ }),
+ ).toBe(false);
+ });
+ });
+
+ describe("normalization", () => {
+ it("should extract tool calls from parts array", () => {
+ const input = [
+ {
+ role: "assistant",
+ parts: [
+ {
+ type: "tool_call",
+ id: ["run_123", "call_456"],
+ name: "get_weather",
+ arguments: { location: "Portland" },
+ },
+ ],
+ },
+ ];
+
+ const result = normalizeInput(input, { framework: "microsoft-agent" });
+
+ expect(result.success).toBe(true);
+ expect(result.data?.[0].tool_calls).toBeDefined();
+ expect(result.data?.[0].tool_calls?.[0].name).toBe("get_weather");
+ expect(result.data?.[0].tool_calls?.[0].arguments).toBe(
+ '{"location":"Portland"}',
+ );
+ expect(result.data?.[0].tool_calls?.[0].id).toBe("call_456");
+ });
+
+ it("should extract text content from parts array", () => {
+ const input = [
+ {
+ role: "user",
+ parts: [
+ {
+ type: "text",
+ content: "What's the weather like in Portland?",
+ },
+ ],
+ },
+ ];
+
+ const result = normalizeInput(input, { framework: "microsoft-agent" });
+
+ expect(result.success).toBe(true);
+ expect(result.data?.[0].content).toBe(
+ "What's the weather like in Portland?",
+ );
+ // parts should be removed during normalization (not in ChatML type)
+ expect((result.data?.[0] as any).parts).toBeUndefined();
+ });
+
+ it("should extract tool call responses from parts array", () => {
+ const input = [
+ {
+ role: "tool",
+ parts: [
+ {
+ type: "tool_call_response",
+ id: ["run_123", "call_456"],
+ response:
+ "The weather in Portland is stormy with a high of 19°C.",
+ },
+ ],
+ },
+ ];
+
+ const result = normalizeInput(input, { framework: "microsoft-agent" });
+
+ expect(result.success).toBe(true);
+ expect(result.data?.[0].content).toBe(
+ "The weather in Portland is stormy with a high of 19°C.",
+ );
+ expect(result.data?.[0].tool_call_id).toBe("call_456");
+ });
+
+ it("should handle full conversation with tool calls", () => {
+ const metadata = {
+ attributes: {
+ "gen_ai.provider.name": "microsoft.agent_framework",
+ "gen_ai.tool.definitions": [
+ {
+ type: "function",
+ function: {
+ name: "get_weather",
+ description: "Get the weather for a given location.",
+ parameters: {
+ properties: {
+ location: {
+ description: "The location to get the weather for.",
+ type: "string",
+ },
+ },
+ required: ["location"],
+ type: "object",
+ },
+ },
+ },
+ ],
+ },
+ };
+
+ const input = [
+ {
+ role: "user",
+ parts: [
+ {
+ type: "text",
+ content: "What's the weather like in Portland?",
+ },
+ ],
+ },
+ ];
+
+ const result = normalizeInput(input, {
+ metadata,
+ framework: "microsoft-agent",
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.data?.[0].content).toBe(
+ "What's the weather like in Portland?",
+ );
+ expect(result.data?.[0].tools).toBeDefined();
+ expect(result.data?.[0].tools?.[0].name).toBe("get_weather");
+ });
+
+ it("should handle output with multiple parts", () => {
+ const output = [
+ {
+ role: "assistant",
+ parts: [
+ {
+ type: "tool_call",
+ id: ["run_123", "call_456"],
+ name: "get_weather",
+ arguments: { location: "Portland" },
+ },
+ ],
+ },
+ {
+ role: "tool",
+ parts: [
+ {
+ type: "tool_call_response",
+ id: ["run_123", "call_456"],
+ response:
+ "The weather in Portland is stormy with a high of 19°C.",
+ },
+ ],
+ },
+ {
+ role: "assistant",
+ parts: [
+ {
+ type: "text",
+ content:
+ "The weather in Portland is currently stormy with a high temperature of 19°C.",
+ },
+ ],
+ },
+ ];
+
+ const result = normalizeOutput(output, { framework: "microsoft-agent" });
+
+ expect(result.success).toBe(true);
+ expect(result.data).toHaveLength(3);
+
+ // First message: tool call
+ expect(result.data?.[0].tool_calls).toBeDefined();
+ expect(result.data?.[0].tool_calls?.[0].name).toBe("get_weather");
+
+ // Second message: tool response
+ expect(result.data?.[1].content).toBe(
+ "The weather in Portland is stormy with a high of 19°C.",
+ );
+
+ // Third message: text response
+ expect(result.data?.[2].content).toBe(
+ "The weather in Portland is currently stormy with a high temperature of 19°C.",
+ );
+ });
+ });
+});
diff --git a/web/src/utils/chatml/adapters/microsoft-agent.ts b/web/src/utils/chatml/adapters/microsoft-agent.ts
new file mode 100644
index 0000000000..040de45814
--- /dev/null
+++ b/web/src/utils/chatml/adapters/microsoft-agent.ts
@@ -0,0 +1,276 @@
+import type { NormalizerContext, ProviderAdapter } from "../types";
+import {
+ parseMetadata,
+ getNestedProperty,
+ stringifyToolResultContent,
+} from "../helpers";
+import { z } from "zod/v4";
+
+/**
+ * Detection schemas for Microsoft Agent Framework format
+ *
+ * Microsoft Agent Framework uses a ChatML-like format with parts arrays:
+ * - Messages: {role: "user|assistant|tool", parts: [{type, ...}]}
+ * - Tool calls: {type: "tool_call", id: [...], name, arguments}
+ * - Tool responses: {type: "tool_call_response", id: [...], response}
+ * - Text: {type: "text", content}
+ */
+
+// Microsoft Agent message with parts array
+const MicrosoftAgentMessageSchema = z.looseObject({
+ role: z.enum(["user", "assistant", "tool"]),
+ parts: z.array(
+ z.looseObject({
+ type: z.enum(["text", "tool_call", "tool_call_response"]),
+ }),
+ ),
+});
+
+// Array of Microsoft Agent messages
+const MicrosoftAgentMessagesSchema = z.array(MicrosoftAgentMessageSchema);
+
+/**
+ * Extract tool calls and text content from parts array
+ * Handles: text, tool_call, tool_call_response
+ */
+function extractFromParts(parts: unknown[]): {
+ toolCalls: Array<Record<string, unknown>>;
+ text: string;
+ toolCallId?: string;
+} {
+ const toolCalls: Array<Record<string, unknown>> = [];
+ const textParts: string[] = [];
+ let toolCallId: string | undefined;
+
+ for (const part of parts) {
+ if (!part || typeof part !== "object") continue;
+
+ const p = part as Record<string, unknown>;
+
+ // Handle tool_call: {type: "tool_call", id: [...], name, arguments}
+ if (p.type === "tool_call") {
+ // uses array IDs: ["run_id", "call_id"], we just need the call id,
+ let callId = "";
+ if (Array.isArray(p.id)) {
+ const callIdMatch = p.id.find(
+ (id) => typeof id === "string" && id.startsWith("call_"),
+ );
+ callId = callIdMatch || p.id[p.id.length - 1] || "";
+ } else if (typeof p.id === "string") {
+ callId = p.id;
+ }
+
+ toolCalls.push({
+ id: callId,
+ name: p.name,
+ arguments:
+ typeof p.arguments === "string"
+ ? p.arguments
+ : JSON.stringify(p.arguments ?? {}),
+ type: "function",
+ });
+ continue;
+ }
+
+ // Handle text: {type: "text", content}
+ if (p.type === "text" && typeof p.content === "string") {
+ textParts.push(p.content);
+ continue;
+ }
+
+ // Handle tool_call_response: {type: "tool_call_response", id: [...], response}
+ if (p.type === "tool_call_response") {
+ // we just need the call_id, again
+ if (Array.isArray(p.id)) {
+ const callIdMatch = p.id.find(
+ (id) => typeof id === "string" && id.startsWith("call_"),
+ );
+ toolCallId = callIdMatch || p.id[p.id.length - 1] || "";
+ } else if (typeof p.id === "string") {
+ toolCallId = p.id;
+ }
+ textParts.push(stringifyToolResultContent(p.response));
+ }
+ }
+
+ return {
+ toolCalls,
+ text: textParts.join(""),
+ toolCallId,
+ };
+}
+
+/**
+ * Extract tool definitions from metadata.attributes["gen_ai.tool.definitions"]
+ * Microsoft Agent Framework uses OpenAI-style tool definitions
+ */
+function extractToolDefinitions(tools: unknown): Array<{
+ name: string;
+ description?: string;
+ parameters?: Record<string, unknown>;
+}> {
+ if (!Array.isArray(tools)) return [];
+
+ const definitions: Array<{
+ name: string;
+ description?: string;
+ parameters?: Record<string, unknown>;
+ }> = [];
+
+ for (const tool of tools) {
+ if (!tool || typeof tool !== "object") continue;
+ const t = tool as Record<string, unknown>;
+
+ // Handle OpenAI-style tool definitions: {type: "function", function: {name, description, parameters}}
+ // intentionally not imported from openai for separation of concerns
+ if (t.type === "function" && t.function && typeof t.function === "object") {
+ const func = t.function as Record<string, unknown>;
+ const toolDef: Record<string, unknown> = {
+ name: func.name || "",
+ };
+ if (func.description !== null && func.description !== undefined) {
+ toolDef.description = func.description;
+ }
+ if (func.parameters !== null && func.parameters !== undefined) {
+ toolDef.parameters = func.parameters;
+ }
+ definitions.push(
+ toolDef as {
+ name: string;
+ description?: string;
+ parameters?: Record<string, unknown>;
+ },
+ );
+ }
+ }
+
+ return definitions;
+}
+
+// Normalize a single Microsoft Agent message to our ChatML format
+function normalizeMicrosoftAgentMessage(msg: unknown): Record<string, unknown> {
+ if (!msg || typeof msg !== "object") return {};
+
+ const message = msg as Record<string, unknown>;
+ const normalized = { ...message };
+
+ if (normalized.parts && Array.isArray(normalized.parts)) {
+ const { toolCalls, text, toolCallId } = extractFromParts(normalized.parts);
+
+ if (toolCalls.length > 0) {
+ normalized.tool_calls = toolCalls;
+ }
+
+ if (text) {
+ normalized.content = text;
+ }
+
+ // Set tool_call_id for tool messages (from tool_call_response)
+ if (toolCallId && normalized.role === "tool") {
+ normalized.tool_call_id = toolCallId;
+ }
+
+ // prevent showing in passthrough
+ delete normalized.parts;
+ }
+
+ // Stringify object content for tool result messages
+ if (
+ normalized.role === "tool" &&
+ typeof normalized.content === "object" &&
+ !Array.isArray(normalized.content)
+ ) {
+ normalized.content = stringifyToolResultContent(normalized.content);
+ }
+
+ return normalized;
+}
+
+function normalizeMessages(data: unknown[]): unknown[] {
+ return data.map(normalizeMicrosoftAgentMessage);
+}
+
+function preprocessData(data: unknown, ctx: NormalizerContext): unknown {
+ if (!data) return data;
+
+ if (Array.isArray(data)) {
+ const normalized = normalizeMessages(data);
+
+ // extract tool definitions from metadata
+ const meta = parseMetadata(ctx.metadata);
+ const toolDefinitions = getNestedProperty(
+ meta,
+ "attributes",
+ "gen_ai.tool.definitions",
+ );
+
+ if (toolDefinitions) {
+ const tools = extractToolDefinitions(toolDefinitions);
+ if (tools.length > 0) {
+ return normalized.map((msg) => ({
+ ...(msg as Record<string, unknown>),
+ tools,
+ }));
+ }
+ }
+
+ return normalized;
+ }
+
+ // messages wrapper
+ if (typeof data === "object" && "messages" in data) {
+ const obj = data as Record<string, unknown>;
+ return {
+ ...obj,
+ messages: Array.isArray(obj.messages)
+ ? normalizeMessages(obj.messages)
+ : obj.messages,
+ };
+ }
+
+ // single message
+ if (typeof data === "object" && "role" in data) {
+ return normalizeMicrosoftAgentMessage(data);
+ }
+
+ return data;
+}
+
+export const microsoftAgentAdapter: ProviderAdapter = {
+ id: "microsoft-agent",
+
+ detect(ctx: NormalizerContext): boolean {
+ const meta = parseMetadata(ctx.metadata);
+
+ // HINTS: Fast checks for explicit Microsoft Agent Framework indicators
+ if (ctx.framework === "microsoft-agent") return true;
+
+ const scopeName = getNestedProperty(meta, "scope", "name");
+ if (scopeName === "agent_framework") return true;
+
+ const providerName = getNestedProperty(
+ meta,
+ "attributes",
+ "gen_ai.provider.name",
+ );
+ if (providerName === "microsoft.agent_framework") return true;
+
+ // STRUCTURAL: Schema-based detection on metadata
+ if (MicrosoftAgentMessagesSchema.safeParse(ctx.metadata).success)
+ return true;
+
+ // Schema-based detection on data (slower, do last)
+ if (MicrosoftAgentMessagesSchema.safeParse(ctx.data).success) return true;
+ if (MicrosoftAgentMessageSchema.safeParse(ctx.data).success) return true;
+
+ return false;
+ },
+
+ preprocess(
+ data: unknown,
+ _kind: "input" | "output",
+ ctx: NormalizerContext,
+ ): unknown {
+ return preprocessData(data, ctx);
+ },
+};
diff --git a/web/src/utils/chatml/adapters/openai.clienttest.ts b/web/src/utils/chatml/adapters/openai.clienttest.ts
index 9f866baf58..4728b3c9e4 100644
--- a/web/src/utils/chatml/adapters/openai.clienttest.ts
+++ b/web/src/utils/chatml/adapters/openai.clienttest.ts
@@ -9,38 +9,84 @@ jest.mock("@langfuse/shared", () => ({
},
}));
-import { normalizeInput } from "./index";
+import { normalizeInput, normalizeOutput } from "./index";
import { openAIAdapter } from "./openai";
describe("OpenAI Adapter", () => {
- it("should detect OpenAI and reject LangGraph", () => {
- expect(openAIAdapter.detect({ observationName: "OpenAI-generation" })).toBe(
- true,
- );
-
- expect(
- openAIAdapter.detect({
- metadata: { messages: [{ role: "user", content: "test" }] },
- }),
- ).toBe(true);
-
- expect(openAIAdapter.detect({ metadata: { framework: "langgraph" } })).toBe(
- false,
- );
+ describe("detection", () => {
+ it("should detect OpenAI and reject LangGraph", () => {
+ expect(
+ openAIAdapter.detect({ observationName: "OpenAI-generation" }),
+ ).toBe(true);
+
+ expect(
+ openAIAdapter.detect({
+ metadata: { messages: [{ role: "user", content: "test" }] },
+ }),
+ ).toBe(true);
+
+ expect(
+ openAIAdapter.detect({ metadata: { framework: "langgraph" } }),
+ ).toBe(false);
+
+ expect(
+ openAIAdapter.detect({
+ metadata: { langgraph_node: "agent", langgraph_step: 3 },
+ }),
+ ).toBe(false);
+
+ expect(
+ openAIAdapter.detect({
+ metadata: {
+ messages: [{ type: "human", content: "test" }],
+ },
+ }),
+ ).toBe(false);
+ });
+
+ it("should detect Chat Completions API formats", () => {
+ // Request format with {tools, messages}
+ expect(
+ openAIAdapter.detect({
+ metadata: {
+ tools: [{ type: "function", function: { name: "test" } }],
+ messages: [{ role: "user", content: "test" }],
+ },
+ }),
+ ).toBe(true);
+
+ // Response format with nested tool_calls (via data field)
+ expect(
+ openAIAdapter.detect({
+ data: {
+ role: "assistant",
+ tool_calls: [
+ {
+ id: "call_123",
+ type: "function",
+ function: { name: "get_weather", arguments: "{}" },
+ },
+ ],
+ },
+ }),
+ ).toBe(true);
+ });
+
+ it("should reject Microsoft Agent format with top-level parts", () => {
+ // Microsoft Agent/Gemini use top-level parts, OpenAI uses parts inside content
+ const input = [
+ {
+ role: "user",
+ parts: [{ type: "text", content: "Hello" }],
+ },
+ ];
- expect(
- openAIAdapter.detect({
- metadata: { langgraph_node: "agent", langgraph_step: 3 },
- }),
- ).toBe(false);
+ // Should reject when passed as metadata
+ expect(openAIAdapter.detect({ metadata: input })).toBe(false);
- expect(
- openAIAdapter.detect({
- metadata: {
- messages: [{ type: "human", content: "test" }],
- },
- }),
- ).toBe(false);
+ // Should also reject when passed as data
+ expect(openAIAdapter.detect({ metadata: {}, data: input })).toBe(false);
+ });
});
it("should normalize tool_calls arguments to JSON strings", () => {
@@ -66,12 +112,11 @@ describe("OpenAI Adapter", () => {
const result = normalizeInput(input, { framework: "openai" });
expect(result.success).toBe(true);
- // Verify arguments were stringified (ChatMlSchema nests in json.json due to content union quirk)
- const toolCalls = result.data?.[0].json?.json?.tool_calls;
+ // Verify tool_calls were flattened to ChatML format and arguments were stringified
+ const toolCalls = result.data?.[0].tool_calls;
expect(toolCalls).toBeDefined();
- expect(toolCalls?.[0].function.arguments).toBe(
- '{"city":"NYC","units":"celsius"}',
- );
+ expect(toolCalls?.[0].name).toBe("get_weather");
+ expect(toolCalls?.[0].arguments).toBe('{"city":"NYC","units":"celsius"}');
});
it("should handle multimodal content (array of parts)", () => {
@@ -133,4 +178,73 @@ describe("OpenAI Adapter", () => {
'{"temperature":72,"conditions":"sunny"}',
);
});
+
+ describe("Chat Completions API", () => {
+ it("should handle request format with tools and flatten tool_calls", () => {
+ const input = {
+ tools: [
+ {
+ type: "function",
+ function: {
+ name: "get_weather",
+ description: "Get weather",
+ parameters: { type: "object" },
+ },
+ },
+ ],
+ messages: [
+ {
+ role: "assistant",
+ tool_calls: [
+ {
+ id: "call_abc",
+ type: "function",
+ function: {
+ name: "get_weather",
+ arguments: { location: "NYC" },
+ },
+ },
+ ],
+ },
+ ],
+ };
+
+ const result = normalizeInput(input, { framework: "openai" });
+ expect(result.success).toBe(true);
+
+ // Tools attached to messages
+ expect(result.data?.[0].tools).toHaveLength(1);
+ expect(result.data?.[0].tools?.[0].name).toBe("get_weather");
+
+ // Tool calls flattened
+ expect(result.data?.[0].tool_calls?.[0].name).toBe("get_weather");
+ expect(result.data?.[0].tool_calls?.[0].arguments).toBe(
+ '{"location":"NYC"}',
+ );
+ });
+
+ it("should handle response format with tool calls", () => {
+ const output = {
+ role: "assistant",
+ tool_calls: [
+ {
+ id: "call_xyz",
+ type: "function",
+ function: {
+ name: "query_db",
+ arguments: { query: "test" },
+ },
+ },
+ ],
+ };
+
+ const result = normalizeOutput(output, { framework: "openai" });
+ expect(result.success).toBe(true);
+
+ expect(result.data?.[0].tool_calls?.[0].name).toBe("query_db");
+ expect(result.data?.[0].tool_calls?.[0].arguments).toBe(
+ '{"query":"test"}',
+ );
+ });
+ });
});
diff --git a/web/src/utils/chatml/adapters/openai.ts b/web/src/utils/chatml/adapters/openai.ts
index 40c407d217..9b219194e9 100644
--- a/web/src/utils/chatml/adapters/openai.ts
+++ b/web/src/utils/chatml/adapters/openai.ts
@@ -1,21 +1,135 @@
import type { NormalizerContext, ProviderAdapter } from "../types";
import {
removeNullFields,
- stringifyToolCallArgs,
stringifyToolResultContent,
parseMetadata,
} from "../helpers";
+import { z } from "zod/v4";
+
+/**
+ * Detection schemas for OpenAI formats
+ * These are permissive - only validate structural markers, not full API contracts
+ */
+
+// INPUT SCHEMAS (requests)
+const OpenAIInputChatCompletionsSchema = z.looseObject({
+ messages: z.array(z.any()),
+ tools: z.array(z.any()).optional(),
+});
+
+const OpenAIInputMessagesSchema = z
+ .array(
+ z.looseObject({
+ role: z.enum(["system", "user", "assistant", "tool", "function"]),
+ }),
+ )
+ .refine(
+ (data) => {
+ // Reject if any message has top-level parts (Microsoft Agent/Gemini format)
+ // OpenAI uses parts inside content, not at message level
+ return !data.some(
+ (msg) =>
+ typeof msg === "object" &&
+ msg !== null &&
+ "parts" in msg &&
+ Array.isArray((msg as Record<string, unknown>).parts),
+ );
+ },
+ { message: "Messages with top-level parts are not OpenAI format" },
+ );
+
+// OUTPUT SCHEMAS (responses)
+const OpenAIOutputResponsesSchema = z.looseObject({
+ output: z.array(z.any()),
+ tools: z.array(z.any()).optional(),
+});
+
+const OpenAIOutputChoicesSchema = z.looseObject({
+ model: z.string(),
+ choices: z.array(z.any()),
+});
+
+const OpenAIOutputSingleMessageSchema = z.looseObject({
+ role: z.string(),
+ tool_calls: z.array(
+ z.looseObject({
+ type: z.string(),
+ function: z.looseObject({
+ name: z.string(),
+ }),
+ }),
+ ),
+});
function normalizeMessage(msg: unknown): Record<string, unknown> {
if (!msg || typeof msg !== "object") return {};
let normalized = removeNullFields(msg);
- // Stringify tool_calls arguments
+ // 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"
+ ) {
+ const toolCall: Record<string, unknown> = {
+ id: normalized.call_id || normalized.id || "",
+ name: normalized.name,
+ arguments:
+ typeof normalized.arguments === "string"
+ ? normalized.arguments
+ : JSON.stringify(normalized.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,
+ ...rest
+ } = normalized;
+ /* eslint-enable @typescript-eslint/no-unused-vars */
+ normalized = {
+ ...rest,
+ role: rest.role || "assistant",
+ tool_calls: [toolCall],
+ };
+ }
+
+ // 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 }
if (normalized.tool_calls && Array.isArray(normalized.tool_calls)) {
normalized.tool_calls = (
normalized.tool_calls as Record<string, unknown>[]
- ).map(stringifyToolCallArgs);
+ ).map((tc) => {
+ if (tc.function && typeof tc.function === "object") {
+ const func = tc.function as Record<string, unknown>;
+ return {
+ id: tc.id,
+ name: func.name,
+ arguments:
+ typeof func.arguments === "string"
+ ? func.arguments
+ : JSON.stringify(func.arguments ?? {}),
+ type: tc.type || "function",
+ index: tc.index,
+ };
+ }
+ // Already flat format, just ensure arguments is stringified
+ return {
+ ...tc,
+ arguments:
+ typeof tc.arguments === "string"
+ ? tc.arguments
+ : JSON.stringify(tc.arguments ?? {}),
+ };
+ });
}
// Stringify object content for tool messages
@@ -30,9 +144,63 @@ function normalizeMessage(msg: unknown): Record<string, unknown> {
return normalized;
}
+/**
+ * Flatten tool definition from nested or flat format to standard format
+ * Handles both Chat Completions {type, function: {name, ...}} and flat {name, ...}
+ */
+function flattenToolDefinition(tool: unknown): Record<string, unknown> {
+ if (typeof tool !== "object" || !tool) return {};
+
+ const t = tool as 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;
+ if (toolFunc.parameters != null) toolDef.parameters = toolFunc.parameters;
+ return toolDef;
+}
+
function preprocessData(data: unknown): unknown {
if (!data) return data;
+ // OpenAI Chat Completions API: {tools, messages} OR Responses API: {tools, output}
+ // References:
+ // - https://platform.openai.com/docs/api-reference/chat/create
+ // - https://platform.openai.com/docs/api-reference/responses
+ if (
+ typeof data === "object" &&
+ !Array.isArray(data) &&
+ "tools" in data &&
+ (("messages" in data && !("output" in data)) || "output" in data)
+ ) {
+ const obj = data as Record<string, unknown>;
+ const messagesArray = (obj.messages ?? obj.output) as unknown[];
+
+ if (Array.isArray(messagesArray) && Array.isArray(obj.tools)) {
+ // Attach tools to all messages
+ return messagesArray.map((msg) => ({
+ ...normalizeMessage(msg),
+ tools: (obj.tools as unknown[]).map(flattenToolDefinition),
+ }));
+ }
+ }
+
+ // Chat Completions response: {choices: [{message: {...}}]}
+ if (typeof data === "object" && !Array.isArray(data) && "choices" in data) {
+ const obj = data as Record<string, unknown>;
+ if (Array.isArray(obj.choices) && obj.choices.length > 0) {
+ const firstChoice = obj.choices[0] as Record<string, unknown>;
+ if (
+ firstChoice &&
+ typeof firstChoice === "object" &&
+ "message" in firstChoice
+ ) {
+ return normalizeMessage(firstChoice.message);
+ }
+ }
+ }
+
// Array of messages
if (Array.isArray(data)) {
return data.map(normalizeMessage);
@@ -63,8 +231,9 @@ export const openAIAdapter: ProviderAdapter = {
detect(ctx: NormalizerContext): boolean {
const meta = parseMetadata(ctx.metadata);
- // Explicit rejection: LangGraph/LangChain traces
+ // REJECTIONS: Explicit rejection of LangGraph/LangChain formats
if (meta && typeof meta === "object") {
+ // LangGraph
if (
"langgraph_step" in meta ||
"langgraph_node" in meta ||
@@ -74,105 +243,65 @@ export const openAIAdapter: ProviderAdapter = {
) {
return false;
}
- }
- // Reject if messages have LangChain structure (type without role)
- if (
- typeof ctx.metadata === "object" &&
- ctx.metadata !== null &&
- "messages" in ctx.metadata
- ) {
- const messages = (ctx.metadata as Record<string, unknown>).messages;
- if (Array.isArray(messages)) {
- const hasLangChainType = messages.some((msg: unknown) => {
- const message = msg as Record<string, unknown>;
- return (
- message.type &&
- typeof message.type === "string" &&
- ["human", "ai", "tool", "system"].includes(message.type) &&
- !("role" in message)
- );
- });
- if (hasLangChainType) return false;
+ // LangChain (type without role)
+ if (
+ ctx.metadata &&
+ typeof ctx.metadata === "object" &&
+ "messages" in ctx.metadata
+ ) {
+ const messages = (ctx.metadata as Record<string, unknown>).messages;
+ if (Array.isArray(messages)) {
+ const hasLangChainType = messages.some((msg: unknown) => {
+ const message = msg as Record<string, unknown>;
+ return (
+ message.type &&
+ typeof message.type === "string" &&
+ ["human", "ai", "tool", "system"].includes(message.type) &&
+ !("role" in message)
+ );
+ });
+ if (hasLangChainType) return false;
+ }
}
}
- // Explicit framework override
+ // HINTS: Fast checks for explicit OpenAI indicators
if (ctx.framework === "openai") return true;
-
- // LangSmith metadata
- if (meta?.ls_provider === "openai") return true;
-
- // Observation name hint
if (ctx.observationName?.toLowerCase().includes("openai")) return true;
+ if (meta?.ls_provider === "openai") return true;
- // Structural: has OpenAI-style messages with role
- if (
- typeof ctx.metadata === "object" &&
- ctx.metadata !== null &&
- "messages" in ctx.metadata
- ) {
- const messages = (ctx.metadata as Record<string, unknown>).messages;
- if (Array.isArray(messages)) {
- const hasRole = messages.some((msg: unknown) => {
- const message = msg as Record<string, unknown>;
- return (
- message.role &&
- typeof message.role === "string" &&
- ["system", "user", "assistant", "tool", "function"].includes(
- message.role,
- )
- );
- });
- if (hasRole) return true;
-
- // OpenAI-style tool_calls at top level
- const hasToolCalls = messages.some((msg: unknown) => {
- const message = msg as Record<string, unknown>;
- return (
- message.tool_calls &&
- Array.isArray(message.tool_calls) &&
- message.tool_calls.some((tc: unknown) => {
- const call = tc as Record<string, unknown>;
- return (
- call.type === "function" &&
- call.function &&
- typeof call.function === "object" &&
- typeof (call.function as Record<string, unknown>).name ===
- "string"
- );
- })
- );
- });
- if (hasToolCalls) return true;
-
- // OpenAI multimodal content with specific types
- const hasMultimodal = messages.some((msg: unknown) => {
- const message = msg as Record<string, unknown>;
- return (
- Array.isArray(message.content) &&
- message.content.some((part: unknown) => {
- if (typeof part !== "object" || !part) return false;
- const p = part as Record<string, unknown>;
- return (
- typeof p.type === "string" &&
- ["text", "image_url", "input_audio"].includes(p.type)
- );
- })
- );
- });
- if (hasMultimodal) return true;
+ // Metadata attributes check
+ if (meta && typeof meta === "object" && "attributes" in meta) {
+ const attributes = (meta as Record<string, unknown>).attributes;
+ if (
+ attributes &&
+ typeof attributes === "object" &&
+ (attributes as Record<string, unknown>)["llm.system"] === "openai"
+ ) {
+ return true;
}
}
- // OpenAI output format with choices
- if (
- typeof ctx.metadata === "object" &&
- ctx.metadata !== null &&
- "choices" in ctx.metadata
- ) {
+ // STRUCTURAL: Schema-based detection on metadata
+ if (OpenAIInputChatCompletionsSchema.safeParse(ctx.metadata).success)
+ return true;
+ if (OpenAIInputMessagesSchema.safeParse(ctx.metadata).success) return true;
+ if (OpenAIOutputResponsesSchema.safeParse(ctx.metadata).success)
+ return true;
+ if (OpenAIOutputChoicesSchema.safeParse(ctx.metadata).success) return true;
+ if (OpenAIOutputSingleMessageSchema.safeParse(ctx.metadata).success)
+ return true;
+
+ // finally, test on data if available. we might've done this already if we passed
+ // data into metadata. we only do this last due to performance concerns.
+ if (OpenAIInputChatCompletionsSchema.safeParse(ctx.data).success)
+ return true;
+ if (OpenAIInputMessagesSchema.safeParse(ctx.data).success) return true;
+ if (OpenAIOutputResponsesSchema.safeParse(ctx.data).success) return true;
+ if (OpenAIOutputChoicesSchema.safeParse(ctx.data).success) return true;
+ if (OpenAIOutputSingleMessageSchema.safeParse(ctx.data).success)
return true;
- }
return false;
},
diff --git a/web/src/utils/chatml/extractTools.ts b/web/src/utils/chatml/extractTools.ts
index c6bcb8e51e..9a4b6c995a 100644
--- a/web/src/utils/chatml/extractTools.ts
+++ b/web/src/utils/chatml/extractTools.ts
@@ -1,17 +1,39 @@
import { z } from "zod/v4";
import { OpenAIToolSchema } from "@langfuse/shared";
import type { PlaygroundTool } from "@/src/features/playground/page/types";
-import { extractGeminiToolDefinitions } from "./adapters/gemini";
import { extractAdditionalInput } from "./core";
/**
* Extracts tool definitions from various LLM input formats.
- * Supports OpenAI, LangChain, and Gemini formats.
+ * Supports OpenAI, LangChain, and Microsoft Agent Framework formats.
+ * Note: Gemini tools come from config.tools, extracted by the Gemini adapter during preprocessing.
*
* @param input - Parsed input object (messages array or object with messages)
+ * @param metadata - Optional metadata object that may contain tool definitions
* @returns Array of PlaygroundTool objects with id, name, description, and parameters
*/
-export function extractTools(input: unknown): PlaygroundTool[] {
+export function extractTools(
+ input: unknown,
+ metadata?: unknown,
+): PlaygroundTool[] {
+ // Microsoft Agent Framework: tools in metadata.attributes["gen_ai.tool.definitions"]
+ if (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>;
+ 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,
+ }));
+ }
+ }
+ }
+ }
+
if (!input) return [];
// LangChain format: tools in additional.tools field
@@ -39,32 +61,59 @@ export function extractTools(input: unknown): PlaygroundTool[] {
}
}
- // Gemini format: tool definitions embedded in messages array
+ // LangChain format: tool definitions embedded in messages array
if (Array.isArray(input)) {
- const geminiTools = extractGeminiToolDefinitions(input);
- if (geminiTools.length > 0) {
- return geminiTools.map((tool) => ({
- id: Math.random().toString(36).substring(2),
- ...tool,
- }));
+ const toolMessages = input.filter(
+ (msg: any) =>
+ msg &&
+ typeof msg === "object" &&
+ msg.role === "tool" &&
+ typeof msg.content === "object" &&
+ msg.content?.type === "function" &&
+ msg.content?.function,
+ );
+
+ if (toolMessages.length > 0) {
+ const toolDefs = toolMessages.map((msg: any) => msg.content);
+ const parsedTools = z.array(OpenAIToolSchema).safeParse(toolDefs);
+
+ if (parsedTools.success) {
+ return parsedTools.data.map((tool) => ({
+ id: Math.random().toString(36).substring(2),
+ ...tool.function,
+ }));
+ }
}
}
- // Also check messages field within input object (Gemini nested format)
+ // Also check messages field within input object (LangChain nested format)
if (
typeof input === "object" &&
input !== null &&
"messages" in input &&
Array.isArray((input as Record<string, unknown>).messages)
) {
- const geminiTools = extractGeminiToolDefinitions(
- (input as Record<string, unknown>).messages as unknown[],
+ const messages = (input as Record<string, unknown>).messages as unknown[];
+ const toolMessages = messages.filter(
+ (msg: any) =>
+ msg &&
+ typeof msg === "object" &&
+ msg.role === "tool" &&
+ typeof msg.content === "object" &&
+ msg.content?.type === "function" &&
+ msg.content?.function,
);
- if (geminiTools.length > 0) {
- return geminiTools.map((tool) => ({
- id: Math.random().toString(36).substring(2),
- ...tool,
- }));
+
+ if (toolMessages.length > 0) {
+ const toolDefs = toolMessages.map((msg: any) => msg.content);
+ const parsedTools = z.array(OpenAIToolSchema).safeParse(toolDefs);
+
+ if (parsedTools.success) {
+ return parsedTools.data.map((tool) => ({
+ id: Math.random().toString(36).substring(2),
+ ...tool.function,
+ }));
+ }
}
}
diff --git a/web/src/utils/chatml/integration.clienttest.ts b/web/src/utils/chatml/integration.clienttest.ts
index 1d3e339355..088cb9fb27 100644
--- a/web/src/utils/chatml/integration.clienttest.ts
+++ b/web/src/utils/chatml/integration.clienttest.ts
@@ -173,11 +173,11 @@ describe("ChatML Integration", () => {
if (!outResult.data)
throw new Error("Expected outResult.data to be defined");
expect(outResult.data).toHaveLength(1);
- expect(outResult.data[0].role).toBe("assistant");
+ expect(outResult.data[0].role).toBe("model");
expect(outResult.data[0].content).toContain("Langfuse");
expect(allMessages).toHaveLength(2);
- expect(allMessages[1].role).toBe("assistant");
+ expect(allMessages[1].role).toBe("model");
});
it("should handle Google Gemini format with contents array and system instruction", () => {
@@ -297,10 +297,12 @@ describe("ChatML Integration", () => {
expect(inResult.data[0].role).toBe("system");
expect(inResult.data[1].role).toBe("user");
expect(inResult.data[1].content).toBe("hi");
- expect(inResult.data[2].role).toBe("assistant");
- expect(inResult.data[2].content).not.toContain("[object Object]");
+ expect(inResult.data[2].role).toBe("model");
+ expect(inResult.data[2].tool_calls).toBeDefined();
+ expect(inResult.data[2].tool_calls?.[0].name).toBe("say_hello");
expect(inResult.data[3].role).toBe("user");
- expect(inResult.data[3].content).not.toContain("[object Object]");
+ expect(typeof inResult.data[3].content).toBe("string");
+ expect(inResult.data[3].content).toContain("Hello Langfuse");
});
it("should handle LangGraph messages with type field", () => {
@@ -361,6 +363,43 @@ describe("ChatML Integration", () => {
expect(inResult.data[2].role).toBe("tool");
});
+ it("should handle Microsoft Agent format with simple text parts", () => {
+ // Microsoft Agent format uses top-level parts array (not OpenAI format)
+ const createInput = () => [
+ {
+ role: "user",
+ parts: [
+ {
+ type: "text",
+ content: "What's the weather like in Portland?",
+ },
+ ],
+ },
+ ];
+
+ // Test with generic adapter explicitly
+ const resultWithFramework = normalizeInput(createInput(), {
+ framework: "generic",
+ });
+ expect(resultWithFramework.success).toBe(true);
+ expect(resultWithFramework.data?.[0].content).toBe(
+ "What's the weather like in Portland?",
+ );
+
+ // Test automatic detection (should use generic adapter since OpenAI/Gemini reject parts)
+ const inResult = normalizeInput(createInput(), {
+ observationName: "invoke_agent",
+ });
+
+ expect(inResult.success).toBe(true);
+ if (!inResult.data) throw new Error("Expected data to be defined");
+ expect(inResult.data).toHaveLength(1);
+ expect(inResult.data[0].role).toBe("user");
+ expect(inResult.data[0].content).toBe(
+ "What's the weather like in Portland?",
+ );
+ });
+
it("should handle Microsoft Agent framework format with parts-based tool calls", () => {
const input = [
{
@@ -439,21 +478,20 @@ describe("ChatML Integration", () => {
throw new Error("Expected outResult.data to be defined");
expect(outResult.data).toHaveLength(3);
expect(outResult.data[0].role).toBe("assistant");
- // Tool call should be preserved as structured content
- expect(Array.isArray(outResult.data[0].content)).toBe(true);
- expect(outResult.data[0].content).toEqual([
- {
- type: "tool_call",
- id: ["run_9guMCbt68iSVgtsx6WdKMA18", "call_Sz1QP8T7fuJkIECGDLFWOorq"],
- name: "get_weather",
- arguments: {
- location: "Portland",
- },
- },
- ]);
+ // Tool calls should be extracted to tool_calls field (normalized format)
+ expect(outResult.data[0].tool_calls).toBeDefined();
+ expect(outResult.data[0].tool_calls?.[0].name).toBe("get_weather");
+ expect(outResult.data[0].tool_calls?.[0].id).toBe(
+ "call_Sz1QP8T7fuJkIECGDLFWOorq",
+ );
+ expect(outResult.data[0].tool_calls?.[0].arguments).toBe(
+ '{"location":"Portland"}',
+ );
expect(outResult.data[1].role).toBe("tool");
- expect(Array.isArray(outResult.data[1].content)).toBe(true);
+ expect(outResult.data[1].content).toBe(
+ "The weather in Portland is stormy with a high of 19°C.",
+ );
expect(outResult.data[2].role).toBe("assistant");
expect(outResult.data[2].content).toBe(
diff --git a/web/src/utils/chatml/jumptoplayground.clienttest.ts b/web/src/utils/chatml/jumptoplayground.clienttest.ts
index 5eca3ef335..ae4ff4689e 100644
--- a/web/src/utils/chatml/jumptoplayground.clienttest.ts
+++ b/web/src/utils/chatml/jumptoplayground.clienttest.ts
@@ -1,21 +1,32 @@
// Mock the problematic @langfuse/shared import before importing our functions
-jest.mock("@langfuse/shared", () => ({
- ChatMessageRole: {
- System: "system",
- Developer: "developer",
- User: "user",
- Assistant: "assistant",
- Tool: "tool",
- Model: "model",
- },
- ChatMessageType: {
- PublicAPICreated: "public-api-created",
- AssistantToolCall: "assistant-tool-call",
- ToolResult: "tool-result",
- Placeholder: "placeholder",
- System: "system",
- },
-}));
+jest.mock("@langfuse/shared", () => {
+ const { z } = require("zod/v4");
+ return {
+ ChatMessageRole: {
+ System: "system",
+ Developer: "developer",
+ User: "user",
+ Assistant: "assistant",
+ Tool: "tool",
+ Model: "model",
+ },
+ ChatMessageType: {
+ PublicAPICreated: "public-api-created",
+ AssistantToolCall: "assistant-tool-call",
+ ToolResult: "tool-result",
+ Placeholder: "placeholder",
+ System: "system",
+ },
+ OpenAIToolSchema: z.object({
+ type: z.literal("function"),
+ function: z.object({
+ name: z.string(),
+ description: z.string().optional(),
+ parameters: z.any().optional(),
+ }),
+ }),
+ };
+});
import { normalizeInput } from "./adapters";
import { convertChatMlToPlayground } from "./playgroundConverter";
@@ -203,8 +214,8 @@ describe("Playground Jump Full Pipeline", () => {
}
});
- it("should handle Gemini-style tool definitions embedded in messages", () => {
- // Gemini format embeds tool definitions as messages with role="tool"
+ it("should handle Langchain Gemini-style tool definitions embedded in messages", () => {
+ // Langchain Gemini format embeds tool definitions as messages with role="tool"
// This test verifies that:
// 1. Tool definition messages are filtered out of the message list
// 2. Tool definitions are extracted and available for the playground
@@ -212,9 +223,6 @@ describe("Playground Jump Full Pipeline", () => {
const metadata = {
ls_provider: "google_vertexai",
ls_model_name: "gemini-2.5-flash",
- ls_model_type: "chat",
- ls_temperature: 0,
- ls_max_tokens: 8192,
};
const input = [
@@ -223,7 +231,7 @@ describe("Playground Jump Full Pipeline", () => {
content: "You are a helpful assistant with access to tools.",
},
{
- role: "assistant",
+ role: "model",
content: [
{
type: "text",
@@ -284,7 +292,7 @@ describe("Playground Jump Full Pipeline", () => {
.map(convertChatMlToPlayground)
.filter((msg) => msg !== null);
- // Should have 3 real messages (system, assistant, user)
+ // Should have 3 real messages (system, model, user)
// Tool definition messages should be filtered out by the converter
expect(playgroundMessages.length).toBe(3);
@@ -295,7 +303,7 @@ describe("Playground Jump Full Pipeline", () => {
// Verify message roles
expect(regularMessages[0]?.role).toBe("system");
- expect(regularMessages[1]?.role).toBe("assistant");
+ expect(regularMessages[1]?.role).toBe("model");
expect(regularMessages[2]?.role).toBe("user");
// All should have type public-api-created (regular messages)
@@ -303,8 +311,8 @@ describe("Playground Jump Full Pipeline", () => {
expect(playgroundMessages[1]?.type).toBe("public-api-created");
expect(playgroundMessages[2]?.type).toBe("public-api-created");
- // IMPORTANT: Test that tools are extracted from the Gemini input format
- // The parseTools function in JumpToPlaygroundButton.tsx needs to handle Gemini format
+ // IMPORTANT: Test that tools are extracted from the Langchain Gemini input format
+ // The parseTools function in JumpToPlaygroundButton.tsx needs to handle Langchain Gemini format
// where tool definitions are embedded as messages with role="tool"
// We need to test parseTools behavior directly
@@ -396,4 +404,116 @@ describe("Playground Jump Full Pipeline", () => {
});
expect(tools[1].name).toBe("search_web");
});
+
+ it("should stringify array content in tool messages for playground (eg as from langgraph)", () => {
+ // CodeMirror expects string but got array in tool result content
+ const input = [
+ {
+ role: "tool",
+ content: [{ url: "https://example.com", title: "Example" }],
+ tool_call_id: "call_123",
+ },
+ ];
+
+ const inResult = normalizeInput(input, { framework: "langgraph" });
+ expect(inResult.success).toBe(true);
+
+ const playgroundMsg = convertChatMlToPlayground(inResult.data![0]);
+ expect(playgroundMsg?.type).toBe("tool-result");
+ // Array must be stringified, not left as object
+ if (playgroundMsg && "content" in playgroundMsg) {
+ expect(typeof playgroundMsg.content).toBe("string");
+ expect(playgroundMsg.content).toBe(
+ '[{"url":"https://example.com","title":"Example"}]',
+ );
+ }
+ });
+
+ it("should extract tools from Microsoft Agent Framework metadata", () => {
+ // Microsoft Agent Framework stores tools in metadata.attributes["gen_ai.tool.definitions"]
+ const input = [
+ {
+ role: "user",
+ parts: [
+ {
+ type: "text",
+ content: "What's the weather like in Portland?",
+ },
+ ],
+ },
+ ];
+
+ const metadata = {
+ attributes: {
+ "gen_ai.provider.name": "microsoft.agent_framework",
+ "gen_ai.operation.name": "invoke_agent",
+ "gen_ai.tool.definitions": [
+ {
+ type: "function",
+ function: {
+ name: "get_weather",
+ description: "Get the weather for a given location.",
+ parameters: {
+ properties: {
+ location: {
+ description: "The location to get the weather for.",
+ title: "Location",
+ type: "string",
+ },
+ },
+ required: ["location"],
+ title: "get_weather_input",
+ type: "object",
+ },
+ },
+ },
+ {
+ type: "function",
+ function: {
+ name: "get_time",
+ description: "Get the current time in a timezone.",
+ parameters: {
+ properties: {
+ timezone: {
+ description: "IANA timezone identifier",
+ type: "string",
+ },
+ },
+ required: ["timezone"],
+ type: "object",
+ },
+ },
+ },
+ ],
+ },
+ scope: {
+ name: "agent_framework",
+ version: "1.0.0b251007",
+ },
+ };
+
+ // Test extractTools with metadata parameter
+ const tools = extractTools(input, metadata);
+
+ expect(tools.length).toBe(2);
+ expect(tools[0]).toEqual({
+ id: expect.any(String),
+ name: "get_weather",
+ description: "Get the weather for a given location.",
+ parameters: {
+ properties: {
+ location: {
+ description: "The location to get the weather for.",
+ title: "Location",
+ type: "string",
+ },
+ },
+ required: ["location"],
+ title: "get_weather_input",
+ type: "object",
+ },
+ });
+ expect(tools[1].name).toBe("get_time");
+ expect(tools[1].description).toBe("Get the current time in a timezone.");
+ });
});
diff --git a/web/src/utils/chatml/playgroundConverter.ts b/web/src/utils/chatml/playgroundConverter.ts
index 0cf14ee407..0109352922 100644
--- a/web/src/utils/chatml/playgroundConverter.ts
+++ b/web/src/utils/chatml/playgroundConverter.ts
@@ -20,21 +20,41 @@ export function convertChatMlToPlayground(
// Handle assistant messages with tool calls (from json field)
// Note: ChatMlSchema may nest in json.json due to content union matching
const jsonData = msg.json?.json || msg.json;
- if (jsonData?.tool_calls && Array.isArray(jsonData.tool_calls)) {
- const toolCalls = jsonData.tool_calls.map((tc: any) => {
+ const toolCallsSource = msg.tool_calls || jsonData?.tool_calls;
+
+ if (toolCallsSource && Array.isArray(toolCallsSource)) {
+ const toolCalls = toolCallsSource.map((tc: any) => {
let args: Record<string, unknown>;
- try {
- args =
- typeof tc.function?.arguments === "string"
- ? JSON.parse(tc.function.arguments)
- : (tc.function?.arguments ?? {});
- } catch {
- args = {};
+ let name: string;
+
+ // Handle flat format: {id, name, arguments, type}
+ if (tc.name && !tc.function) {
+ name = tc.name;
+ try {
+ args =
+ typeof tc.arguments === "string"
+ ? JSON.parse(tc.arguments)
+ : (tc.arguments ?? {});
+ } catch {
+ args = {};
+ }
+ }
+ // Handle nested format: {id, type, function: {name, arguments}}
+ else {
+ name = tc.function?.name || "";
+ try {
+ args =
+ typeof tc.function?.arguments === "string"
+ ? JSON.parse(tc.function.arguments)
+ : (tc.function?.arguments ?? {});
+ } catch {
+ args = {};
+ }
}
return {
id: tc.id || "",
- name: tc.function?.name || "",
+ name,
args,
};
});
@@ -47,13 +67,16 @@ export function convertChatMlToPlayground(
};
}
- // Handle tool results (from json field)
- if (jsonData?.tool_call_id || jsonData?.toolCallId) {
+ // Handle tool results
+ // Check top-level field first, then fall back to json field
+ const toolCallId =
+ msg.tool_call_id || jsonData?.tool_call_id || jsonData?.toolCallId;
+ if (toolCallId) {
return {
role: ChatMessageRole.Tool,
content: (msg.content as string) || "",
type: ChatMessageType.ToolResult,
- toolCallId: (jsonData.tool_call_id || jsonData.toolCallId) as string,
+ toolCallId: toolCallId as string,
};
}
diff --git a/web/src/utils/chatml/types.ts b/web/src/utils/chatml/types.ts
index 431a2db804..6b4ea37bb8 100644
--- a/web/src/utils/chatml/types.ts
+++ b/web/src/utils/chatml/types.ts
@@ -2,6 +2,7 @@ export type NormalizerContext = {
metadata?: unknown;
observationName?: string;
framework?: string; // for explicit overrides
+ data?: unknown; // Optional: actual input/output content for structural detection
};
// Unified tool event representation across all providers