Skip to content

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

chore: simplify chatml mappers again (#9716)

Nimar846cb22744b0
diff --git a/web/src/components/trace/IOPreview.tsx b/web/src/components/trace/IOPreview.tsx
index fa140d3b4a..cf63b5e901 100644
--- a/web/src/components/trace/IOPreview.tsx
+++ b/web/src/components/trace/IOPreview.tsx
@@ -18,7 +18,13 @@ import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePos
import useLocalStorage from "@/src/components/useLocalStorage";
import usePreserveRelativeScroll from "@/src/hooks/usePreserveRelativeScroll";
import { MARKDOWN_RENDER_CHARACTER_LIMIT } from "@/src/utils/constants";
-import { mapToLangfuseChatML } from "@/src/utils/langfuse-chatml";
+import {
+ normalizeInput,
+ normalizeOutput,
+ combineInputOutputMessages,
+ cleanLegacyOutput,
+ extractAdditionalInput,
+} from "@/src/utils/chatml";
export const IOPreview: React.FC<{
input?: Prisma.JsonValue;
@@ -65,19 +71,18 @@ export const IOPreview: React.FC<{
const [compensateScrollRef, startPreserveScroll] =
usePreserveRelativeScroll<HTMLDivElement>([selectedView]);
- const chatML = useMemo(
- () =>
- mapToLangfuseChatML(
- input,
- output,
- metadata,
- props.observationName ?? undefined,
- ),
- [input, output, metadata, props.observationName],
- );
- const canDisplayAsChat = chatML.canDisplayAsChat();
- const allMessages = chatML.getAllMessages();
- const additionalInput = chatML.input.additional;
+ const { canDisplayAsChat, allMessages, additionalInput } = useMemo(() => {
+ const ctx = { metadata, observationName: props.observationName };
+ const inResult = normalizeInput(input, ctx);
+ const outResult = normalizeOutput(output, ctx);
+ const outputClean = cleanLegacyOutput(output, output);
+
+ return {
+ canDisplayAsChat: inResult.success || outResult.success,
+ allMessages: combineInputOutputMessages(inResult, outResult, outputClean),
+ additionalInput: extractAdditionalInput(input),
+ };
+ }, [input, output, metadata, props.observationName]);
// Pretty view is available for ChatML content OR any JSON content
const isPrettyViewAvailable = true; // Always show the toggle, let individual components decide how to render
diff --git a/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx b/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
index 3fc33c3410..bbc44bf9cb 100644
--- a/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
+++ b/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
@@ -36,10 +36,8 @@ import {
PromptType,
isGenerationLike,
} from "@langfuse/shared";
-import {
- mapToLangfuseChatML,
- type LangfuseChatMLMessage,
-} from "@/src/utils/langfuse-chatml";
+import { normalizeInput, extractAdditionalInput } from "@/src/utils/chatml";
+import { convertChatMlToPlayground } from "@/src/utils/chatml/playgroundConverter";
import { api } from "@/src/utils/api";
import { cn } from "@/src/utils/tailwind";
import usePlaygroundCache from "@/src/features/playground/page/hooks/usePlaygroundCache";
@@ -213,78 +211,20 @@ export const JumpToPlaygroundButton: React.FC<JumpToPlaygroundButtonProps> = (
);
};
-function convertLangfuseChatMLMessageToPlayground(
- msg: LangfuseChatMLMessage,
-): ChatMessage | PlaceholderMessage | null {
- // Handle placeholder messages
- if (msg.type === "placeholder") {
- return {
- type: ChatMessageType.Placeholder,
- name: msg.name || "",
- } as PlaceholderMessage;
- }
-
- // Handle assistant messages with tool calls
- if (msg.toolCalls && msg.toolCalls.length > 0) {
- return {
- role: ChatMessageRole.Assistant,
- content: (msg.content as string) || "",
- type: ChatMessageType.AssistantToolCall,
- toolCalls: msg.toolCalls.map((tc) => {
- // Parse JSON string to object, with safety
- let args: Record<string, unknown>;
- try {
- args = JSON.parse(tc.function.arguments);
- } catch {
- // If parsing fails, treat as empty args
- args = {};
- }
-
- return {
- id: tc.id || "", // Playground requires string, convert null to empty
- name: tc.function.name,
- args,
- };
- }),
- };
- }
-
- // Handle tool results with tool role
- if (msg.toolCallId) {
- return {
- role: ChatMessageRole.Tool,
- content: (msg.content as string) || "",
- type: ChatMessageType.ToolResult,
- toolCallId: msg.toolCallId,
- };
- }
-
- // Handle regular messages
- const content =
- typeof msg.content === "string"
- ? msg.content
- : msg.content === null || msg.content === undefined
- ? ""
- : JSON.stringify(msg.content);
-
- return {
- role: (msg.role as ChatMessageRole) || ChatMessageRole.Assistant,
- content,
- type: ChatMessageType.PublicAPICreated,
- };
-}
-
const parsePrompt = (
prompt: Prompt & { resolvedPrompt?: Prisma.JsonValue },
): PlaygroundCache => {
if (prompt.type === PromptType.Chat) {
- // Use mapper system for all framework detection and normalization
try {
- const chatML = mapToLangfuseChatML(prompt.resolvedPrompt, null);
+ const inResult = normalizeInput(prompt.resolvedPrompt);
- const messages = chatML.input.messages
- .map(convertLangfuseChatMLMessageToPlayground)
- .filter((msg): msg is ChatMessage | PlaceholderMessage => msg !== null);
+ const messages = inResult.success
+ ? inResult.data
+ .map(convertChatMlToPlayground)
+ .filter(
+ (msg): msg is ChatMessage | PlaceholderMessage => msg !== null,
+ )
+ : [];
if (messages.length === 0) return null;
@@ -363,19 +303,25 @@ const parseGeneration = (
}
}
- // use mapper: input is an object
if (typeof input === "object") {
try {
- const chatML = mapToLangfuseChatML(
- input,
- generation.output,
- generation.metadata,
- generation.name ?? undefined,
- );
+ const ctx = {
+ metadata:
+ typeof generation.metadata === "string"
+ ? JSON.parse(generation.metadata)
+ : generation.metadata,
+ observationName: generation.name ?? undefined,
+ };
+
+ const inResult = normalizeInput(input, ctx);
- const messages = chatML.input.messages
- .map(convertLangfuseChatMLMessageToPlayground)
- .filter((msg): msg is ChatMessage | PlaceholderMessage => msg !== null);
+ const messages = inResult.success
+ ? inResult.data
+ .map(convertChatMlToPlayground)
+ .filter(
+ (msg): msg is ChatMessage | PlaceholderMessage => msg !== null,
+ )
+ : [];
if (messages.length === 0) return null;
@@ -442,31 +388,21 @@ function parseTools(
metadata: string | null;
},
): PlaygroundTool[] {
- // Use mapper to extract tools from all frameworks
try {
const input = JSON.parse(generation.input as string);
- const chatML = mapToLangfuseChatML(
- input,
- generation.output,
- generation.metadata,
- generation.name ?? undefined,
- );
-
- // Tools extracted by mappers (LangChain puts them in additional.tools)
- if (
- chatML.input.additional?.tools &&
- Array.isArray(chatML.input.additional.tools)
- ) {
- return chatML.input.additional.tools.map((tool: any) => ({
+ // Check additional.tools , langchain puts tools there
+ const additionalInput = extractAdditionalInput(input);
+ if (additionalInput?.tools && Array.isArray(additionalInput.tools)) {
+ return additionalInput.tools.map((tool: any) => ({
id: Math.random().toString(36).substring(2),
- name: tool.name,
- description: tool.description,
- parameters: tool.parameters,
+ name: tool.name || tool.function?.name,
+ description: tool.description || tool.function?.description,
+ parameters: tool.parameters || tool.function?.parameters,
}));
}
- // OpenAI format: tools in input.tools field (not extracted by mapper)
+ // OpenAI format: tools in input.tools field
if (typeof input === "object" && input !== null && "tools" in input) {
const parsedTools = z.array(OpenAIToolSchema).safeParse(input["tools"]);
diff --git a/web/src/utils/chatml/README.md b/web/src/utils/chatml/README.md
new file mode 100644
index 0000000000..af1006c427
--- /dev/null
+++ b/web/src/utils/chatml/README.md
@@ -0,0 +1,47 @@
+# ChatML Normalization System
+
+Normalizes LLM provider/framework data (traces, observations) to ChatML format for display and, partly, playground.
+In general, provider adapters preprocess data → ChatMlSchema validates → UI renders
+
+## Usage
+
+### Display (IOPreview)
+```typescript
+import { normalizeInput, normalizeOutput, combineInputOutputMessages } from "@/src/utils/chatml";
+
+const ctx = { metadata, observationName };
+const inResult = normalizeInput(input, ctx);
+const outResult = normalizeOutput(output, ctx);
+const allMessages = combineInputOutputMessages(inResult, outResult, output);
+```
+
+### Playground
+```typescript
+import { normalizeInput } from "@/src/utils/chatml";
+import { convertChatMlToPlayground } from "@/src/utils/chatml/playgroundConverter";
+
+const inResult = normalizeInput(input, { metadata });
+const playgroundMessages = inResult.success
+ ? inResult.data.map(convertChatMlToPlayground)
+ : [];
+```
+
+## Adding a Provider
+
+1. Create `adapters/yourprovider.ts`:
+```typescript
+export const yourProviderAdapter: ProviderAdapter = {
+ id: "yourprovider",
+ detect(ctx) {
+ return ctx.metadata?.provider === "yourprovider";
+ },
+ preprocess(data, kind, ctx) {
+ // Normalize messages, stringify tool args, etc.
+ return normalizedData;
+ },
+};
+```
+
+2. Add to `adapters/index.ts` registry before generic adapter
+
+3. Write tests in `provider.clienttest.ts`
diff --git a/web/src/utils/chatml/adapters/generic.clienttest.ts b/web/src/utils/chatml/adapters/generic.clienttest.ts
new file mode 100644
index 0000000000..d5fd4d25a7
--- /dev/null
+++ b/web/src/utils/chatml/adapters/generic.clienttest.ts
@@ -0,0 +1,81 @@
+jest.mock("@langfuse/shared", () => ({
+ ChatMessageRole: {
+ System: "system",
+ Developer: "developer",
+ User: "user",
+ Assistant: "assistant",
+ Tool: "tool",
+ Model: "model",
+ },
+}));
+
+import { normalizeInput, normalizeOutput } from "./index";
+import { combineInputOutputMessages, cleanLegacyOutput } from "../core";
+import { genericAdapter } from "./generic";
+
+describe("Generic Adapter", () => {
+ it("should always detect (fallback)", () => {
+ expect(genericAdapter.detect({})).toBe(true);
+ expect(genericAdapter.detect({ metadata: { anything: "value" } })).toBe(
+ true,
+ );
+ });
+
+ it("should handle basic ChatML format", () => {
+ const input = [
+ { role: "user", content: "Hello!" },
+ { role: "assistant", content: "Hi there!" },
+ ];
+ const output = { role: "assistant", content: "Response" };
+
+ const inResult = normalizeInput(input);
+ const outResult = normalizeOutput(output);
+ const allMessages = combineInputOutputMessages(
+ inResult,
+ outResult,
+ cleanLegacyOutput(output, output),
+ );
+
+ expect(inResult.success).toBe(true);
+ expect(outResult.success).toBe(true);
+ expect(allMessages).toHaveLength(3);
+ expect(allMessages).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ role: "user", content: "Hello!" }),
+ expect.objectContaining({ role: "assistant", content: "Hi there!" }),
+ expect.objectContaining({ role: "assistant", content: "Response" }),
+ ]),
+ );
+ });
+
+ it("should not display non-ChatML formats as chat", () => {
+ const input = {
+ new_message: {
+ parts: [{ text: "hi" }],
+ role: "user",
+ },
+ run_config: {
+ streaming_mode: "StreamingMode.NONE",
+ },
+ };
+
+ const output = {
+ content: {
+ parts: [{ text: "Hello!" }],
+ role: "model",
+ },
+ finish_reason: "STOP",
+ };
+
+ const inResult = normalizeInput(input);
+ const outResult = normalizeOutput(output);
+ const allMessages = combineInputOutputMessages(
+ inResult,
+ outResult,
+ cleanLegacyOutput(output, output),
+ );
+
+ expect(inResult.success).toBe(false);
+ expect(allMessages).toHaveLength(0);
+ });
+});
diff --git a/web/src/utils/chatml/adapters/generic.ts b/web/src/utils/chatml/adapters/generic.ts
new file mode 100644
index 0000000000..650e4b127d
--- /dev/null
+++ b/web/src/utils/chatml/adapters/generic.ts
@@ -0,0 +1,138 @@
+import type { NormalizerContext, ProviderAdapter } from "../types";
+
+function normalizeGoogleMessage(msg: unknown): Record<string, unknown> {
+ if (!msg || typeof msg !== "object") return {};
+
+ const message = msg as Record<string, unknown>;
+ let normalized = { ...message };
+
+ // Google/Gemini: "model" role → "assistant"
+ if (message.role === "model") {
+ normalized.role = "assistant";
+ }
+
+ // Google/Gemini: "parts" field → "content" field
+ if (message.parts && Array.isArray(message.parts)) {
+ // Check if parts contain function_call or function_response
+ const hasFunctionCall = message.parts.some((p: unknown) => {
+ const part = p as Record<string, unknown>;
+ return part.function_call;
+ });
+ const hasFunctionResponse = message.parts.some((p: unknown) => {
+ const part = p as Record<string, unknown>;
+ return part.function_response;
+ });
+
+ if (hasFunctionCall || hasFunctionResponse) {
+ // Keep parts as structured content array
+ normalized.content = message.parts;
+ } else {
+ // Extract text from parts
+ const content = message.parts
+ .map((part: unknown) => {
+ if (typeof part === "object" && part !== null) {
+ const p = part as Record<string, unknown>;
+ if (p.text) {
+ return p.text;
+ }
+ }
+ // Only stringify if it's actually a simple value, not an object
+ if (typeof part === "string" || typeof part === "number") {
+ return String(part);
+ }
+ return "";
+ })
+ .filter((text: unknown) => text !== "")
+ .join("");
+ normalized.content = content;
+ }
+ delete normalized.parts;
+ }
+
+ return normalized;
+}
+
+function preprocessData(data: unknown): unknown {
+ if (!data) return data;
+
+ // Handle Google output format: {candidates: [{content: {parts, role}}]}
+ if (
+ typeof data === "object" &&
+ "candidates" in data &&
+ Array.isArray((data as Record<string, unknown>).candidates)
+ ) {
+ const obj = data as Record<string, unknown>;
+ const candidate = (obj.candidates as Record<string, unknown>[])[0];
+ if (candidate?.content) {
+ return normalizeGoogleMessage(candidate.content);
+ }
+ }
+
+ // Handle Google input format: {model: "...", contents: [...]} or {contents: "string"}
+ if (typeof data === "object" && "contents" in data && !("messages" in data)) {
+ const obj = data as Record<string, unknown>;
+ const contents = obj.contents;
+ const messages: Record<string, unknown>[] = [];
+
+ // Handle system_instruction if present
+ const config = obj.config as Record<string, unknown> | undefined;
+ if (config?.system_instruction) {
+ messages.push({
+ role: "system",
+ content: config.system_instruction,
+ });
+ }
+
+ // Convert contents to ChatML format
+ if (typeof contents === "string") {
+ messages.push({ role: "user", content: contents });
+ } else if (Array.isArray(contents)) {
+ messages.push(...contents.map(normalizeGoogleMessage));
+ }
+
+ return messages.length > 0 ? messages : data;
+ }
+
+ // Array of messages
+ if (Array.isArray(data)) {
+ // Handle nested array format: [[ChatML...]]
+ if (data.length === 1 && Array.isArray(data[0])) {
+ return data[0].map(normalizeGoogleMessage);
+ }
+ return data.map(normalizeGoogleMessage);
+ }
+
+ // 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(normalizeGoogleMessage)
+ : obj.messages,
+ };
+ }
+
+ // Single message
+ if (typeof data === "object" && ("role" in data || "parts" in data)) {
+ return normalizeGoogleMessage(data);
+ }
+
+ return data;
+}
+
+export const genericAdapter: ProviderAdapter = {
+ id: "generic",
+
+ detect(_ctx: NormalizerContext): boolean {
+ return true; // fallback
+ },
+
+ preprocess(
+ data: unknown,
+ _kind: "input" | "output",
+ _ctx: NormalizerContext,
+ ): unknown {
+ return preprocessData(data);
+ },
+};
diff --git a/web/src/utils/chatml/adapters/index.ts b/web/src/utils/chatml/adapters/index.ts
new file mode 100644
index 0000000000..9e04ac4fb4
--- /dev/null
+++ b/web/src/utils/chatml/adapters/index.ts
@@ -0,0 +1,39 @@
+import type { NormalizerContext, ProviderAdapter } from "../types";
+import { mapToChatMl, mapOutputToChatMl } from "../core";
+import { openAIAdapter } from "./openai";
+import { genericAdapter } from "./generic";
+
+const adapters: ProviderAdapter[] = [
+ openAIAdapter,
+ // Add more adapters here as needed
+ genericAdapter, // Always last (fallback)
+];
+
+function selectAdapter(ctx: NormalizerContext): ProviderAdapter {
+ // Explicit override
+ if (ctx.framework) {
+ const adapter = adapters.find((a) => a.id === ctx.framework);
+ if (adapter) return adapter;
+ }
+
+ // First adapter that matches wins
+ for (const adapter of adapters) {
+ if (adapter.detect(ctx)) {
+ return adapter;
+ }
+ }
+
+ return genericAdapter;
+}
+
+export function normalizeInput(input: unknown, ctx: NormalizerContext = {}) {
+ const adapter = selectAdapter({ ...ctx, metadata: ctx.metadata ?? 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 preprocessed = adapter.preprocess(output, "output", ctx);
+ return mapOutputToChatMl(preprocessed);
+}
diff --git a/web/src/utils/chatml/adapters/openai.clienttest.ts b/web/src/utils/chatml/adapters/openai.clienttest.ts
new file mode 100644
index 0000000000..14daa294de
--- /dev/null
+++ b/web/src/utils/chatml/adapters/openai.clienttest.ts
@@ -0,0 +1,120 @@
+jest.mock("@langfuse/shared", () => ({
+ ChatMessageRole: {
+ System: "system",
+ Developer: "developer",
+ User: "user",
+ Assistant: "assistant",
+ Tool: "tool",
+ Model: "model",
+ },
+}));
+
+import { normalizeInput } from "./index";
+import { openAIAdapter } from "./openai";
+
+describe("OpenAI Adapter", () => {
+ it("should detect OpenAI via metadata", () => {
+ expect(
+ openAIAdapter.detect({ metadata: { scope: { name: "langfuse-sdk" } } }),
+ ).toBe(true);
+
+ expect(openAIAdapter.detect({ observationName: "OpenAI-generation" })).toBe(
+ true,
+ );
+
+ expect(openAIAdapter.detect({ metadata: { framework: "langgraph" } })).toBe(
+ false,
+ );
+ });
+
+ it("should normalize tool_calls arguments to JSON strings", () => {
+ const input = {
+ messages: [
+ {
+ role: "assistant",
+ content: "",
+ tool_calls: [
+ {
+ id: "call_abc",
+ type: "function",
+ function: {
+ name: "get_weather",
+ arguments: { city: "NYC", units: "celsius" },
+ },
+ },
+ ],
+ },
+ ],
+ };
+
+ 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;
+ expect(toolCalls).toBeDefined();
+ expect(toolCalls?.[0].function.arguments).toBe(
+ '{"city":"NYC","units":"celsius"}',
+ );
+ });
+
+ it("should handle multimodal content (array of parts)", () => {
+ const input = {
+ messages: [
+ {
+ role: "user",
+ content: [
+ { type: "text", text: "What's in this image?" },
+ {
+ type: "image_url",
+ image_url: { url: "https://example.com/image.jpg" },
+ },
+ ],
+ },
+ ],
+ };
+
+ const result = normalizeInput(input, { framework: "openai" });
+ expect(result.success).toBe(true);
+ expect(Array.isArray(result.data?.[0].content)).toBe(true);
+ });
+
+ it("should remove null fields from messages", () => {
+ const input = {
+ messages: [
+ {
+ role: "user",
+ content: "Hello",
+ tool_call_id: null,
+ name: null,
+ },
+ ],
+ };
+
+ const result = normalizeInput(input, { framework: "openai" });
+ expect(result.success).toBe(true);
+
+ // When all extra fields are null and removed, json field won't exist (correct behavior)
+ expect(result.data?.[0].role).toBe("user");
+ expect(result.data?.[0].content).toBe("Hello");
+ });
+
+ it("should stringify tool message object content", () => {
+ const input = {
+ messages: [
+ {
+ role: "tool",
+ content: { temperature: 72, conditions: "sunny" },
+ tool_call_id: "call_123",
+ },
+ ],
+ };
+
+ const result = normalizeInput(input, { framework: "openai" });
+ expect(result.success).toBe(true);
+ expect(typeof result.data?.[0].content).toBe("string");
+ expect(result.data?.[0].content).toBe(
+ '{"temperature":72,"conditions":"sunny"}',
+ );
+ });
+});
diff --git a/web/src/utils/chatml/adapters/openai.ts b/web/src/utils/chatml/adapters/openai.ts
new file mode 100644
index 0000000000..bf0fa39b6a
--- /dev/null
+++ b/web/src/utils/chatml/adapters/openai.ts
@@ -0,0 +1,121 @@
+import type { NormalizerContext, ProviderAdapter } from "../types";
+import {
+ removeNullFields,
+ stringifyToolCallArgs,
+ stringifyToolResultContent,
+ parseMetadata,
+ getNestedProperty,
+} from "../helpers";
+
+function normalizeMessage(msg: unknown): Record<string, unknown> {
+ if (!msg || typeof msg !== "object") return {};
+
+ let normalized = removeNullFields(msg);
+
+ // 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);
+ }
+
+ // Stringify object content for tool messages
+ if (
+ normalized.role === "tool" &&
+ typeof normalized.content === "object" &&
+ !Array.isArray(normalized.content)
+ ) {
+ normalized.content = stringifyToolResultContent(normalized.content);
+ }
+
+ return normalized;
+}
+
+function preprocessData(data: unknown): unknown {
+ if (!data) return data;
+
+ // Array of messages
+ if (Array.isArray(data)) {
+ return data.map(normalizeMessage);
+ }
+
+ // 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,
+ };
+ }
+
+ // Single message
+ if (typeof data === "object" && "role" in data) {
+ return normalizeMessage(data);
+ }
+
+ return data;
+}
+
+export const openAIAdapter: ProviderAdapter = {
+ id: "openai",
+
+ detect(ctx: NormalizerContext): boolean {
+ const meta = parseMetadata(ctx.metadata);
+
+ // LangSmith metadata
+ if (meta?.ls_provider === "openai") return true;
+
+ // OpenTelemetry langfuse-sdk (OpenAI auto-instrumentation)
+ if (getNestedProperty(meta, "scope", "name") === "langfuse-sdk")
+ return true;
+
+ // Observation name hint
+ if (ctx.observationName?.toLowerCase().includes("openai")) return true;
+
+ // Structural: has OpenAI-style tool_calls
+ 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 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.id === "string"
+ );
+ })
+ );
+ });
+ if (hasToolCalls) return true;
+
+ // Multimodal content
+ const hasMultimodal = messages.some((msg: unknown) => {
+ const message = msg as Record<string, unknown>;
+ return Array.isArray(message.content);
+ });
+ if (hasMultimodal) return true;
+ }
+ }
+
+ return false;
+ },
+
+ preprocess(
+ data: unknown,
+ _kind: "input" | "output",
+ _ctx: NormalizerContext,
+ ): unknown {
+ return preprocessData(data);
+ },
+};
diff --git a/web/src/utils/chatml/core.ts b/web/src/utils/chatml/core.ts
new file mode 100644
index 0000000000..1e11cfaeea
--- /dev/null
+++ b/web/src/utils/chatml/core.ts
@@ -0,0 +1,103 @@
+import { z } from "zod/v4";
+import {
+ ChatMlArraySchema,
+ type ChatMlMessageSchema,
+} from "@/src/components/schemas/ChatMlSchema";
+
+export function mapToChatMl(
+ input: unknown,
+): ReturnType<typeof ChatMlArraySchema.safeParse> {
+ let result = ChatMlArraySchema.safeParse(input);
+ if (result.success) {
+ return result;
+ }
+
+ // Check if input is an array of length 1 including an array of ChatMlMessageSchema
+ // e.g. [[ChatMlMessageSchema, ...]]
+ const inputArray = z.array(ChatMlArraySchema).safeParse(input);
+ if (inputArray.success && inputArray.data.length === 1) {
+ return ChatMlArraySchema.safeParse(inputArray.data[0]);
+ }
+
+ // Check if input is an object with a messages key
+ // e.g. { messages: [ChatMlMessageSchema, ...] }
+ const inputObject = z
+ .object({
+ messages: ChatMlArraySchema,
+ })
+ .safeParse(input);
+
+ if (inputObject.success) {
+ return ChatMlArraySchema.safeParse(inputObject.data.messages);
+ }
+
+ return result;
+}
+
+export function mapOutputToChatMl(
+ output: unknown,
+): ReturnType<typeof ChatMlArraySchema.safeParse> {
+ const result = ChatMlArraySchema.safeParse(
+ Array.isArray(output) ? output : [output],
+ );
+
+ return result;
+}
+
+export function cleanLegacyOutput(output: unknown, fallback?: unknown) {
+ const outLegacyCompletionSchema = z
+ .object({
+ completion: z.string(),
+ })
+ .refine((value) => Object.keys(value).length === 1);
+
+ const outLegacyCompletionSchemaParsed =
+ outLegacyCompletionSchema.safeParse(output);
+ const outputClean = outLegacyCompletionSchemaParsed.success
+ ? outLegacyCompletionSchemaParsed.data
+ : (fallback ?? null);
+
+ return outputClean;
+}
+
+export function extractAdditionalInput(
+ input: unknown,
+): Record<string, unknown> | undefined {
+ const additionalInput =
+ typeof input === "object" && input !== null && !Array.isArray(input)
+ ? Object.fromEntries(
+ Object.entries(input as object).filter(([key]) => key !== "messages"),
+ )
+ : undefined;
+
+ return additionalInput;
+}
+
+export function combineInputOutputMessages(
+ inputResult: ReturnType<typeof mapToChatMl>,
+ outputResult: ReturnType<typeof mapOutputToChatMl>,
+ cleanOutput: unknown,
+): ChatMlMessageSchema[] {
+ if (!inputResult.success) {
+ return [];
+ }
+
+ const combinedMessages = [
+ ...inputResult.data,
+ ...(outputResult.success
+ ? outputResult.data.map((m) => ({
+ ...m,
+ role: m.role ?? "assistant",
+ }))
+ : [
+ {
+ role: "assistant",
+ ...(typeof cleanOutput === "string"
+ ? { content: cleanOutput }
+ : { json: cleanOutput }),
+ } as ChatMlMessageSchema,
+ ]),
+ ];
+
+ return combinedMessages;
+}
diff --git a/web/src/utils/chatml/helpers.ts b/web/src/utils/chatml/helpers.ts
new file mode 100644
index 0000000000..e35881e1ba
--- /dev/null
+++ b/web/src/utils/chatml/helpers.ts
@@ -0,0 +1,69 @@
+export function removeNullFields(obj: unknown): Record<string, unknown> {
+ if (!obj || typeof obj !== "object") return {};
+
+ const cleaned: Record<string, unknown> = { ...obj };
+
+ Object.keys(cleaned).forEach((key) => {
+ if (cleaned[key] === null) {
+ delete cleaned[key];
+ }
+ });
+
+ return cleaned;
+}
+
+export function stringifyToolCallArgs(
+ toolCall: Record<string, unknown>,
+): Record<string, unknown> {
+ if (!toolCall?.function) return toolCall;
+
+ const func = toolCall.function as Record<string, unknown>;
+ return {
+ ...toolCall,
+ function: {
+ ...func,
+ arguments:
+ typeof func.arguments === "string"
+ ? func.arguments
+ : JSON.stringify(func.arguments ?? {}),
+ },
+ };
+}
+
+export function stringifyToolResultContent(content: unknown): string {
+ if (typeof content === "string") return content;
+ if (content === null || content === undefined) return "";
+ return JSON.stringify(content);
+}
+
+export function parseMetadata(
+ metadata: unknown,
+): Record<string, unknown> | null {
+ if (!metadata) return null;
+
+ if (typeof metadata === "string") {
+ try {
+ return JSON.parse(metadata);
+ } catch {
+ return null;
+ }
+ }
+
+ if (typeof metadata === "object") {
+ return metadata as Record<string, unknown>;
+ }
+
+ return null;
+}
+
+export function getNestedProperty(
+ obj: Record<string, unknown> | null | undefined,
+ ...path: string[]
+): unknown {
+ let current: unknown = obj;
+ for (const key of path) {
+ if (!current || typeof current !== "object") return undefined;
+ current = (current as Record<string, unknown>)[key];
+ }
+ return current;
+}
diff --git a/web/src/utils/chatml/index.ts b/web/src/utils/chatml/index.ts
new file mode 100644
index 0000000000..65491b9a28
--- /dev/null
+++ b/web/src/utils/chatml/index.ts
@@ -0,0 +1,11 @@
+export {
+ mapToChatMl,
+ mapOutputToChatMl,
+ cleanLegacyOutput,
+ extractAdditionalInput,
+ combineInputOutputMessages,
+} from "./core";
+
+export { normalizeInput, normalizeOutput } from "./adapters";
+
+export type { NormalizerContext, ProviderAdapter, ToolEvent } from "./types";
diff --git a/web/src/utils/chatml/integration.clienttest.ts b/web/src/utils/chatml/integration.clienttest.ts
new file mode 100644
index 0000000000..4306a898be
--- /dev/null
+++ b/web/src/utils/chatml/integration.clienttest.ts
@@ -0,0 +1,305 @@
+jest.mock("@langfuse/shared", () => ({
+ ChatMessageRole: {
+ System: "system",
+ Developer: "developer",
+ User: "user",
+ Assistant: "assistant",
+ Tool: "tool",
+ Model: "model",
+ },
+}));
+
+import { normalizeInput, normalizeOutput } from "./adapters";
+import {
+ combineInputOutputMessages,
+ cleanLegacyOutput,
+ extractAdditionalInput,
+} from "./core";
+
+describe("ChatML Integration", () => {
+ it("should handle OpenAI multimodal format", () => {
+ const input = {
+ messages: [
+ {
+ role: "user",
+ content: [
+ { type: "text", text: "What's in this image?" },
+ {
+ type: "image_url",
+ image_url: { url: "data:image/jpeg;base64,..." },
+ },
+ ],
+ },
+ ],
+ temperature: 0.7,
+ model: "gpt-4-vision-preview",
+ };
+
+ const ctx = { metadata: { scope: { name: "langfuse-sdk" } } };
+ const inResult = normalizeInput(input, ctx);
+ const additionalInput = extractAdditionalInput(input);
+
+ expect(inResult.success).toBe(true);
+ expect(inResult.data).toHaveLength(1);
+ expect(Array.isArray(inResult.data?.[0].content)).toBe(true);
+ expect(additionalInput).toEqual({
+ temperature: 0.7,
+ model: "gpt-4-vision-preview",
+ });
+ });
+
+ it("should handle nested array format [[ChatML...]]", () => {
+ const input = [
+ [
+ { role: "system", content: "You are a helpful assistant." },
+ { role: "user", content: "Hello!" },
+ ],
+ ];
+ const output = { role: "assistant", content: "Hi there!" };
+
+ const inResult = normalizeInput(input);
+ const outResult = normalizeOutput(output);
+ const allMessages = combineInputOutputMessages(inResult, outResult, output);
+
+ expect(inResult.success).toBe(true);
+ if (!inResult.data) throw new Error("Expected data to be defined");
+ expect(inResult.data).toHaveLength(2);
+ expect(allMessages).toHaveLength(3);
+ });
+
+ it("should handle legacy completion format {completion: string}", () => {
+ const input = [{ role: "user", content: "Write a haiku" }];
+ const output = {
+ completion:
+ "Cherry blossoms fall\nSoftly on the morning dew\nSpring has come at last",
+ };
+
+ const inResult = normalizeInput(input);
+ const outResult = normalizeOutput(output);
+ const outputClean = cleanLegacyOutput(output, output);
+ const allMessages = combineInputOutputMessages(
+ inResult,
+ outResult,
+ outputClean,
+ );
+
+ expect(inResult.success).toBe(true);
+ expect(allMessages).toHaveLength(2);
+ expect(allMessages[1].json).toEqual({
+ completion:
+ "Cherry blossoms fall\nSoftly on the morning dew\nSpring has come at last",
+ });
+ });
+
+ it("should handle placeholder messages", () => {
+ const input = [
+ { role: "user", content: "Hello" },
+ { type: "placeholder", name: "Processing" },
+ { role: "assistant", content: "Hi there!" },
+ ];
+ const output = { role: "assistant", content: "How can I help?" };
+
+ const inResult = normalizeInput(input);
+ const outResult = normalizeOutput(output);
+ const allMessages = combineInputOutputMessages(inResult, outResult, output);
+
+ expect(inResult.success).toBe(true);
+ expect(allMessages).toHaveLength(4);
+ expect(allMessages[1].type).toBe("placeholder");
+ });
+
+ it("should handle circular references gracefully", () => {
+ const input: any = [{ role: "user", content: "test" }];
+ input[0].circular = input[0];
+
+ expect(() => normalizeInput(input)).not.toThrow();
+ });
+
+ it("should handle very large inputs", () => {
+ const largeContent = "x".repeat(1000000);
+ const input = [{ role: "user", content: largeContent }];
+
+ const inResult = normalizeInput(input);
+
+ expect(inResult.success).toBe(true);
+ expect(inResult.data?.[0].content).toHaveLength(1000000);
+ });
+
+ it("should handle Google Gemini format with simple string contents", () => {
+ const input = {
+ model: "gemini-2.5-flash",
+ contents: "What is Langfuse?",
+ };
+ const output = {
+ candidates: [
+ {
+ content: {
+ parts: [
+ {
+ text: "**Langfuse** is an **open-source observability and evaluation platform** for LLM applications.",
+ },
+ ],
+ role: "model",
+ },
+ finish_reason: "STOP",
+ index: 0,
+ },
+ ],
+ model_version: "gemini-2.5-flash",
+ usage_metadata: {
+ candidates_token_count: 20,
+ prompt_token_count: 6,
+ total_token_count: 26,
+ },
+ };
+
+ const ctx = {
+ metadata: {
+ scope: { name: "openinference.instrumentation.google_genai" },
+ },
+ };
+
+ const inResult = normalizeInput(input, ctx);
+ const outResult = normalizeOutput(output, ctx);
+ const allMessages = combineInputOutputMessages(inResult, outResult, output);
+
+ expect(inResult.success).toBe(true);
+ if (!inResult.data) throw new Error("Expected inResult.data to be defined");
+ expect(inResult.data).toHaveLength(1);
+ expect(inResult.data[0].role).toBe("user");
+ expect(inResult.data[0].content).toBe("What is Langfuse?");
+
+ expect(outResult.success).toBe(true);
+ 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].content).toContain("Langfuse");
+
+ expect(allMessages).toHaveLength(2);
+ expect(allMessages[1].role).toBe("assistant");
+ });
+
+ it("should handle Google Gemini format with contents array and system instruction", () => {
+ const input = {
+ model: "gemini-2.0-flash",
+ config: {
+ http_options: {
+ headers: {
+ "x-goog-api-client": "google-adk/1.12.0 gl-python/3.12.11",
+ "user-agent": "google-adk/1.12.0 gl-python/3.12.11",
+ },
+ },
+ system_instruction:
+ 'Always greet using the say_hello tool.\n\nYou are an agent. Your internal name is "hello_agent".',
+ tools: [
+ {
+ function_declarations: [
+ {
+ name: "say_hello",
+ },
+ ],
+ },
+ ],
+ },
+ contents: [
+ {
+ parts: [
+ {
+ text: "hi",
+ },
+ ],
+ role: "user",
+ },
+ ],
+ };
+
+ const ctx = {
+ metadata: {
+ scope: { name: "openinference.instrumentation.google_genai" },
+ },
+ };
+
+ const inResult = normalizeInput(input, ctx);
+
+ expect(inResult.success).toBe(true);
+ if (!inResult.data) throw new Error("Expected data to be defined");
+ expect(inResult.data).toHaveLength(2);
+ expect(inResult.data[0].role).toBe("system");
+ expect(inResult.data[0].content).toContain("hello_agent");
+ expect(inResult.data[1].role).toBe("user");
+ expect(inResult.data[1].content).toBe("hi");
+ });
+
+ it("should handle Google Gemini format with function_call and function_response", () => {
+ const input = {
+ model: "gemini-2.0-flash",
+ config: {
+ system_instruction:
+ 'Always greet using the say_hello tool.\n\nYou are an agent. Your internal name is "hello_agent".',
+ tools: [
+ {
+ function_declarations: [
+ {
+ name: "say_hello",
+ },
+ ],
+ },
+ ],
+ },
+ 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 ctx = {
+ metadata: {
+ scope: { name: "openinference.instrumentation.google_genai" },
+ },
+ };
+
+ const inResult = normalizeInput(input, ctx);
+
+ expect(inResult.success).toBe(true);
+ if (!inResult.data) throw new Error("Expected data to be defined");
+ expect(inResult.data).toHaveLength(4);
+ 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[3].role).toBe("user");
+ expect(inResult.data[3].content).not.toContain("[object Object]");
+ });
+});
diff --git a/web/src/utils/chatml/jumptoplayground.clienttest.ts b/web/src/utils/chatml/jumptoplayground.clienttest.ts
new file mode 100644
index 0000000000..9ae821cbc4
--- /dev/null
+++ b/web/src/utils/chatml/jumptoplayground.clienttest.ts
@@ -0,0 +1,204 @@
+// 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",
+ },
+}));
+
+import { normalizeInput } from "./adapters";
+import { convertChatMlToPlayground } from "./playgroundConverter";
+
+describe("Playground Jump Full Pipeline", () => {
+ it("should convert full trace with tool calls through mapper and playground conversion", () => {
+ // Same data as integration test
+ const observationName = "OpenAI-generation";
+ const metadata = {
+ language: "en",
+ resourceAttributes: {
+ "telemetry.sdk.language": "python",
+ "telemetry.sdk.name": "opentelemetry",
+ "telemetry.sdk.version": "1.34.1",
+ "deployment.environment": "prod",
+ },
+ scope: {
+ name: "langfuse-sdk",
+ version: "3.2.3",
+ attributes: {
+ public_key: "pk-lf-1234567890",
+ },
+ },
+ };
+
+ const input = {
+ tools: [
+ {
+ type: "function",
+ function: {
+ name: "get_user_info",
+ description: "Retrieve user contact information",
+ parameters: {
+ type: "object",
+ properties: {},
+ required: [],
+ },
+ },
+ },
+ {
+ type: "function",
+ function: {
+ name: "query_database",
+ description: "Query the knowledge base for information",
+ parameters: {
+ type: "object",
+ properties: {
+ query: {
+ type: "string",
+ description: "The search query",
+ },
+ lang: {
+ type: "string",
+ description: "Language code",
+ },
+ },
+ required: ["query", "lang"],
+ },
+ },
+ },
+ ],
+ messages: [
+ {
+ role: "system",
+ content:
+ "You are a helpful assistant. Use tools to gather information before responding.",
+ },
+ {
+ role: "assistant",
+ content: "",
+ tool_calls: [
+ {
+ id: "call_user_info_001",
+ type: "function",
+ function: {
+ name: "get_user_info",
+ arguments: {},
+ },
+ },
+ ],
+ },
+ {
+ role: "tool",
+ content: JSON.stringify({
+ userInfo: {
+ displayName: "Test User",
+ email: "[email protected]",
+ },
+ }),
+ tool_call_id: "call_user_info_001",
+ },
+ {
+ role: "user",
+ content: "How do I configure the API settings?",
+ },
+ {
+ role: "assistant",
+ content: "",
+ tool_calls: [
+ {
+ id: "call_query_db_002",
+ type: "function",
+ function: {
+ name: "query_database",
+ arguments: {
+ query: "configure API settings",
+ lang: "en",
+ },
+ },
+ },
+ ],
+ },
+ {
+ role: "tool",
+ content:
+ "To configure API settings, go to Settings > API Configuration. Enter your API key and select the appropriate region.",
+ name: "query_database",
+ tool_call_id: "call_query_db_002",
+ },
+ ],
+ };
+
+ // const output = {
+ // role: "assistant",
+ // content:
+ // "To configure the API settings, follow these steps:\n\n1. Navigate to **Settings\n2. Enter your API key\n3. Select the appropriate region.",
+ // };
+
+ const ctx = { metadata, observationName };
+ const inResult = normalizeInput(input, ctx);
+
+ expect(inResult.success).toBe(true);
+ if (!inResult.data) throw new Error("Expected data to be defined");
+
+ // convert all messages to playground format
+ const playgroundMessages = inResult.data
+ .map(convertChatMlToPlayground)
+ .filter((msg) => msg !== null);
+
+ // Verify we got messages (if length is 0, button would be disabled!)
+ expect(playgroundMessages.length).toBeGreaterThan(0);
+ expect(playgroundMessages).toHaveLength(6);
+
+ // Verify first assistant message with tool call
+ const assistantWithToolCall1 = playgroundMessages[1];
+ expect(assistantWithToolCall1?.type).toBe("assistant-tool-call");
+ if (assistantWithToolCall1?.type === "assistant-tool-call") {
+ expect(assistantWithToolCall1.toolCalls).toHaveLength(1);
+ expect(assistantWithToolCall1.toolCalls[0].id).toBe("call_user_info_001");
+ expect(assistantWithToolCall1.toolCalls[0].name).toBe("get_user_info");
+ expect(assistantWithToolCall1.toolCalls[0].args).toEqual({});
+ }
+
+ // Verify first tool result
+ const toolResult1 = playgroundMessages[2];
+ expect(toolResult1?.type).toBe("tool-result");
+ if (toolResult1?.type === "tool-result") {
+ expect(toolResult1.toolCallId).toBe("call_user_info_001");
+ expect(typeof toolResult1.content).toBe("string");
+ expect(toolResult1.content).toContain("Test User");
+ }
+
+ // Verify second assistant message with tool call (object args)
+ const assistantWithToolCall2 = playgroundMessages[4];
+ expect(assistantWithToolCall2?.type).toBe("assistant-tool-call");
+ if (assistantWithToolCall2?.type === "assistant-tool-call") {
+ expect(assistantWithToolCall2.toolCalls).toHaveLength(1);
+ expect(assistantWithToolCall2.toolCalls[0].id).toBe("call_query_db_002");
+ expect(assistantWithToolCall2.toolCalls[0].name).toBe("query_database");
+ // Object arguments should be parsed back to object
+ expect(assistantWithToolCall2.toolCalls[0].args).toEqual({
+ query: "configure API settings",
+ lang: "en",
+ });
+ }
+
+ // Verify second tool result
+ const toolResult2 = playgroundMessages[5];
+ expect(toolResult2?.type).toBe("tool-result");
+ if (toolResult2?.type === "tool-result") {
+ expect(toolResult2.toolCallId).toBe("call_query_db_002");
+ expect(typeof toolResult2.content).toBe("string");
+ expect(toolResult2.content).toContain("Settings > API Configuration");
+ }
+ });
+});
diff --git a/web/src/utils/chatml/playgroundConverter.ts b/web/src/utils/chatml/playgroundConverter.ts
new file mode 100644
index 0000000000..0cf14ee407
--- /dev/null
+++ b/web/src/utils/chatml/playgroundConverter.ts
@@ -0,0 +1,73 @@
+import type { ChatMlMessageSchema } from "@/src/components/schemas/ChatMlSchema";
+import {
+ ChatMessageRole,
+ ChatMessageType,
+ type ChatMessage,
+ type PlaceholderMessage,
+} from "@langfuse/shared";
+
+export function convertChatMlToPlayground(
+ msg: ChatMlMessageSchema,
+): ChatMessage | PlaceholderMessage | null {
+ // Handle placeholder messages
+ if (msg.type === "placeholder") {
+ return {
+ type: ChatMessageType.Placeholder,
+ name: msg.name || "",
+ } as PlaceholderMessage;
+ }
+
+ // 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) => {
+ let args: Record<string, unknown>;
+ 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 || "",
+ args,
+ };
+ });
+
+ return {
+ role: ChatMessageRole.Assistant,
+ content: (msg.content as string) || "",
+ type: ChatMessageType.AssistantToolCall,
+ toolCalls,
+ };
+ }
+
+ // Handle tool results (from json field)
+ if (jsonData?.tool_call_id || jsonData?.toolCallId) {
+ return {
+ role: ChatMessageRole.Tool,
+ content: (msg.content as string) || "",
+ type: ChatMessageType.ToolResult,
+ toolCallId: (jsonData.tool_call_id || jsonData.toolCallId) as string,
+ };
+ }
+
+ // Handle regular messages
+ const content =
+ typeof msg.content === "string"
+ ? msg.content
+ : msg.content === null || msg.content === undefined
+ ? ""
+ : JSON.stringify(msg.content);
+
+ return {
+ role: (msg.role as ChatMessageRole) || ChatMessageRole.Assistant,
+ content,
+ type: ChatMessageType.PublicAPICreated,
+ };
+}
diff --git a/web/src/utils/chatml/types.ts b/web/src/utils/chatml/types.ts
new file mode 100644
index 0000000000..431a2db804
--- /dev/null
+++ b/web/src/utils/chatml/types.ts
@@ -0,0 +1,32 @@
+export type NormalizerContext = {
+ metadata?: unknown;
+ observationName?: string;
+ framework?: string; // for explicit overrides
+};
+
+// Unified tool event representation across all providers
+export type ToolEvent =
+ | {
+ type: "call";
+ id?: string;
+ name: string;
+ argsJson: string; // Always JSON string for consistency
+ }
+ | {
+ type: "result";
+ id?: string;
+ content: string; // Always string (stringify objects)
+ status?: "ok" | "error";
+ };
+
+// Minimal provider adapter interface
+export interface ProviderAdapter {
+ id: string;
+ detect(ctx: NormalizerContext): boolean;
+ preprocess(
+ data: unknown,
+ kind: "input" | "output",
+ ctx: NormalizerContext,
+ ): unknown;
+ extractToolEvents?(message: Record<string, unknown>): ToolEvent[];
+}
diff --git a/web/src/utils/langfuse-chatml/README.md b/web/src/utils/langfuse-chatml/README.md
deleted file mode 100644
index b14c9ae7b5..0000000000
--- a/web/src/utils/langfuse-chatml/README.md
+++ /dev/null
@@ -1,37 +0,0 @@
-# Langfuse ChatML Mappers
-
-This utils package handles conversion of various SDK formats to a Langfuse ChatML format.
-We display the Langfuse ChatML format in the frontend and ensure parsing.
-
-The mapping is selected by three values:
-* data source (i.e. SDK name)
-* data source version (i.e. SDK version)
-* language (i.e. SDK programming language)
-
-## How It Works
-
-Whenever we want to map a source to `LangfuseChatML`, we call the function `mapToLangfuseChatML(input?, output?, metadata?)`.
-The function then selects the appropriate mapper and calls its `map()` function.
-For each `framework`+`version`+`language` (with the latter 2 optional), we have mapper class and a test file.
-Each class has 2 main functions: `canMapScore` and `map`.
-The `canMapScore` discovers if this mapper is applicable (i.e. by checking the metadata) and assigns a score.
-If a mapper has the score `10`, it's a definite match.
-Then, the mappers are run in the order of the scores until one succeeds.
-
-
-## Adding a New Mapping
-
-1. Create the mapper file: `mappers/[framework].ts`
- - Implement canMapScore(): uses metadata to determine if mapper is applicable
- - Implement map(): transforms input to `LangfuseChatML` format
- - Create convert[Framework]Message(): extract framework-specific stuff (tool calls, etc.)
-2. Create tests: `mappers/[framework].clienttest.ts`
- - Use real examples with obfuscated data
- - Test canMapScore() detection (metadata + structural)
- - Test message conversion (tool calls, special fields)
-3. Register mapper in `index.ts`
-
-Langfuse ChatML Model
-* messages array
-* tool calls
-* highlight row, ...
diff --git a/web/src/utils/langfuse-chatml/index.ts b/web/src/utils/langfuse-chatml/index.ts
deleted file mode 100644
index 480aa29e36..0000000000
--- a/web/src/utils/langfuse-chatml/index.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import { genericMapper } from "./mappers/generic";
-import { openAIMapper } from "./mappers/openai";
-import { langGraphMapper } from "./mappers/langgraph";
-import { langChainMapper } from "./mappers/langchain";
-import { pydanticMapper } from "./mappers/pydantic";
-import { llamaIndexMapper } from "./mappers/llamaindex";
-import type { LangfuseChatML } from "./types";
-import type { ChatMLMapper } from "./mappers/base";
-
-const mappers: ChatMLMapper[] = [
- openAIMapper,
- langGraphMapper,
- langChainMapper,
- pydanticMapper,
- llamaIndexMapper,
- genericMapper, // Fallback
-];
-
-// TODO: Cache the parsed result to not parse twice (in findBestMapper and mapToLangfuseChatML)
-function findBestMapper(
- input: unknown,
- output: unknown,
- metadata?: unknown,
- observationName?: string,
-): ChatMLMapper {
- const scored = mappers.map((mapper) => ({
- mapper,
- score: mapper.canMapScore(input, output, metadata, observationName),
- }));
-
- scored.sort((a, b) => b.score - a.score);
-
- // Try map in order until success
- for (const { mapper, score } of scored) {
- // Skip zero-score non-generic mappers
- if (score === 0 && mapper.mapperName !== "generic") continue;
-
- try {
- const result = mapper.map(input, output, metadata, observationName);
- const hasData =
- result.input.messages.length > 0 || result.output.messages.length > 0;
- if (hasData) return mapper;
- } catch {
- // next mapper
- continue;
- }
- }
-
- // fallback to generic mapper
- return genericMapper;
-}
-
-export function mapToLangfuseChatML(
- input: unknown,
- output: unknown,
- metadata?: unknown,
- observationName?: string,
-): LangfuseChatML {
- const mapper = findBestMapper(input, output, metadata, observationName);
- const result = mapper.map(input, output, metadata, observationName);
-
- result._selectedMapper = mapper.mapperName; // just for debug
-
- return result;
-}
-
-export * from "./types";
-export type { ChatMLMapper } from "./mappers/base";
diff --git a/web/src/utils/langfuse-chatml/integration.clienttest.ts b/web/src/utils/langfuse-chatml/integration.clienttest.ts
deleted file mode 100644
index 361f230ea8..0000000000
--- a/web/src/utils/langfuse-chatml/integration.clienttest.ts
+++ /dev/null
@@ -1,219 +0,0 @@
-// 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",
- },
-}));
-
-import { mapToLangfuseChatML } from "./index";
-
-describe("LangfuseChatML Integration", () => {
- it("should auto-detect and map OpenAI Parts format", () => {
- const input = {
- messages: [
- {
- role: "user",
- content: [
- { type: "text", text: "What's in this image?" },
- {
- type: "image_url",
- image_url: { url: "data:image/jpeg;base64,..." },
- },
- ],
- },
- ],
- temperature: 0.7,
- model: "gpt-4-vision-preview",
- };
-
- // Test with metadata
- // TODO: remove ls_... checks
- const resultWithMeta = mapToLangfuseChatML(input, null, {
- ls_provider: "openai",
- ls_version: "1.0",
- });
- expect(resultWithMeta.dataSource).toBe("openai");
- expect(resultWithMeta.dataSourceVersion).toBe("1.0");
-
- // Test with structural detection (no metadata)
- const resultNoMeta = mapToLangfuseChatML(input, null);
- expect(resultNoMeta.dataSource).toBeUndefined();
- expect(resultNoMeta.dataSourceVersion).toBeUndefined();
- expect(resultNoMeta.canDisplayAsChat()).toBe(true);
- expect(resultNoMeta.input.additional).toEqual({
- temperature: 0.7,
- model: "gpt-4-vision-preview",
- });
- });
-
- it("should auto-detect and map LangGraph format", () => {
- const input = {
- messages: [{ role: "model", content: "Response from Gemini" }],
- metadata: JSON.stringify({ langgraph_node: "agent_node" }),
- };
-
- // Test with metadata
- // TODO: remove ls_... checks
- const resultWithMeta = mapToLangfuseChatML(input, null, {
- framework: "langgraph",
- ls_version: "2.1",
- });
- expect(resultWithMeta.dataSource).toBe("langgraph");
- expect(resultWithMeta.dataSourceVersion).toBe("2.1");
-
- // Test with structural detection (no metadata)
- const resultNoMeta = mapToLangfuseChatML(input, null);
- expect(resultNoMeta.dataSource).toBeUndefined();
- expect(resultNoMeta.dataSourceVersion).toBeUndefined();
- expect(resultNoMeta.canDisplayAsChat()).toBe(true);
-
- // Check that model role was normalized to assistant
- const allMessages = resultNoMeta.getAllMessages();
- expect(allMessages.some((m) => m.role === "assistant")).toBe(true);
- });
-
- it("should auto-detect and map Pydantic AI format", () => {
- const input = [
- {
- content: "You are a helpful assistant.",
- role: "system",
- "gen_ai.system": "openai",
- "gen_ai.message.index": 0,
- "event.name": "gen_ai.system.message",
- },
- {
- content: "What is the capital of Italy?",
- role: "user",
- "gen_ai.system": "openai",
- "gen_ai.message.index": 0,
- "event.name": "gen_ai.user.message",
- },
- ];
-
- const output = {
- index: 0,
- message: {
- role: "assistant",
- content: "Rome",
- },
- "gen_ai.system": "openai",
- "event.name": "gen_ai.choice",
- };
-
- const metadata = {
- scope: {
- name: "pydantic-ai",
- version: "0.2.15",
- },
- };
-
- // Test with metadata
- const resultWithMeta = mapToLangfuseChatML(input, output, metadata);
- expect(resultWithMeta._selectedMapper).toBe("pydantic");
- expect(resultWithMeta.canDisplayAsChat()).toBe(true);
- expect(resultWithMeta.input.messages).toHaveLength(2);
- expect(resultWithMeta.output.messages).toHaveLength(1);
- expect(resultWithMeta.output.messages[0].content).toBe("Rome");
-
- // Test with structural detection (no metadata)
- // const resultNoMeta = mapToLangfuseChatML(input, output);
- // expect(resultNoMeta._selectedMapper).toBe("pydantic");
- // expect(resultNoMeta.canDisplayAsChat()).toBe(true);
- });
-
- it("should fallback to generic mapper for regular ChatML", () => {
- const input = [
- { role: "user", content: "Hello!" },
- { role: "assistant", content: "Hi there!" },
- ];
- const output = { role: "assistant", content: "How can I help?" };
-
- const result = mapToLangfuseChatML(input, output);
-
- // Should use generic mapper (no data source info)
- expect(result.dataSource).toBeUndefined();
- expect(result.dataSourceVersion).toBeUndefined();
- expect(result.canDisplayAsChat()).toBe(true);
-
- const allMessages = result.getAllMessages();
- expect(allMessages).toHaveLength(3); // 2 input + 1 output
- });
-
- it("should handle nested array format [[ChatML...]]", () => {
- // Some integrations wrap messages in double arrays
- const input = [
- [
- { role: "system", content: "You are a helpful assistant." },
- { role: "user", content: "Hello!" },
- ],
- ];
- const output = { role: "assistant", content: "Hi there!" };
-
- const result = mapToLangfuseChatML(input, output);
-
- expect(result.canDisplayAsChat()).toBe(true);
- expect(result.input.messages).toHaveLength(2);
- expect(result.input.messages[0].role).toBe("system");
- expect(result.input.messages[1].role).toBe("user");
- expect(result.output.messages).toHaveLength(1);
- });
-
- it("should handle legacy completion format {completion: string}", () => {
- const input = [{ role: "user", content: "Write a haiku" }];
- const output = {
- completion:
- "Cherry blossoms fall\nSoftly on the morning dew\nSpring has come at last",
- };
-
- const result = mapToLangfuseChatML(input, output);
-
- expect(result.canDisplayAsChat()).toBe(true);
- expect(result.input.messages).toHaveLength(1);
- expect(result.output.messages).toHaveLength(1);
- // Legacy completion gets wrapped in json field
- expect(result.output.messages[0].json).toEqual({
- completion:
- "Cherry blossoms fall\nSoftly on the morning dew\nSpring has come at last",
- });
- });
-
- it("should handle placeholder messages", () => {
- const input = [
- { role: "user", content: "Hello" },
- { type: "placeholder", name: "Processing..." },
- { role: "assistant", content: "Hi there!" },
- ];
- const output = { role: "assistant", content: "How can I help?" };
-
- const result = mapToLangfuseChatML(input, output);
-
- expect(result.canDisplayAsChat()).toBe(true);
- const allMessages = result.getAllMessages();
- expect(allMessages).toHaveLength(4); // 3 input (including placeholder) + 1 output
- expect(allMessages[1].type).toBe("placeholder");
- });
-
- it("should handle circular references gracefully", () => {
- const input: any = [{ role: "user", content: "test" }];
- input[0].circular = input[0]; // Create circular reference
-
- // Should not crash, though parsing may succeed or fail gracefully
- expect(() => mapToLangfuseChatML(input, null)).not.toThrow();
- });
-
- it("should handle very large inputs", () => {
- const largeContent = "x".repeat(1000000); // 1 million chars
- const input = [{ role: "user", content: largeContent }];
- const output = { role: "assistant", content: "OK" };
-
- const result = mapToLangfuseChatML(input, output);
-
- expect(result.canDisplayAsChat()).toBe(true);
- expect(result.input.messages[0].content).toHaveLength(1000000);
- });
-});
diff --git a/web/src/utils/langfuse-chatml/mappers/base.ts b/web/src/utils/langfuse-chatml/mappers/base.ts
deleted file mode 100644
index 800b1150c7..0000000000
--- a/web/src/utils/langfuse-chatml/mappers/base.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import type { LangfuseChatML } from "../types";
-
-// Scoring constants for mapper selection
-export const MAPPER_SCORE_DEFINITIVE = 10; // Definitive match (e.g., metadata match)
-export const MAPPER_SCORE_NONE = 0; // No match
-
-export interface ChatMLMapper {
- readonly mapperName: string;
- readonly dataSourceName: string;
- readonly dataSourceVersion?: string;
- readonly dataSourceLanguage?: string;
-
- // score based on metadata/structure indicators (no parsing)
- // MAPPER_SCORE_DEFINITIVE (10) = definitive match
- // 1-9 = partial match based on indicators
- // MAPPER_SCORE_NONE (0) = no match
- // metadata can be a string or object
- canMapScore(
- input: unknown,
- output: unknown,
- metadata?: unknown,
- observationName?: string,
- ): number;
-
- map(
- input: unknown,
- output: unknown,
- metadata?: unknown,
- observationName?: string,
- ): LangfuseChatML;
-}
diff --git a/web/src/utils/langfuse-chatml/mappers/generic.clienttest.ts b/web/src/utils/langfuse-chatml/mappers/generic.clienttest.ts
deleted file mode 100644
index b606e70feb..0000000000
--- a/web/src/utils/langfuse-chatml/mappers/generic.clienttest.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-// TODO: fix that mocking @langfuse/shared is required
-jest.mock("@langfuse/shared", () => ({
- ChatMessageRole: {
- System: "system",
- Developer: "developer",
- User: "user",
- Assistant: "assistant",
- Tool: "tool",
- Model: "model",
- },
-}));
-
-import { genericMapper } from "./generic";
-
-describe("genericMapper", () => {
- it("should be fallback mapper with score 0 and map basic ChatML", () => {
- // Always score 0 (fallback)
- expect(genericMapper.canMapScore("anything", "anything")).toBe(0);
- expect(genericMapper.canMapScore(null, undefined)).toBe(0);
- expect(genericMapper.canMapScore({}, {}, "openai")).toBe(0);
-
- // Map simple ChatML
- const input = [
- { role: "user", content: "Hello!" },
- { role: "assistant", content: "Hi there!" },
- ];
- const output = { role: "assistant", content: "Response" };
-
- const result = genericMapper.map(input, output);
-
- expect(result.canDisplayAsChat()).toBe(true);
- expect(result.getAllMessages()).toEqual(
- expect.arrayContaining([
- expect.objectContaining({ role: "user", content: "Hello!" }),
- expect.objectContaining({ role: "assistant", content: "Hi there!" }),
- expect.objectContaining({ role: "assistant", content: "Response" }),
- ]),
- );
- expect(result.input.messages).toHaveLength(2);
- expect(result.output.messages).toHaveLength(1);
- });
-
- it("should not display as chat if chat has no messages (or not parsed as in content-parts / google-adk)", () => {
- // Based on real google-adk trace data
- const input = {
- new_message: {
- parts: [{ text: "hi" }],
- role: "user",
- },
- run_config: {
- streaming_mode: "StreamingMode.NONE",
- max_llm_calls: 500,
- },
- };
-
- const output = {
- content: {
- parts: [{ text: "Hello Langfuse 👋!\n" }],
- role: "model",
- },
- finish_reason: "STOP",
- usage_metadata: {
- candidates_token_count: 6,
- candidates_tokens_details: [{ modality: "TEXT", token_count: 6 }],
- prompt_token_count: 39,
- prompt_tokens_details: [{ modality: "TEXT", token_count: 39 }],
- total_token_count: 45,
- },
- author: "hello_agent",
- actions: {
- state_delta: {},
- artifact_delta: {},
- requested_auth_configs: {},
- },
- id: "some-id",
- timestamp: 1756366351.22196,
- };
-
- const result = genericMapper.map(input, output);
-
- // Should NOT display as chat even though output parses successfully
- // because getAllMessages / combineInputOutputMessages returns 0
- expect(result.canDisplayAsChat()).toBe(false);
- expect(result.getAllMessages()).toHaveLength(0);
- expect(result.input.messages).toHaveLength(0);
- // Output technically parses as 1 message (has content field)
- // but won't be displayed in chat view since getAllMessages returns 0
- expect(result.output.messages).toHaveLength(1);
-
- // Output should be in additional field for rendering as JSON
- expect(result.output.additional).toBeDefined();
- expect(result.output.additional).toMatchObject({
- content: expect.objectContaining({
- parts: expect.any(Array),
- role: "model",
- }),
- finish_reason: "STOP",
- });
- });
-});
diff --git a/web/src/utils/langfuse-chatml/mappers/generic.ts b/web/src/utils/langfuse-chatml/mappers/generic.ts
deleted file mode 100644
index 9741cd5814..0000000000
--- a/web/src/utils/langfuse-chatml/mappers/generic.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-import { type ChatMLMapper, MAPPER_SCORE_NONE } from "./base";
-import type { LangfuseChatML, LangfuseChatMLMessage } from "../types";
-import type { ChatMlMessageSchema } from "@/src/components/schemas/ChatMlSchema";
-import {
- isPlainObject,
- mapToChatMl,
- mapOutputToChatMl,
- cleanLegacyOutput,
- extractAdditionalInput,
- combineInputOutputMessages,
-} from "./utils";
-
-export const genericMapper: ChatMLMapper = {
- mapperName: "generic",
- dataSourceName: "generic",
-
- canMapScore(
- _input: unknown,
- _output: unknown,
- _metadata?: unknown,
- _observationName?: string,
- ): number {
- // Fallback mapper, always tried last
- return MAPPER_SCORE_NONE;
- },
-
- map: (
- input: unknown,
- output: unknown,
- _metadata?: unknown,
- _observationName?: string,
- ): LangfuseChatML => {
- const inChatMlArray = mapToChatMl(input);
- const outChatMlArray = mapOutputToChatMl(output);
- const outputClean = cleanLegacyOutput(output, output ?? null);
- const additionalInput = extractAdditionalInput(input);
-
- const result: LangfuseChatML = {
- input: {
- messages: inChatMlArray.success
- ? inChatMlArray.data.map(convertToLangfuseChatMLMessage)
- : [],
- additional:
- Object.keys(additionalInput ?? {}).length > 0
- ? additionalInput
- : undefined,
- },
- output: {
- messages: outChatMlArray.success
- ? outChatMlArray.data.map(convertToLangfuseChatMLMessage)
- : [],
- additional: isPlainObject(outputClean) ? outputClean : undefined,
- },
-
- canDisplayAsChat: function () {
- // if input/output parsing failed, exit early for performance reasons
- if (!inChatMlArray.success && !outChatMlArray.success) {
- return false;
- }
-
- // Only display as chat if we have actual renderable messages
- // Check getAllMessages() instead of just parse success, may filter out messages
- // TODO: once we move to langfuse-chatml, we can fix this
- const allMessages = combineInputOutputMessages(
- inChatMlArray,
- outChatMlArray,
- outputClean,
- );
- const canDisplay = allMessages.length > 0;
- return canDisplay;
- },
-
- getAllMessages: function () {
- return combineInputOutputMessages(
- inChatMlArray,
- outChatMlArray,
- outputClean,
- );
- },
- };
-
- return result;
- },
-};
-
-function convertToLangfuseChatMLMessage(
- msg: ChatMlMessageSchema,
-): LangfuseChatMLMessage {
- // Generic mapper: simple pass-through, no framework-specific tool extraction
- return {
- role: msg.role || "assistant",
- name: msg.name,
- content: msg.content,
- audio: msg.audio,
- type: msg.type,
- json: msg.json,
- };
-}
diff --git a/web/src/utils/langfuse-chatml/mappers/langchain.clienttest.ts b/web/src/utils/langfuse-chatml/mappers/langchain.clienttest.ts
deleted file mode 100644
index f78ac8fdbb..0000000000
--- a/web/src/utils/langfuse-chatml/mappers/langchain.clienttest.ts
+++ /dev/null
@@ -1,313 +0,0 @@
-// TODO: remove this mock...
-jest.mock("@langfuse/shared", () => {
- const { z } = require("zod/v4");
-
- return {
- ChatMessageRole: {
- System: "system",
- Developer: "developer",
- User: "user",
- Assistant: "assistant",
- Tool: "tool",
- Model: "model",
- },
- OpenAIToolSchema: z.object({
- type: z.literal("function"),
- function: z.object({
- name: z.string(),
- description: z.string(),
- parameters: z.any(),
- }),
- }),
- };
-});
-
-import { langChainMapper } from "./langchain";
-import { MAPPER_SCORE_DEFINITIVE, MAPPER_SCORE_NONE } from "./base";
-
-describe("langChainMapper", () => {
- it("should detect LangChain via metadata and structural indicators", () => {
- // Metadata detection: ls_ prefix (LangSmith convention)
- const metadata = {
- tags: ["seq:step:1"],
- ls_provider: "amazon_bedrock",
- ls_model_name: "eu.anthropic.claude-3-haiku-20240307-v1:0",
- ls_model_type: "chat",
- ls_temperature: 0.1,
- };
-
- expect(langChainMapper.canMapScore({}, {}, metadata)).toBe(
- MAPPER_SCORE_DEFINITIVE,
- );
- expect(langChainMapper.canMapScore({}, {}, { ls_provider: "openai" })).toBe(
- MAPPER_SCORE_DEFINITIVE,
- );
- expect(
- langChainMapper.canMapScore({}, {}, { framework: "langchain" }),
- ).toBe(MAPPER_SCORE_DEFINITIVE);
- expect(
- langChainMapper.canMapScore({}, {}, { some_provider: "openai" }),
- ).toBe(MAPPER_SCORE_NONE);
-
- // Structural detection: additional_kwargs
- const inputWithStructure = {
- messages: [
- {
- role: "assistant",
- content: "Let me help",
- additional_kwargs: {
- tool_calls: [
- {
- id: "call_123",
- function: { name: "search", arguments: '{"q":"test"}' },
- },
- ],
- },
- },
- ],
- };
-
- expect(
- langChainMapper.canMapScore(inputWithStructure, null),
- ).toBeGreaterThan(0);
-
- // Should not detect regular ChatML
- const regularInput = {
- messages: [
- { role: "user", content: "Hello!" },
- { role: "assistant", content: "Hi there!" },
- ],
- };
- expect(langChainMapper.canMapScore(regularInput, null)).toBe(0);
- });
-
- it("should handle tool calls and results", () => {
- // Extract tool_calls from additional_kwargs (standard format)
- const input1 = {
- messages: [
- {
- role: "assistant",
- content: "Using tools",
- additional_kwargs: {
- tool_calls: [
- {
- id: "call_lc1",
- function: {
- name: "weather_tool",
- arguments: '{"city": "NYC"}',
- },
- },
- ],
- },
- custom_field: "preserved",
- },
- ],
- };
-
- const result1 = langChainMapper.map(input1, null);
- expect(result1.input.messages[0].toolCalls).toHaveLength(1);
- expect(result1.input.messages[0].toolCalls?.[0]).toEqual({
- id: "call_lc1",
- type: "function",
- function: {
- name: "weather_tool",
- arguments: '{"city": "NYC"}',
- },
- });
- expect(result1.input.messages[0].json).toEqual({
- custom_field: "preserved",
- });
-
- // Handle object arguments (not string)
- const input2 = {
- messages: [
- {
- role: "assistant",
- content: "",
- additional_kwargs: {
- tool_calls: [
- {
- id: "call_lc2",
- function: {
- name: "calculator",
- arguments: { operation: "add", a: 1, b: 2 },
- },
- },
- ],
- },
- },
- ],
- };
-
- const result2 = langChainMapper.map(input2, null);
- expect(result2.input.messages[0].toolCalls?.[0].function.arguments).toBe(
- '{"operation":"add","a":1,"b":2}',
- );
-
- // Handle missing tool call ID
- const input3 = {
- messages: [
- {
- role: "assistant",
- content: "",
- additional_kwargs: {
- tool_calls: [
- {
- function: {
- name: "test_tool",
- arguments: "{}",
- },
- },
- ],
- },
- },
- ],
- };
-
- const result3 = langChainMapper.map(input3, null);
- expect(result3.input.messages[0].toolCalls?.[0].id).toBeNull();
-
- // Handle shorthand format (name/args instead of function.name/function.arguments)
- const input4 = {
- messages: [
- {
- role: "assistant",
- content: "",
- additional_kwargs: {
- tool_calls: [
- {
- id: "call_short",
- name: "shorthand_tool",
- args: { key: "value" },
- },
- ],
- },
- },
- ],
- };
-
- const result4 = langChainMapper.map(input4, null);
- expect(result4.input.messages[0].toolCalls?.[0].function).toEqual({
- name: "shorthand_tool",
- arguments: '{"key":"value"}',
- });
-
- // Extract tool_call_id from tool result messages
- const input5 = {
- messages: [
- {
- role: "tool",
- content: "result",
- tool_call_id: "call_lc123",
- },
- ],
- };
-
- const result5 = langChainMapper.map(input5, null);
- expect(result5.input.messages[0].toolCallId).toBe("call_lc123");
- });
-
- it("should extract tool definitions to additional.tools", () => {
- // Basic tool definition extraction
- const input1 = {
- messages: [
- {
- role: "tool",
- content: JSON.stringify({
- type: "function",
- function: {
- name: "search",
- description: "Search the web",
- parameters: {
- type: "object",
- properties: {
- query: { type: "string", description: "Search query" },
- },
- required: ["query"],
- },
- },
- }),
- },
- {
- role: "tool",
- content: JSON.stringify({
- type: "function",
- function: {
- name: "calculator",
- description: "Perform calculations",
- parameters: {
- type: "object",
- properties: {
- expression: { type: "string" },
- },
- },
- },
- }),
- },
- {
- role: "user",
- content: "Search for cats",
- },
- ],
- };
-
- const result1 = langChainMapper.map(input1, null);
- expect(result1.input.additional?.tools).toHaveLength(2);
- expect((result1.input.additional?.tools as any)?.[0]).toEqual({
- name: "search",
- description: "Search the web",
- parameters: {
- type: "object",
- properties: {
- query: { type: "string", description: "Search query" },
- },
- required: ["query"],
- },
- });
- expect(result1.input.messages).toHaveLength(1);
- expect(result1.input.messages[0].role).toBe("user");
-
- // Mixed: tool definitions + tool calls + tool results
- const input2 = {
- messages: [
- {
- role: "tool",
- content: JSON.stringify({
- type: "function",
- function: {
- name: "weather",
- description: "Get weather",
- parameters: { type: "object", properties: {} },
- },
- }),
- },
- {
- role: "assistant",
- content: "",
- additional_kwargs: {
- tool_calls: [
- {
- id: "call_1",
- function: { name: "weather", arguments: '{"city":"SF"}' },
- },
- ],
- },
- },
- {
- role: "tool",
- content: "Sunny, 72°F",
- tool_call_id: "call_1",
- },
- ],
- };
-
- const result2 = langChainMapper.map(input2, null);
- expect(result2.input.additional?.tools).toHaveLength(1);
- expect((result2.input.additional?.tools as any)?.[0].name).toBe("weather");
- expect(result2.input.messages).toHaveLength(2);
- expect(result2.input.messages[0].role).toBe("assistant");
- expect(result2.input.messages[0].toolCalls).toHaveLength(1);
- expect(result2.input.messages[1].role).toBe("tool");
- expect(result2.input.messages[1].toolCallId).toBe("call_1");
- });
-});
diff --git a/web/src/utils/langfuse-chatml/mappers/langchain.ts b/web/src/utils/langfuse-chatml/mappers/langchain.ts
deleted file mode 100644
index 2b9e28528b..0000000000
--- a/web/src/utils/langfuse-chatml/mappers/langchain.ts
+++ /dev/null
@@ -1,186 +0,0 @@
-import {
- type ChatMLMapper,
- MAPPER_SCORE_DEFINITIVE,
- MAPPER_SCORE_NONE,
-} from "./base";
-import type { LangfuseChatML, LangfuseChatMLMessage } from "../types";
-import type { ChatMlMessageSchema } from "@/src/components/schemas/ChatMlSchema";
-import {
- isPlainObject,
- parseMetadata,
- extractJsonData,
- extractToolData,
- mapToChatMl,
- mapOutputToChatMl,
- cleanLegacyOutput,
- extractAdditionalInput,
- combineInputOutputMessages,
-} from "./utils";
-import { OpenAIToolSchema, type LLMToolDefinition } from "@langfuse/shared";
-
-// is a message a LangChain tool **definition** schema?
-function isToolDefinitionMessage(msg: ChatMlMessageSchema): boolean {
- if (msg.role !== "tool") return false;
- if (typeof msg.content !== "string") return false;
- // Tool results have tool_call_id in json field, tool definitions don't
- const jsonData = extractJsonData(msg.json);
- if (jsonData?.tool_call_id) return false;
-
- try {
- const parsed = JSON.parse(msg.content);
- return OpenAIToolSchema.safeParse(parsed).success;
- } catch {
- return false;
- }
-}
-
-function extractToolDefinition(msg: ChatMlMessageSchema) {
- try {
- const parsed = JSON.parse(msg.content as string);
- if (parsed.type === "function" && parsed.function) {
- return {
- name: parsed.function.name,
- description: parsed.function.description,
- parameters: parsed.function.parameters,
- };
- }
- } catch {}
- return null;
-}
-
-function convertLangChainMessage(
- msg: ChatMlMessageSchema,
-): LangfuseChatMLMessage {
- const base: LangfuseChatMLMessage = {
- role: msg.role || "assistant",
- name: msg.name,
- content: msg.content,
- audio: msg.audio,
- type: msg.type,
- };
-
- if (!msg.json) return base;
-
- // ChatML schema wraps extra fields in nested json object
- const jsonData = extractJsonData(msg.json);
- if (!jsonData) return base;
-
- // NOTE: mapToChatMl() flattens LangChain's additional_kwargs.tool_calls to just tool_calls
- // So by the time we get here, LangChain format looks the same as OpenAI format
- return extractToolData(base, jsonData);
-}
-
-export const langChainMapper: ChatMLMapper = {
- mapperName: "langchain",
- dataSourceName: "langchain",
-
- canMapScore(
- input: unknown,
- output: unknown,
- metadata?: unknown,
- _observationName?: string,
- ): number {
- const meta = parseMetadata(metadata);
-
- if (meta?.framework === "langchain") {
- return MAPPER_SCORE_DEFINITIVE;
- }
-
- // Check for any ls_ prefixed fields (common for LangChain due to LangSmith integration)
- if (meta && typeof meta === "object") {
- const hasLsPrefix = Object.keys(meta).some((key) =>
- key.startsWith("ls_"),
- );
- if (hasLsPrefix) {
- return MAPPER_SCORE_DEFINITIVE;
- }
- }
-
- // Structural detection for LangChain traces
- const scoreData = (data: unknown): number => {
- if (!data || typeof data !== "object") return MAPPER_SCORE_NONE;
-
- const obj = data as Record<string, unknown>;
-
- // Check if messages have additional_kwargs (LangChain-specific structure)
- if (obj.messages && Array.isArray(obj.messages)) {
- const hasAdditionalKwargs = obj.messages.some(
- (msg: any) =>
- msg &&
- typeof msg === "object" &&
- "additional_kwargs" in msg &&
- msg.additional_kwargs &&
- typeof msg.additional_kwargs === "object",
- );
- if (hasAdditionalKwargs) return 5; // Structural indicator
- }
-
- return MAPPER_SCORE_NONE;
- };
-
- return Math.max(scoreData(input), scoreData(output));
- },
-
- map: (
- input: unknown,
- output: unknown,
- metadata?: unknown,
- _observationName?: string,
- ): LangfuseChatML => {
- const meta = parseMetadata(metadata);
- const inChatMlArray = mapToChatMl(input);
- const outChatMlArray = mapOutputToChatMl(output);
- const outputClean = cleanLegacyOutput(output, output ?? null);
- const additionalInput = extractAdditionalInput(input);
-
- // Separate tool definitions from regular messages
- const toolDefinitions: LLMToolDefinition[] = [];
- const regularMessages: ChatMlMessageSchema[] = [];
-
- if (inChatMlArray.success) {
- for (const msg of inChatMlArray.data) {
- if (isToolDefinitionMessage(msg)) {
- const toolDef = extractToolDefinition(msg);
- if (toolDef) toolDefinitions.push(toolDef);
- } else {
- regularMessages.push(msg);
- }
- }
- }
-
- // Build additional field with tools if present
- const additional = {
- ...additionalInput,
- ...(toolDefinitions.length > 0 ? { tools: toolDefinitions } : {}),
- };
-
- const result: LangfuseChatML = {
- input: {
- messages: regularMessages.map(convertLangChainMessage),
- additional: Object.keys(additional).length > 0 ? additional : undefined,
- },
- output: {
- messages: outChatMlArray.success
- ? outChatMlArray.data.map(convertLangChainMessage)
- : [],
- additional: isPlainObject(outputClean) ? outputClean : undefined,
- },
- dataSource: meta?.framework ? String(meta.framework) : undefined,
- dataSourceVersion: meta?.ls_version ? String(meta.ls_version) : undefined,
-
- canDisplayAsChat: function () {
- return regularMessages.length > 0 || outChatMlArray.success;
- },
-
- getAllMessages: function () {
- return combineInputOutputMessages(
- { success: true, data: regularMessages },
- outChatMlArray,
- outputClean,
- );
- },
- };
-
- return result;
- },
-};
diff --git a/web/src/utils/langfuse-chatml/mappers/langgraph.clienttest.ts b/web/src/utils/langfuse-chatml/mappers/langgraph.clienttest.ts
deleted file mode 100644
index 7743e5507b..0000000000
--- a/web/src/utils/langfuse-chatml/mappers/langgraph.clienttest.ts
+++ /dev/null
@@ -1,145 +0,0 @@
-// TODO: remove this mock
-jest.mock("@langfuse/shared", () => ({
- ChatMessageRole: {
- System: "system",
- Developer: "developer",
- User: "user",
- Assistant: "assistant",
- Tool: "tool",
- Model: "model",
- },
-}));
-
-import { langGraphMapper } from "./langgraph";
-import { MAPPER_SCORE_DEFINITIVE, MAPPER_SCORE_NONE } from "./base";
-
-describe("langGraphMapper", () => {
- it("should detect LangGraph via metadata and structural indicators", () => {
- // Metadata detection: framework or ls_provider
- expect(
- langGraphMapper.canMapScore({}, {}, { framework: "langgraph" }),
- ).toBe(MAPPER_SCORE_DEFINITIVE);
- expect(
- langGraphMapper.canMapScore({}, {}, { ls_provider: "langgraph" }),
- ).toBe(MAPPER_SCORE_DEFINITIVE);
- expect(
- langGraphMapper.canMapScore({}, {}, { some_provider: "openai" }),
- ).toBe(MAPPER_SCORE_NONE);
-
- // Structural detection: langgraph_node or langgraph_step in metadata
- const inputWithStructure = {
- metadata: JSON.stringify({ langgraph_node: "some_node" }),
- };
- expect(
- langGraphMapper.canMapScore(inputWithStructure, null),
- ).toBeGreaterThan(0);
-
- // Should not detect regular ChatML
- const regularInput = [
- { role: "user", content: "Hello!" },
- { role: "assistant", content: "Hi there!" },
- ];
- expect(langGraphMapper.canMapScore(regularInput, null)).toBe(0);
- });
-
- it("should normalize roles (Gemini support)", () => {
- // Normalize Gemini "model" role to "assistant"
- const input1 = {
- messages: [{ role: "model", content: "Response from Gemini" }],
- metadata: JSON.stringify({ langgraph_step: 1 }),
- };
-
- const result1 = langGraphMapper.map(input1, null);
- expect(result1.input.messages[0].role).toBe("assistant");
-
- // Preserve _originalRole for custom tool names (used for tool call ID inference)
- const input2 = {
- messages: [{ role: "custom_tool_name", content: "Tool result" }],
- metadata: JSON.stringify({ langgraph_node: "agent" }),
- };
-
- const result2 = langGraphMapper.map(input2, null);
- expect(result2.input.messages[0].role).toBe("tool");
- expect(result2.input.messages[0]._originalRole).toBe("custom_tool_name");
-
- // Handle Gemini parts array conversion
- const input3 = {
- messages: [
- {
- role: "user",
- parts: [{ text: "Hello" }, { text: " world" }],
- },
- ],
- metadata: JSON.stringify({ langgraph_node: "test" }),
- };
-
- const result3 = langGraphMapper.map(input3, null);
- expect(result3.input.messages[0].content).toBe("Hello world");
- });
-
- it("should handle tool calls and results", () => {
- // Extract tool_calls from LangGraph messages
- const input1 = {
- messages: [
- {
- role: "assistant",
- content: "Using tools",
- tool_calls: [
- {
- id: "call_lg1",
- name: "weather_tool",
- args: { city: "SF" },
- },
- ],
- },
- ],
- metadata: JSON.stringify({ langgraph_node: "agent" }),
- };
-
- const result1 = langGraphMapper.map(input1, null);
- expect(result1.input.messages[0].toolCalls).toHaveLength(1);
- expect(result1.input.messages[0].toolCalls?.[0]).toEqual({
- id: "call_lg1",
- type: "function",
- function: {
- name: "weather_tool",
- arguments: '{"city":"SF"}',
- },
- });
-
- // Handle missing tool call IDs (use null)
- const input2 = {
- messages: [
- {
- role: "assistant",
- content: "",
- tool_calls: [
- {
- name: "test_tool",
- args: {},
- },
- ],
- },
- ],
- metadata: JSON.stringify({ langgraph_node: "test" }),
- };
-
- const result2 = langGraphMapper.map(input2, null);
- expect(result2.input.messages[0].toolCalls?.[0].id).toBeNull();
-
- // Extract tool_call_id from tool result messages
- const input3 = {
- messages: [
- {
- role: "tool",
- content: "result",
- tool_call_id: "call_123",
- },
- ],
- metadata: JSON.stringify({ langgraph_node: "tools" }),
- };
-
- const result3 = langGraphMapper.map(input3, null);
- expect(result3.input.messages[0].toolCallId).toBe("call_123");
- });
-});
diff --git a/web/src/utils/langfuse-chatml/mappers/langgraph.ts b/web/src/utils/langfuse-chatml/mappers/langgraph.ts
deleted file mode 100644
index d805c63d25..0000000000
--- a/web/src/utils/langfuse-chatml/mappers/langgraph.ts
+++ /dev/null
@@ -1,236 +0,0 @@
-import {
- type ChatMLMapper,
- MAPPER_SCORE_DEFINITIVE,
- MAPPER_SCORE_NONE,
-} from "./base";
-import type { LangfuseChatML, LangfuseChatMLMessage } from "../types";
-import type { ChatMlMessageSchema } from "@/src/components/schemas/ChatMlSchema";
-import {
- isPlainObject,
- parseMetadata,
- extractJsonData,
- extractToolData,
- mapToChatMl,
- mapOutputToChatMl,
- cleanLegacyOutput,
- extractAdditionalInput,
- combineInputOutputMessages,
-} from "./utils";
-import { ChatMessageRole } from "@langfuse/shared";
-
-function hasLangGraphIndicators(data: unknown): boolean {
- if (!data || typeof data !== "object") return false;
-
- const obj = data as Record<string, unknown>;
-
- // Check direct properties
- if ("langgraph_node" in obj || "langgraph_step" in obj) {
- return true;
- }
-
- // Check top-level metadata field
- if ("metadata" in obj) {
- const metadata = parseMetadata(obj.metadata);
- if (
- metadata &&
- ("langgraph_node" in metadata || "langgraph_step" in metadata)
- ) {
- return true;
- }
- }
-
- // Check nested messages[].metadata
- if ("messages" in obj && Array.isArray(obj.messages)) {
- return obj.messages.some((msg: unknown) => {
- if (!msg || typeof msg !== "object") return false;
- const msgObj = msg as Record<string, unknown>;
- if (!msgObj.metadata) return false;
-
- const metadata = parseMetadata(msgObj.metadata);
- return (
- metadata &&
- ("langgraph_node" in metadata || "langgraph_step" in metadata)
- );
- });
- }
-
- return false;
-}
-
-// Normalize LangGraph tool messages by converting tool-name roles to "tool"
-// and normalize Google/Gemini format (model role + parts field)
-function normalizeLangGraphMessage(
- message: unknown,
- isLangGraph: boolean = false,
-): unknown {
- if (!message || typeof message !== "object" || !("role" in message)) {
- return message;
- }
-
- const msg = message as any;
- const validRoles = Object.values(ChatMessageRole);
- let normalizedMessage = { ...msg };
-
- // convert google format: "model" role -> "assistant"
- if (msg.role === "model") {
- normalizedMessage.role = ChatMessageRole.Assistant;
- }
-
- // convert google format: "parts" field -> "content" field
- if (msg.parts && Array.isArray(msg.parts)) {
- const content = msg.parts
- .map((part: any) =>
- typeof part === "object" && part.text ? part.text : String(part),
- )
- .join("");
- normalizedMessage.content = content;
- delete normalizedMessage.parts;
- }
-
- // convert LangGraph: invalid roles -> "tool" role
- if (
- isLangGraph &&
- !validRoles.includes(normalizedMessage.role as ChatMessageRole)
- ) {
- return {
- ...normalizedMessage,
- role: ChatMessageRole.Tool,
- _originalRole: msg.role,
- };
- }
-
- return normalizedMessage;
-}
-
-function convertLangGraphMessage(
- msg: ChatMlMessageSchema,
-): LangfuseChatMLMessage {
- const base: LangfuseChatMLMessage = {
- role: msg.role || "assistant",
- name: msg.name,
- content: msg.content,
- audio: msg.audio,
- type: msg.type,
- };
-
- if (!msg.json) return base;
-
- const jsonData = extractJsonData(msg.json);
- if (!jsonData) return base;
-
- const jsonCopy = { ...jsonData };
-
- // Keep _originalRole for tool call ID inference (LangGraph-specific)
- if (jsonCopy._originalRole) {
- base._originalRole = String(jsonCopy._originalRole);
- delete jsonCopy._originalRole;
- }
-
- return extractToolData(base, jsonCopy);
-}
-
-export const langGraphMapper: ChatMLMapper = {
- mapperName: "langgraph",
- dataSourceName: "langgraph",
-
- canMapScore(
- input: unknown,
- output: unknown,
- metadata?: unknown,
- _observationName?: string,
- ): number {
- const meta = parseMetadata(metadata);
-
- // LangGraph uses both framework and ls_provider keys
- if (meta?.framework === "langgraph" || meta?.ls_provider === "langgraph") {
- return MAPPER_SCORE_DEFINITIVE;
- }
-
- if (
- hasLangGraphIndicators(meta) ||
- hasLangGraphIndicators(input) ||
- hasLangGraphIndicators(output)
- ) {
- return 8;
- }
-
- return MAPPER_SCORE_NONE;
- },
-
- map: (
- input: unknown,
- output: unknown,
- metadata?: unknown,
- _observationName?: string,
- ): LangfuseChatML => {
- const meta = parseMetadata(metadata);
- const normalizeData = (data: unknown): unknown => {
- if (!data || typeof data !== "object") return data;
-
- const obj = data as Record<string, unknown>;
-
- // Normalize messages if they exist
- if (obj.messages && Array.isArray(obj.messages)) {
- return {
- ...obj,
- messages: obj.messages.map((msg: unknown) =>
- normalizeLangGraphMessage(msg, true),
- ),
- };
- }
-
- // If it's a single message, normalize it
- if (obj.role) {
- return normalizeLangGraphMessage(obj, true);
- }
-
- return data;
- };
-
- const normalizedInput = normalizeData(input);
- const normalizedOutput = normalizeData(output);
-
- const inChatMlArray = mapToChatMl(normalizedInput);
- const outChatMlArray = mapOutputToChatMl(normalizedOutput);
- const outputClean = cleanLegacyOutput(output, output ?? null);
- const additionalInput = extractAdditionalInput(normalizedInput);
-
- const result: LangfuseChatML = {
- input: {
- messages: inChatMlArray.success
- ? inChatMlArray.data.map(convertLangGraphMessage)
- : [],
- additional:
- Object.keys(additionalInput ?? {}).length > 0
- ? additionalInput
- : undefined,
- },
- output: {
- messages: outChatMlArray.success
- ? outChatMlArray.data.map(convertLangGraphMessage)
- : [],
- additional: isPlainObject(outputClean) ? outputClean : undefined,
- },
- dataSource: meta?.framework
- ? String(meta.framework)
- : meta?.ls_provider
- ? String(meta.ls_provider)
- : undefined,
- dataSourceVersion: meta?.ls_version ? String(meta.ls_version) : undefined,
-
- canDisplayAsChat: function () {
- return inChatMlArray.success || outChatMlArray.success;
- },
-
- getAllMessages: function () {
- return combineInputOutputMessages(
- inChatMlArray,
- outChatMlArray,
- outputClean,
- );
- },
- };
-
- return result;
- },
-};
diff --git a/web/src/utils/langfuse-chatml/mappers/llamaindex.clienttest.ts b/web/src/utils/langfuse-chatml/mappers/llamaindex.clienttest.ts
deleted file mode 100644
index 749070ce73..0000000000
--- a/web/src/utils/langfuse-chatml/mappers/llamaindex.clienttest.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { llamaIndexMapper } from "./llamaindex";
-import { MAPPER_SCORE_DEFINITIVE } from "./base";
-
-describe("LlamaIndex Mapper", () => {
- it("should detect LlamaIndex via metadata scope.name", () => {
- const metadata = {
- attributes: {
- "llm.model_name": "gpt-4o",
- "llm.provider": "openai",
- "llm.prompts": ["What is Langfuse?"],
- "openinference.span.kind": "LLM",
- },
- scope: {
- name: "openinference.instrumentation.llama_index",
- version: "4.3.0",
- },
- };
-
- expect(llamaIndexMapper.canMapScore({}, {}, metadata)).toBe(
- MAPPER_SCORE_DEFINITIVE,
- );
- });
-
- it("should map LlamaIndex format to ChatML", () => {
- const input = {
- args: ["What is Langfuse?"],
- };
-
- const output =
- "Langfuse is a tool designed to help developers monitor and debug applications that utilize large language models (LLMs).";
-
- const metadata = {
- attributes: {
- "llm.model_name": "gpt-4o",
- "llm.provider": "openai",
- "llm.prompts": ["What is Langfuse?"],
- "output.value": output,
- "openinference.span.kind": "LLM",
- },
- scope: {
- name: "openinference.instrumentation.llama_index",
- version: "4.3.0",
- },
- };
-
- const result = llamaIndexMapper.map(input, output, metadata);
-
- expect(result.input.messages).toHaveLength(1);
- expect(result.input.messages[0]).toEqual({
- role: "user",
- name: undefined,
- content: "What is Langfuse?",
- });
-
- expect(result.output.messages).toHaveLength(1);
- expect(result.output.messages[0]).toEqual({
- role: "assistant",
- name: undefined,
- content: output,
- });
-
- expect(result.canDisplayAsChat()).toBe(true);
- });
-});
diff --git a/web/src/utils/langfuse-chatml/mappers/llamaindex.ts b/web/src/utils/langfuse-chatml/mappers/llamaindex.ts
deleted file mode 100644
index 4e209b2479..0000000000
--- a/web/src/utils/langfuse-chatml/mappers/llamaindex.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-import {
- type ChatMLMapper,
- MAPPER_SCORE_DEFINITIVE,
- MAPPER_SCORE_NONE,
-} from "./base";
-import type { LangfuseChatML, LangfuseChatMLMessage } from "../types";
-import { parseMetadata, normalizeMessageForChatMl } from "./utils";
-
-export const llamaIndexMapper: ChatMLMapper = {
- mapperName: "llamaindex",
- dataSourceName: "llama-index",
-
- canMapScore(
- input: unknown,
- output: unknown,
- metadata?: unknown,
- _observationName?: string,
- ): number {
- const meta = parseMetadata(metadata);
-
- if (
- meta &&
- typeof meta === "object" &&
- "scope" in meta &&
- typeof meta.scope === "object" &&
- meta.scope !== null &&
- "name" in meta.scope &&
- typeof meta.scope.name === "string" &&
- (meta.scope.name as string).includes("llama_index")
- ) {
- return MAPPER_SCORE_DEFINITIVE;
- }
-
- return MAPPER_SCORE_NONE;
- },
-
- map: (
- input: unknown,
- output: unknown,
- metadata?: unknown,
- _observationName?: string,
- ): LangfuseChatML => {
- const inputMessages: LangfuseChatMLMessage[] = [];
- const outputMessages: LangfuseChatMLMessage[] = [];
-
- const meta = parseMetadata(metadata);
-
- // Extract prompts from metadata.attributes.llm.prompts
- if (
- meta &&
- typeof meta === "object" &&
- "attributes" in meta &&
- typeof meta.attributes === "object" &&
- meta.attributes !== null
- ) {
- const attrs = meta.attributes as Record<string, unknown>;
-
- // Process llm.prompts as input messages (user role)
- if (Array.isArray(attrs["llm.prompts"])) {
- for (const prompt of attrs["llm.prompts"]) {
- if (typeof prompt === "string") {
- inputMessages.push({
- role: "user",
- name: undefined,
- content: prompt,
- audio: undefined,
- type: undefined,
- });
- }
- }
- }
- }
-
- // Process output (direct string)
- if (typeof output === "string" && output.length > 0) {
- outputMessages.push({
- role: "assistant",
- name: undefined,
- content: output,
- audio: undefined,
- type: undefined,
- });
- }
-
- // Extract dataSource from metadata.scope.name
- let dataSource: string | undefined = undefined;
- if (
- meta &&
- typeof meta === "object" &&
- "scope" in meta &&
- typeof meta.scope === "object" &&
- meta.scope !== null &&
- "name" in meta.scope
- ) {
- dataSource = String(meta.scope.name);
- }
-
- return {
- input: {
- messages: inputMessages,
- additional: undefined,
- },
- output: {
- messages: outputMessages,
- additional: undefined,
- },
- dataSource,
- dataSourceVersion: undefined,
-
- canDisplayAsChat: function () {
- return inputMessages.length > 0 || outputMessages.length > 0;
- },
-
- getAllMessages: function () {
- return [...inputMessages, ...outputMessages].map(
- normalizeMessageForChatMl,
- );
- },
- };
- },
-};
diff --git a/web/src/utils/langfuse-chatml/mappers/openai.clienttest.ts b/web/src/utils/langfuse-chatml/mappers/openai.clienttest.ts
deleted file mode 100644
index bdcdb16266..0000000000
--- a/web/src/utils/langfuse-chatml/mappers/openai.clienttest.ts
+++ /dev/null
@@ -1,324 +0,0 @@
-// TODO: remove
-jest.mock("@langfuse/shared", () => ({
- ChatMessageRole: {
- System: "system",
- Developer: "developer",
- User: "user",
- Assistant: "assistant",
- Tool: "tool",
- Model: "model",
- },
-}));
-
-import { openAIMapper } from "./openai";
-import { MAPPER_SCORE_DEFINITIVE, MAPPER_SCORE_NONE } from "./base";
-
-describe("openAIMapper", () => {
- it("should detect OpenAI via metadata and structural indicators", () => {
- // Metadata detection: ls_provider
- // TODO: remove ls_... check -> should be oai specific
- expect(openAIMapper.canMapScore({}, {}, { ls_provider: "openai" })).toBe(
- MAPPER_SCORE_DEFINITIVE,
- );
- expect(
- openAIMapper.canMapScore(
- {},
- {},
- { ls_provider: "openai", ls_version: "1.0" },
- ),
- ).toBe(MAPPER_SCORE_DEFINITIVE);
- expect(openAIMapper.canMapScore({}, {}, { framework: "langgraph" })).toBe(
- MAPPER_SCORE_NONE,
- );
-
- // Structural detection: Parts API
- const partsInput = {
- messages: [
- {
- role: "user",
- content: [
- { type: "text", text: "What's in this image?" },
- {
- type: "image_url",
- image_url: { url: "data:image/jpeg;base64,..." },
- },
- ],
- },
- ],
- };
- expect(openAIMapper.canMapScore(partsInput, null)).toBeGreaterThan(0);
-
- // Should not detect regular ChatML
- const regularInput = [
- { role: "user", content: "Hello!" },
- { role: "assistant", content: "Hi there!" },
- ];
- expect(openAIMapper.canMapScore(regularInput, null)).toBe(0);
- });
-
- it("should handle tool calls and tool results", () => {
- // Test assistant message with tool_calls
- const inputWithToolCalls = {
- messages: [
- {
- role: "assistant",
- content: "Let me check that for you",
- tool_calls: [
- {
- id: "call_abc123",
- type: "function",
- function: {
- name: "get_weather",
- arguments: '{"city": "NYC"}',
- },
- },
- ],
- custom_field: "should_be_preserved",
- },
- ],
- };
-
- const result1 = openAIMapper.map(inputWithToolCalls, null);
- expect(result1.input.messages).toHaveLength(1);
- expect(result1.input.messages[0].toolCalls).toHaveLength(1);
- expect(result1.input.messages[0].toolCalls?.[0]).toEqual({
- id: "call_abc123",
- type: "function",
- function: {
- name: "get_weather",
- arguments: '{"city": "NYC"}',
- },
- });
- expect(result1.input.messages[0].content).toBe("Let me check that for you");
- expect(result1.input.messages[0].json).toEqual({
- custom_field: "should_be_preserved",
- });
-
- // Test tool message with tool_call_id
- const inputWithToolResult = {
- messages: [
- {
- role: "tool",
- content: '{"temperature": 72}',
- tool_call_id: "call_abc123",
- },
- ],
- };
-
- const result2 = openAIMapper.map(inputWithToolResult, null);
- expect(result2.input.messages).toHaveLength(1);
- expect(result2.input.messages[0].toolCallId).toBe("call_abc123");
- expect(result2.input.messages[0].content).toBe('{"temperature": 72}');
-
- // Test object arguments (not string)
- const inputWithObjectArgs = {
- messages: [
- {
- role: "assistant",
- content: "",
- tool_calls: [
- {
- id: "call_obj",
- type: "function",
- function: {
- name: "test_func",
- arguments: { key: "value", nested: { data: 123 } },
- },
- },
- ],
- },
- ],
- };
-
- const result3 = openAIMapper.map(inputWithObjectArgs, null);
- expect(result3.input.messages[0].toolCalls?.[0].function.arguments).toBe(
- '{"key":"value","nested":{"data":123}}',
- );
- });
-
- it("should not add toolCalls or toolCallId if not present", () => {
- const input = {
- messages: [
- {
- role: "assistant",
- content: "Regular message without tools",
- },
- ],
- };
-
- const result = openAIMapper.map(input, null);
-
- expect(result.input.messages[0].toolCalls).toBeUndefined();
- expect(result.input.messages[0].toolCallId).toBeUndefined();
- });
-
- it("should handle trace with tool calls (langfuse-sdk, openai auto instrument)", () => {
- const metadata = {
- language: "en",
- scope: {
- name: "langfuse-sdk",
- version: "3.2.3",
- },
- };
-
- const input = {
- tools: [
- {
- type: "function",
- function: {
- name: "get_user_contact_information",
- description: "Retrieve user contact information",
- parameters: {
- type: "object",
- properties: {},
- required: [],
- },
- },
- },
- {
- type: "function",
- function: {
- name: "query_knowledge_base",
- description: "Query the knowledge base for information",
- parameters: {
- type: "object",
- properties: {
- _inquiry_summary: { type: "string" },
- _lang: { type: "string" },
- },
- required: ["_inquiry_summary", "_lang"],
- },
- },
- },
- ],
- messages: [
- {
- role: "system",
- content: "You are a helpful assistant.",
- },
- {
- role: "assistant",
- content: "",
- name: null,
- tool_call_id: null,
- tool_calls: [
- {
- id: "call_user_001",
- type: "function",
- function: {
- name: "get_user_contact_information",
- arguments: {}, // Object, not string
- },
- },
- ],
- },
- {
- role: "tool",
- content: {
- // Object content, not stringified
- userInformation: {
- displayName: "Anonymous",
- emails: [],
- phoneNumbers: [],
- },
- },
- name: null,
- tool_call_id: "call_user_001",
- tool_calls: null,
- },
- {
- role: "user",
- content: "how do I add an agent?",
- name: null,
- tool_call_id: null,
- tool_calls: null,
- },
- {
- role: "assistant",
- content: "",
- name: null,
- tool_call_id: null,
- tool_calls: [
- {
- id: "call_kb_002",
- type: "function",
- function: {
- name: "query_knowledge_base",
- arguments: {
- // Object arguments
- _inquiry_summary: "how to add an agent",
- _lang: "en",
- },
- },
- },
- ],
- },
- {
- role: "tool",
- content:
- "To add an agent, go to Settings and add it. Complete the required fields.",
- name: "query_knowledge_base",
- tool_call_id: "call_kb_002",
- tool_calls: null,
- },
- ],
- };
-
- const output = {
- role: "assistant",
- content: "To add an agent, follow these steps:\n1. Go to Settings",
- };
-
- const result = openAIMapper.map(input, output, metadata);
-
- // Verify mapper was used correctly
- expect(result.input.messages).toHaveLength(6);
-
- // Check first assistant message with tool call
- const assistantMsg1 = result.input.messages[1];
- expect(assistantMsg1.role).toBe("assistant");
- expect(assistantMsg1.toolCalls).toBeDefined();
- expect(assistantMsg1.toolCalls).toHaveLength(1);
- expect(assistantMsg1.toolCalls?.[0].id).toBe("call_user_001");
- expect(assistantMsg1.toolCalls?.[0].function.name).toBe(
- "get_user_contact_information",
- );
- expect(assistantMsg1.toolCalls?.[0].function.arguments).toBe("{}");
-
- // Check first tool response - content should remain as string
- const toolMsg1 = result.input.messages[2];
- expect(toolMsg1.role).toBe("tool");
- expect(toolMsg1.toolCallId).toBe("call_user_001");
- expect(typeof toolMsg1.content).toBe("string");
- // Content should be the JSON string we provided
- expect(toolMsg1.content).toContain("userInformation");
-
- // Check second assistant message with tool call (object arguments)
- const assistantMsg2 = result.input.messages[4];
- expect(assistantMsg2.toolCalls).toBeDefined();
- expect(assistantMsg2.toolCalls).toHaveLength(1);
- expect(assistantMsg2.toolCalls?.[0].id).toBe("call_kb_002");
- expect(assistantMsg2.toolCalls?.[0].function.name).toBe(
- "query_knowledge_base",
- );
- // Object arguments should be stringified
- expect(typeof assistantMsg2.toolCalls?.[0].function.arguments).toBe(
- "string",
- );
- const args = JSON.parse(
- assistantMsg2.toolCalls?.[0].function.arguments || "{}",
- );
- expect(args._inquiry_summary).toBe("how to add an agent");
-
- // Check second tool response with name field
- const toolMsg2 = result.input.messages[5];
- expect(toolMsg2.role).toBe("tool");
- expect(toolMsg2.toolCallId).toBe("call_kb_002");
- expect(toolMsg2.name).toBe("query_knowledge_base");
- expect(typeof toolMsg2.content).toBe("string");
-
- // Verify additional input (tools array)
- expect(result.input.additional).toBeDefined();
- expect(result.input.additional?.tools).toBeDefined();
- });
-});
diff --git a/web/src/utils/langfuse-chatml/mappers/openai.ts b/web/src/utils/langfuse-chatml/mappers/openai.ts
deleted file mode 100644
index 152eb020a9..0000000000
--- a/web/src/utils/langfuse-chatml/mappers/openai.ts
+++ /dev/null
@@ -1,220 +0,0 @@
-import {
- type ChatMLMapper,
- MAPPER_SCORE_DEFINITIVE,
- MAPPER_SCORE_NONE,
-} from "./base";
-import type { LangfuseChatML, LangfuseChatMLMessage } from "../types";
-import type { ChatMlMessageSchema } from "@/src/components/schemas/ChatMlSchema";
-import {
- isPlainObject,
- parseMetadata,
- extractJsonData,
- extractToolData,
- mapToChatMl,
- mapOutputToChatMl,
- cleanLegacyOutput,
- extractAdditionalInput,
- combineInputOutputMessages,
-} from "./utils";
-import { z } from "zod/v4";
-
-const OpenAIPartsAPISchema = z.object({
- messages: z.array(
- z.object({
- content: z.array(
- z.object({
- type: z.enum(["text", "image_url", "input_audio"]),
- }),
- ),
- }),
- ),
-});
-
-// normalization by stringifying tool call arguments
-// Input: tool_calls[].function.arguments may be object or string (from DB)
-// Output: tool_calls[].function.arguments is always a JSON string (API-compliant)
-function normalizeToolCall(tc: unknown): unknown {
- if (!tc || typeof tc !== "object") return tc;
-
- const toolCall = tc as Record<string, unknown>;
- return {
- ...toolCall,
- function:
- toolCall.function &&
- typeof toolCall.function === "object" &&
- !Array.isArray(toolCall.function)
- ? {
- ...(toolCall.function as Record<string, unknown>),
- arguments:
- typeof (toolCall.function as any).arguments === "string"
- ? (toolCall.function as any).arguments
- : JSON.stringify((toolCall.function as any).arguments ?? {}),
- }
- : toolCall.function,
- };
-}
-
-// transformations
-// 1. Removes explicit null fields (schema uses .optional() not .nullish())
-// 2. tool_calls[].function.arguments: object → JSON string (via normalizeToolCall)
-// 3. tool message content: object → JSON string
-function normalizeMessage(msg: any): any {
- if (!msg || typeof msg !== "object") return msg;
-
- const normalized: Record<string, unknown> = { ...msg };
-
- // Remove explicit null fields
- Object.keys(normalized).forEach((key) => {
- if (normalized[key] === null) {
- delete normalized[key];
- }
- });
-
- // Stringify tool_calls arguments if present
- if (normalized.tool_calls && Array.isArray(normalized.tool_calls)) {
- normalized.tool_calls = normalized.tool_calls.map(normalizeToolCall);
- }
-
- // Stringify object content for tool messages
- if (
- normalized.role === "tool" &&
- typeof normalized.content === "object" &&
- normalized.content !== null &&
- !Array.isArray(normalized.content)
- ) {
- normalized.content = JSON.stringify(normalized.content);
- }
-
- return normalized;
-}
-
-// outputs normalized messages
-const NormalizedOpenAIDataSchema = z.preprocess((data) => {
- if (!data) return data;
-
- // arrays
- if (Array.isArray(data)) {
- return data.map(normalizeMessage);
- }
-
- // 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,
- };
- }
-
- // single message object
- if (typeof data === "object" && "role" in data) {
- return normalizeMessage(data);
- }
-
- return data;
-}, z.unknown());
-
-function convertOpenAIMessage(msg: ChatMlMessageSchema): LangfuseChatMLMessage {
- const base: LangfuseChatMLMessage = {
- role: msg.role || "assistant",
- name: msg.name,
- content: msg.content,
- audio: msg.audio,
- type: msg.type,
- };
-
- if (!msg.json) return base;
-
- // The ChatML schema wraps extra fields in a nested json object
- // extractJsonData handles both: { json: {...} } and {...}
- const jsonData = extractJsonData(msg.json);
- if (!jsonData) return base;
-
- return extractToolData(base, jsonData);
-}
-
-export const openAIMapper: ChatMLMapper = {
- mapperName: "openai",
- dataSourceName: "openai",
-
- canMapScore(
- input: unknown,
- output: unknown,
- metadata?: unknown,
- observationName?: string,
- ): number {
- const meta = parseMetadata(metadata);
- let currentScore = MAPPER_SCORE_NONE;
-
- // TODO: ls_provider is a LangSmith convention - may need to check other keys for pure OpenAI traces
- if (meta?.ls_provider === "openai") return MAPPER_SCORE_DEFINITIVE;
-
- // Check for langfuse-sdk in scope.name (OpenTelemetry convention)
- if ((meta?.scope as Record<string, unknown>)?.name === "langfuse-sdk") {
- currentScore += 5;
- }
-
- if (observationName && observationName.toLowerCase().includes("openai")) {
- currentScore += 3;
- }
-
- if (OpenAIPartsAPISchema.safeParse(input).success) {
- currentScore = Math.max(currentScore, 8);
- }
-
- return Math.min(10, currentScore);
- },
-
- map: (
- input: unknown,
- output: unknown,
- metadata?: unknown,
- _observationName?: string,
- ): LangfuseChatML => {
- const meta = parseMetadata(metadata);
-
- const normalizedInput = NormalizedOpenAIDataSchema.parse(input);
- const normalizedOutput = NormalizedOpenAIDataSchema.parse(output);
-
- const inChatMlArray = mapToChatMl(normalizedInput);
- const outChatMlArray = mapOutputToChatMl(normalizedOutput);
- const outputClean = cleanLegacyOutput(output, output);
- const additionalInput = extractAdditionalInput(normalizedInput);
-
- const result: LangfuseChatML = {
- input: {
- messages: inChatMlArray.success
- ? inChatMlArray.data.map(convertOpenAIMessage)
- : [],
- additional:
- Object.keys(additionalInput ?? {}).length > 0
- ? additionalInput
- : undefined,
- },
- output: {
- messages: outChatMlArray.success
- ? outChatMlArray.data.map(convertOpenAIMessage)
- : [],
- additional: isPlainObject(outputClean) ? outputClean : undefined,
- },
- dataSource: meta?.ls_provider ? String(meta.ls_provider) : undefined,
- dataSourceVersion: meta?.ls_version ? String(meta.ls_version) : undefined,
-
- canDisplayAsChat: function () {
- return inChatMlArray.success || outChatMlArray.success;
- },
-
- getAllMessages: function () {
- return combineInputOutputMessages(
- inChatMlArray,
- outChatMlArray,
- outputClean,
- );
- },
- };
-
- return result;
- },
-};
diff --git a/web/src/utils/langfuse-chatml/mappers/pydantic.clienttest.ts b/web/src/utils/langfuse-chatml/mappers/pydantic.clienttest.ts
deleted file mode 100644
index 26c0744ea5..0000000000
--- a/web/src/utils/langfuse-chatml/mappers/pydantic.clienttest.ts
+++ /dev/null
@@ -1,149 +0,0 @@
-import { pydanticMapper } from "./pydantic";
-import { MAPPER_SCORE_DEFINITIVE, MAPPER_SCORE_NONE } from "./base";
-
-describe("pydanticMapper", () => {
- it("should detect Pydantic AI via metadata and structural indicators", () => {
- const metadata = {
- attributes: {
- "gen_ai.operation.name": "chat",
- "gen_ai.system": "openai",
- "gen_ai.request.model": "gpt-4o",
- },
- scope: {
- name: "pydantic-ai",
- version: "0.2.15",
- attributes: {},
- },
- };
-
- expect(pydanticMapper.canMapScore({}, {}, metadata)).toBe(
- MAPPER_SCORE_DEFINITIVE,
- );
- expect(
- pydanticMapper.canMapScore(
- {},
- {},
- { attributes: { "gen_ai.system": "openai" } },
- ),
- ).toBe(MAPPER_SCORE_NONE);
-
- // Structural detection: gen_ai.* and event.name fields
- const inputWithStructure = [
- {
- content: "You are a helpful assistant.",
- role: "system",
- "gen_ai.system": "openai",
- "gen_ai.message.index": 0,
- "event.name": "gen_ai.system.message",
- },
- {
- content: "What is the capital of Italy?",
- role: "user",
- "gen_ai.system": "openai",
- "gen_ai.message.index": 0,
- "event.name": "gen_ai.user.message",
- },
- ];
-
- const outputWithStructure = {
- index: 0,
- message: {
- role: "assistant",
- content: "Rome",
- },
- "gen_ai.system": "openai",
- "event.name": "gen_ai.choice",
- };
-
- expect(
- pydanticMapper.canMapScore(inputWithStructure, null),
- ).toBeGreaterThan(0);
- expect(
- pydanticMapper.canMapScore(null, outputWithStructure),
- ).toBeGreaterThan(0);
-
- // Should not detect regular ChatML
- const regularInput = {
- messages: [
- { role: "user", content: "Hello!" },
- { role: "assistant", content: "Hi!" },
- ],
- };
- expect(pydanticMapper.canMapScore(regularInput, null)).toBe(
- MAPPER_SCORE_NONE,
- );
- });
-
- it("should map Pydantic AI format and handle nested messages", () => {
- // Basic mapping with gen_ai.* field filtering
- const input1 = [
- {
- content: "You are a helpful assistant.",
- role: "system",
- "gen_ai.system": "openai",
- "gen_ai.message.index": 0,
- "event.name": "gen_ai.system.message",
- },
- {
- content: "What is the capital of Italy?",
- role: "user",
- "gen_ai.system": "openai",
- "gen_ai.message.index": 0,
- "event.name": "gen_ai.user.message",
- custom_field: "preserved",
- another_field: 123,
- },
- ];
-
- const output1 = {
- index: 0,
- message: {
- role: "assistant",
- content: "Rome",
- },
- "gen_ai.system": "openai",
- "event.name": "gen_ai.choice",
- };
-
- const result1 = pydanticMapper.map(input1, output1);
- expect(result1.input.messages).toHaveLength(2);
- expect(result1.input.messages[0]).toEqual({
- role: "system",
- name: undefined,
- content: "You are a helpful assistant.",
- json: undefined,
- });
- expect(result1.input.messages[1].json).toEqual({
- custom_field: "preserved",
- another_field: 123,
- });
- expect(result1.output.messages).toHaveLength(1);
- expect(result1.output.messages[0]).toEqual({
- role: "assistant",
- name: undefined,
- content: "Rome",
- json: undefined,
- });
-
- // Extract nested message with custom fields
- const output2 = {
- index: 0,
- message: {
- role: "assistant",
- content: "Nested response",
- custom_field: "test",
- },
- "gen_ai.system": "openai",
- "event.name": "gen_ai.choice",
- };
-
- const result2 = pydanticMapper.map(null, output2);
- expect(result2.output.messages).toHaveLength(1);
- expect(result2.output.messages[0]).toEqual({
- role: "assistant",
- name: undefined,
- content: "Nested response",
- json: { custom_field: "test" },
- });
- });
-});
diff --git a/web/src/utils/langfuse-chatml/mappers/pydantic.ts b/web/src/utils/langfuse-chatml/mappers/pydantic.ts
deleted file mode 100644
index 2a621199b7..0000000000
--- a/web/src/utils/langfuse-chatml/mappers/pydantic.ts
+++ /dev/null
@@ -1,166 +0,0 @@
-import {
- type ChatMLMapper,
- MAPPER_SCORE_DEFINITIVE,
- MAPPER_SCORE_NONE,
-} from "./base";
-import type { LangfuseChatML, LangfuseChatMLMessage } from "../types";
-import {
- isPlainObject,
- parseMetadata,
- normalizeMessageForChatMl,
-} from "./utils";
-
-function convertPydanticMessage(msg: any): LangfuseChatMLMessage | null {
- if (!msg || typeof msg !== "object") return null;
-
- const { role, content, ...rest } = msg;
-
- if (!role || typeof role !== "string") return null;
-
- // Remove gen_ai.* and event.name fields from json
- const jsonFields: Record<string, unknown> = {};
- for (const [key, value] of Object.entries(rest)) {
- if (!key.startsWith("gen_ai.") && key !== "event.name") {
- jsonFields[key] = value;
- }
- }
-
- return {
- role,
- name: undefined,
- content: content ?? "",
- audio: undefined,
- type: undefined,
- json: Object.keys(jsonFields).length > 0 ? jsonFields : undefined,
- };
-}
-
-export const pydanticMapper: ChatMLMapper = {
- mapperName: "pydantic",
- dataSourceName: "pydantic-ai",
-
- canMapScore(
- input: unknown,
- output: unknown,
- metadata?: unknown,
- _observationName?: string,
- ): number {
- // Parse metadata (handles string or object)
- const meta = parseMetadata(metadata);
-
- // Check for pydantic-ai in scope.name (definitive detection)
- if (
- meta &&
- typeof meta === "object" &&
- "scope" in meta &&
- typeof meta.scope === "object" &&
- meta.scope !== null &&
- "name" in meta.scope &&
- meta.scope.name === "pydantic-ai"
- ) {
- return MAPPER_SCORE_DEFINITIVE;
- }
-
- // Structural detection: check for gen_ai.system and event.name fields
- const scoreData = (data: unknown): number => {
- if (!data) return MAPPER_SCORE_NONE;
-
- // Input format: array of messages with gen_ai.* fields
- if (Array.isArray(data)) {
- const hasPydanticFields = data.some(
- (msg: any) =>
- msg &&
- typeof msg === "object" &&
- "gen_ai.system" in msg &&
- "event.name" in msg &&
- typeof msg["event.name"] === "string" &&
- (msg["event.name"] as string).startsWith("gen_ai."),
- );
- if (hasPydanticFields) return 7; // High confidence structural indicator
- }
-
- // Output format: object with gen_ai.system and event.name fields
- if (isPlainObject(data)) {
- const obj = data as Record<string, unknown>;
- if (
- "gen_ai.system" in obj &&
- "event.name" in obj &&
- typeof obj["event.name"] === "string" &&
- (obj["event.name"] as string).startsWith("gen_ai.")
- ) {
- return 7;
- }
- }
-
- return MAPPER_SCORE_NONE;
- };
-
- return Math.max(scoreData(input), scoreData(output));
- },
-
- map: (
- input: unknown,
- output: unknown,
- metadata?: unknown,
- _observationName?: string,
- ): LangfuseChatML => {
- const meta = parseMetadata(metadata);
- const inputMessages: LangfuseChatMLMessage[] = [];
- const outputMessages: LangfuseChatMLMessage[] = [];
-
- // Process input messages
- if (Array.isArray(input)) {
- for (const msg of input) {
- const converted = convertPydanticMessage(msg);
- if (converted) inputMessages.push(converted);
- }
- }
-
- // Process output message
- if (output && typeof output === "object") {
- const obj = output as Record<string, unknown>;
-
- // Pydantic output has message nested in message field
- if ("message" in obj && typeof obj.message === "object") {
- const converted = convertPydanticMessage(obj.message);
- if (converted) outputMessages.push(converted);
- }
- }
-
- // Extract dataSource from metadata.scope.name
- let dataSource: string | undefined = undefined;
- if (
- meta &&
- typeof meta === "object" &&
- "scope" in meta &&
- typeof meta.scope === "object" &&
- meta.scope !== null &&
- "name" in meta.scope
- ) {
- dataSource = String(meta.scope.name);
- }
-
- return {
- input: {
- messages: inputMessages,
- additional: undefined,
- },
- output: {
- messages: outputMessages,
- additional: undefined,
- },
- dataSource,
- dataSourceVersion: undefined,
-
- canDisplayAsChat: function () {
- return inputMessages.length > 0 || outputMessages.length > 0;
- },
-
- getAllMessages: function () {
- return [...inputMessages, ...outputMessages].map(
- normalizeMessageForChatMl,
- );
- },
- };
- },
-};
diff --git a/web/src/utils/langfuse-chatml/mappers/utils.ts b/web/src/utils/langfuse-chatml/mappers/utils.ts
deleted file mode 100644
index 824ec4c647..0000000000
--- a/web/src/utils/langfuse-chatml/mappers/utils.ts
+++ /dev/null
@@ -1,222 +0,0 @@
-import { z } from "zod/v4";
-import {
- ChatMlArraySchema,
- type ChatMlMessageSchema,
-} from "@/src/components/schemas/ChatMlSchema";
-
-// check if object (not array nor null)
-export const isPlainObject = (val: unknown): val is Record<string, unknown> =>
- typeof val === "object" && val !== null && !Array.isArray(val);
-
-export function parseMetadata(
- metadata: unknown,
-): Record<string, unknown> | undefined {
- if (typeof metadata === "string") {
- try {
- return JSON.parse(metadata) as Record<string, unknown>;
- } catch {
- return undefined;
- }
- }
- if (metadata && typeof metadata === "object") {
- return metadata as Record<string, unknown>;
- }
- return undefined;
-}
-
-/**
- * Extract the actual json data from ChatML message json field.
- * ChatML schema's passthrough behavior wraps extra fields in nested json object.
- * This handles both: { json: {...} } and {...}
- */
-export function extractJsonData(
- msgJson: unknown,
-): Record<string, unknown> | undefined {
- if (!msgJson || typeof msgJson !== "object") return undefined;
-
- const obj = msgJson as Record<string, unknown>;
-
- // if it's the nested format: { json: {...} }
- if ("json" in obj && typeof obj.json === "object" && obj.json !== null) {
- return obj.json as Record<string, unknown>;
- }
-
- return obj;
-}
-
-/**
- * Generic ChatML input parser with fallback handling
- * Handles various input formats:
- * - Direct array: [{role, content}, ...]
- * - Nested array: [[{role, content}, ...]]
- * - Object wrapper: {messages: [{role, content}, ...]}
- */
-export function mapToChatMl(
- input: unknown,
-): ReturnType<typeof ChatMlArraySchema.safeParse> {
- let result = ChatMlArraySchema.safeParse(input);
- if (result.success) {
- return result;
- }
-
- // Check if input is an array of length 1 including an array of ChatMlMessageSchema
- // This is the case for some integrations
- // e.g. [[ChatMlMessageSchema, ...]]
- const inputArray = z.array(ChatMlArraySchema).safeParse(input);
- if (inputArray.success && inputArray.data.length === 1) {
- return ChatMlArraySchema.safeParse(inputArray.data[0]);
- }
-
- // Check if input is an object with a messages key
- // This is the case for some integrations
- // e.g. { messages: [ChatMlMessageSchema, ...] }
- const inputObject = z
- .object({
- messages: ChatMlArraySchema,
- })
- .safeParse(input);
-
- if (inputObject.success) {
- return ChatMlArraySchema.safeParse(inputObject.data.messages);
- }
-
- return result; // Return the original failed parse result
-}
-
-// Wraps single messages in array and validates
-export function mapOutputToChatMl(
- output: unknown,
-): ReturnType<typeof ChatMlArraySchema.safeParse> {
- const result = ChatMlArraySchema.safeParse(
- Array.isArray(output) ? output : [output],
- );
-
- return result;
-}
-
-// Cleans legacy completion format output for display
-// handles {completion: string} -> string transformation
-export function cleanLegacyOutput(output: unknown, fallback?: unknown) {
- const outLegacyCompletionSchema = z
- .object({
- completion: z.string(),
- })
- .refine((value) => Object.keys(value).length === 1);
-
- const outLegacyCompletionSchemaParsed =
- outLegacyCompletionSchema.safeParse(output);
- const outputClean = outLegacyCompletionSchemaParsed.success
- ? outLegacyCompletionSchemaParsed.data
- : (fallback ?? null);
-
- return outputClean;
-}
-
-// Extracts additional input fields beyond the messages array
-// Returns raw additionalInput (may be empty object) - filtering done at usage site
-export function extractAdditionalInput(
- input: unknown,
-): Record<string, unknown> | undefined {
- const additionalInput =
- typeof input === "object" && input !== null && !Array.isArray(input)
- ? Object.fromEntries(
- Object.entries(input as object).filter(([key]) => key !== "messages"),
- )
- : undefined;
-
- // raw result should still be filtered (Object.keys().length > 0)
- return additionalInput;
-}
-
-// combines input and output messages into a single chat conversation
-export function combineInputOutputMessages(
- inputResult: ReturnType<typeof mapToChatMl>,
- outputResult: ReturnType<typeof mapOutputToChatMl>,
- cleanOutput: unknown,
-): ChatMlMessageSchema[] {
- if (!inputResult.success) {
- // Return empty array to prevent crash - this should never happen in normal usage
- return [];
- }
-
- const combinedMessages = [
- ...inputResult.data,
- ...(outputResult.success
- ? outputResult.data.map((m) => ({
- ...m,
- role: m.role ?? "assistant",
- }))
- : [
- {
- role: "assistant",
- ...(typeof cleanOutput === "string"
- ? { content: cleanOutput }
- : { json: cleanOutput }),
- } as ChatMlMessageSchema,
- ]),
- ];
-
- return combinedMessages;
-}
-
-// Normalize LangfuseChatMLMessage to match ChatMlMessageSchema structure
-// Ensures all required fields are present (even if undefined) for type compatibility
-export function normalizeMessageForChatMl(msg: any): ChatMlMessageSchema {
- return {
- role: msg.role,
- name: msg.name,
- content: msg.content,
- audio: msg.audio,
- type: msg.type,
- ...(msg.json && Object.keys(msg.json).length > 0 ? { json: msg.json } : {}),
- } as ChatMlMessageSchema;
-}
-
-/**
- * Extract tool data (tool_calls and tool_call_id) from json object
- * Returns updated message with toolCalls/toolCallId and remaining json fields
- */
-export function extractToolData(
- base: any,
- jsonData: Record<string, unknown>,
-): any {
- const jsonCopy = { ...jsonData };
-
- // Extract tool_calls
- if (jsonCopy.tool_calls && Array.isArray(jsonCopy.tool_calls)) {
- const toolCalls = jsonCopy.tool_calls.map((tc: any) => ({
- id: tc.id || null,
- type: "function" as const,
- function: {
- name: tc.function?.name || tc.name,
- arguments:
- typeof tc.function?.arguments === "string"
- ? tc.function.arguments
- : JSON.stringify(tc.function?.arguments || tc.args || {}),
- },
- }));
-
- delete jsonCopy.tool_calls;
- return {
- ...base,
- toolCalls,
- json: Object.keys(jsonCopy).length > 0 ? jsonCopy : undefined,
- };
- }
-
- // Extract tool_call_id
- if (jsonCopy.tool_call_id) {
- const toolCallId = String(jsonCopy.tool_call_id);
- delete jsonCopy.tool_call_id;
- return {
- ...base,
- toolCallId,
- json: Object.keys(jsonCopy).length > 0 ? jsonCopy : undefined,
- };
- }
-
- return {
- ...base,
- json: Object.keys(jsonCopy).length > 0 ? jsonCopy : undefined,
- };
-}
diff --git a/web/src/utils/langfuse-chatml/types.ts b/web/src/utils/langfuse-chatml/types.ts
deleted file mode 100644
index 58da154e3b..0000000000
--- a/web/src/utils/langfuse-chatml/types.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import type { ChatMlMessageSchema } from "@/src/components/schemas/ChatMlSchema";
-import { z } from "zod/v4";
-
-// Zod Schemas for Runtime Validation
-
-// like Tool call in OpenAI format
-export const LangfuseChatMLToolCallSchema = z.object({
- id: z.string().nullable(), // null if not provided in input
- type: z.literal("function"),
- function: z.object({
- name: z.string(),
- arguments: z.string(),
- }),
-});
-
-export const LangfuseChatMLMessageSchema = z.object({
- id: z.string().optional(),
- role: z.string(),
- name: z.string().optional(),
- // Content can be string, array, object, or null - intentionally loose
- content: z.unknown().optional(),
- audio: z.unknown().optional(), // OpenAIOutputAudioType - rare, keep loose
- metadata: z.record(z.string(), z.unknown()).optional(),
- type: z.string().optional(), // "placeholder" or other special types
- json: z.record(z.string(), z.unknown()).optional(),
-
- // Tool calls (assistant messages)
- toolCalls: z.array(LangfuseChatMLToolCallSchema).optional(),
-
- // Tool results (tool role messages)
- toolCallId: z.string().optional(),
- toolResultStatus: z.enum(["ok", "error"]).optional(),
- toolError: z.string().optional(),
-
- // LangGraph: preserve original role for tool call ID matching
- _originalRole: z.string().optional(),
-});
-
-// Input wrapper
-export const LangfuseChatMLInputSchema = z.object({
- messages: z.array(LangfuseChatMLMessageSchema),
- additional: z.record(z.string(), z.unknown()).optional(),
-});
-
-// Output wrapper
-export const LangfuseChatMLOutputSchema = z.object({
- messages: z.array(LangfuseChatMLMessageSchema),
- additional: z.record(z.string(), z.unknown()).optional(),
-});
-
-// Data portion of LangfuseChatML (without methods)
-export const LangfuseChatMLDataSchema = z.object({
- input: LangfuseChatMLInputSchema,
- output: LangfuseChatMLOutputSchema,
- dataSource: z.string().optional(),
- dataSourceVersion: z.string().optional(),
- highlightMessageId: z.string().optional(),
- _selectedMapper: z.string().optional(),
-});
-
-// TypeScript Types from Zod schemas
-
-// Derive types from schemas to eliminate duplication
-export type LangfuseChatMLMessage = z.infer<typeof LangfuseChatMLMessageSchema>;
-export type LangfuseChatMLInput = z.infer<typeof LangfuseChatMLInputSchema>;
-export type LangfuseChatMLOutput = z.infer<typeof LangfuseChatMLOutputSchema>;
-
-// TODO: should probably be a class, has methods
-export interface LangfuseChatML {
- input: LangfuseChatMLInput;
- output: LangfuseChatMLOutput;
- dataSource?: string; // SDK name: "openai", "langgraph", etc.
- dataSourceVersion?: string; // SDK version: "v0", "v1", etc.
- highlightMessageId?: string; // For scrolling to specific message
-
- // as debug info
- _selectedMapper?: string;
-
- canDisplayAsChat(): boolean;
- getAllMessages(): ChatMlMessageSchema[]; // Return current ChatML format for compatibility
-}