Skip to content

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

refactor: extract ChatML Mapper from IOPreview (#9202)

Nimar1a0a2b1b5398
diff --git a/web/src/components/trace/IOPreview.tsx b/web/src/components/trace/IOPreview.tsx
index 208bc6ddd4..c9c9ef3a6a 100644
--- a/web/src/components/trace/IOPreview.tsx
+++ b/web/src/components/trace/IOPreview.tsx
@@ -1,13 +1,13 @@
import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";
-import { z } from "zod/v4";
import { type Prisma, deepParseJson } from "@langfuse/shared";
import { cn } from "@/src/utils/tailwind";
import { useEffect, useMemo, useState } from "react";
import { Button } from "@/src/components/ui/button";
import { Fragment } from "react";
-import {
+import type { z } from "zod/v4";
+import type {
ChatMlArraySchema,
- type ChatMlMessageSchema,
+ ChatMlMessageSchema,
} from "@/src/components/schemas/ChatMlSchema";
import { type MediaReturnType } from "@/src/features/media/validation";
import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";
@@ -18,6 +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 {
+ mapToChatMl,
+ mapOutputToChatMl,
+ cleanLegacyOutput,
+ extractAdditionalInput,
+ combineInputOutputMessages,
+} from "@/src/utils/chatMlMappers";
export const IOPreview: React.FC<{
input?: Prisma.JsonValue;
@@ -60,45 +67,9 @@ export const IOPreview: React.FC<{
const [compensateScrollRef, startPreserveScroll] =
usePreserveRelativeScroll<HTMLDivElement>([selectedView]);
- // parse old completions: { completion: string } -> string
- 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
- : (props.output ?? null);
-
- // ChatML format
- let inChatMlArray = ChatMlArraySchema.safeParse(input);
- if (!inChatMlArray.success) {
- // 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) {
- inChatMlArray = ChatMlArraySchema.safeParse(inputArray.data[0]);
- } else {
- // 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) {
- inChatMlArray = ChatMlArraySchema.safeParse(inputObject.data.messages);
- }
- }
- }
- const outChatMlArray = ChatMlArraySchema.safeParse(
- Array.isArray(output) ? output : [output],
- );
+ const inChatMlArray = mapToChatMl(input);
+ const outChatMlArray = mapOutputToChatMl(output);
+ const outputClean = cleanLegacyOutput(output, props.output ?? null);
// 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
@@ -109,12 +80,7 @@ export const IOPreview: React.FC<{
}, [isPrettyViewAvailable]);
// If there are additional input fields beyond the messages, render them
- const additionalInput =
- typeof input === "object" && input !== null && !Array.isArray(input)
- ? Object.fromEntries(
- Object.entries(input as object).filter(([key]) => key !== "messages"),
- )
- : undefined;
+ const additionalInput = extractAdditionalInput(input);
// Don't render markdown if total content size exceeds limit
const inputSize = JSON.stringify(input || {}).length;
@@ -162,22 +128,11 @@ export const IOPreview: React.FC<{
>
{inChatMlArray.success ? (
<OpenAiMessageView
- messages={[
- ...inChatMlArray.data,
- ...(outChatMlArray.success
- ? outChatMlArray.data.map((m) => ({
- ...m,
- role: m.role ?? "assistant",
- }))
- : [
- {
- role: "assistant",
- ...(typeof outputClean === "string"
- ? { content: outputClean }
- : { json: outputClean }),
- } as ChatMlMessageSchema,
- ]),
- ]}
+ messages={combineInputOutputMessages(
+ inChatMlArray,
+ outChatMlArray,
+ outputClean,
+ )}
shouldRenderMarkdown={shouldRenderMarkdownSafely}
additionalInput={
Object.keys(additionalInput ?? {}).length > 0
diff --git a/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx b/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
index d9f8220adc..8b549b7240 100644
--- a/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
+++ b/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
@@ -41,9 +41,9 @@ import {
isGenerationLike,
} from "@langfuse/shared";
import {
- LANGGRAPH_NODE_TAG,
- LANGGRAPH_STEP_TAG,
-} from "@/src/features/trace-graph-view/types";
+ isLangGraphTrace,
+ normalizeLangGraphMessage,
+} from "@/src/utils/chatMlMappers";
import { api } from "@/src/utils/api";
import { cn } from "@/src/utils/tailwind";
import usePlaygroundCache from "@/src/features/playground/page/hooks/usePlaygroundCache";
@@ -217,71 +217,6 @@ export const JumpToPlaygroundButton: React.FC<JumpToPlaygroundButtonProps> = (
);
};
-// Is LangGraph Trace? Decide from metadata. If so, we might need to recognise roles as tool names
-const isLangGraphTrace = (generation: { metadata: string | null }): boolean => {
- if (!generation.metadata) return false;
-
- try {
- let metadata = generation.metadata;
- if (typeof metadata === "string") {
- metadata = JSON.parse(metadata);
- }
-
- if (typeof metadata === "object" && metadata !== null) {
- return LANGGRAPH_NODE_TAG in metadata || LANGGRAPH_STEP_TAG in metadata;
- }
- } catch {
- // Ignore JSON parsing errors
- }
-
- return false;
-};
-
-// Normalize LangGraph tool messages by converting tool-name roles to "tool"
-// And normalize Google/Gemini format (model role + parts field)
-const 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;
-};
-
const ParsedChatMessageListSchema = z.array(
z.union([
// Regular chat message
diff --git a/web/src/utils/chatMlMappers.clienttest.ts b/web/src/utils/chatMlMappers.clienttest.ts
new file mode 100644
index 0000000000..3c5578f9a0
--- /dev/null
+++ b/web/src/utils/chatMlMappers.clienttest.ts
@@ -0,0 +1,580 @@
+// 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 {
+ mapToChatMl,
+ mapOutputToChatMl,
+ cleanLegacyOutput,
+ extractAdditionalInput,
+ combineInputOutputMessages,
+ isLangGraphTrace,
+ normalizeLangGraphMessage,
+} from "./chatMlMappers";
+
+describe("chatMlMappers", () => {
+ describe("mapToChatMl", () => {
+ it("should parse direct ChatML array format", () => {
+ const input = [
+ { role: "system", content: "You are a helpful assistant." },
+ { role: "user", content: "Hello!" },
+ ];
+
+ const result = mapToChatMl(input);
+
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data).toHaveLength(2);
+ expect(result.data[0]).toMatchObject({
+ role: "system",
+ content: "You are a helpful assistant.",
+ });
+ expect(result.data[1]).toMatchObject({
+ role: "user",
+ content: "Hello!",
+ });
+ }
+ });
+
+ it("should parse nested array format [[ChatML...]]", () => {
+ const input = [
+ [
+ { role: "system", content: "You are a helpful assistant." },
+ { role: "user", content: "Hello!" },
+ ],
+ ];
+
+ const result = mapToChatMl(input);
+
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data).toHaveLength(2);
+ expect(result.data[0].role).toBe("system");
+ expect(result.data[1].role).toBe("user");
+ }
+ });
+
+ it("should parse object with messages key {messages: [ChatML...]}", () => {
+ const input = {
+ messages: [
+ { role: "system", content: "You are a helpful assistant." },
+ { role: "user", content: "Hello!" },
+ ],
+ temperature: 0.7,
+ model: "gpt-4",
+ };
+
+ const result = mapToChatMl(input);
+
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data).toHaveLength(2);
+ expect(result.data[0].role).toBe("system");
+ expect(result.data[1].role).toBe("user");
+ }
+ });
+
+ it("should fail gracefully for invalid input", () => {
+ const input = "not a valid format";
+
+ const result = mapToChatMl(input);
+
+ expect(result.success).toBe(false);
+ });
+
+ it("should fail gracefully for empty input", () => {
+ const result = mapToChatMl(null);
+
+ expect(result.success).toBe(false);
+ });
+
+ it("should handle complex message structures with additional fields", () => {
+ const input = [
+ {
+ role: "system",
+ content: "You are a helpful assistant.",
+ name: "system",
+ },
+ {
+ role: "user",
+ content: "Hello!",
+ additional_kwargs: { custom_field: "value" },
+ },
+ {
+ role: "assistant",
+ content: "Hi there!",
+ json: { metadata: "extra data" },
+ },
+ ];
+
+ const result = mapToChatMl(input);
+
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data).toHaveLength(3);
+ expect(result.data[0].name).toBe("system");
+ // ChatML schema transforms extra fields - expecting actual behavior
+ expect(result.data[2].json).toEqual({
+ json: { metadata: "extra data" },
+ });
+ }
+ });
+
+ it("should handle OpenAI content parts format", () => {
+ const input = [
+ {
+ role: "user",
+ content: [
+ { type: "text", text: "What's in this image?" },
+ {
+ type: "image_url",
+ image_url: { url: "data:image/jpeg;base64,..." },
+ },
+ ],
+ },
+ ];
+
+ const result = mapToChatMl(input);
+
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data).toHaveLength(1);
+ expect(Array.isArray(result.data[0].content)).toBe(true);
+ }
+ });
+
+ it("should handle tool call messages", () => {
+ const input = [
+ {
+ role: "assistant",
+ content: null,
+ tool_calls: [
+ {
+ id: "call_123",
+ type: "function",
+ function: { name: "get_weather", arguments: '{"city": "NYC"}' },
+ },
+ ],
+ },
+ {
+ role: "tool",
+ content: '{"temperature": 72}',
+ tool_call_id: "call_123",
+ },
+ ];
+
+ const result = mapToChatMl(input);
+
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data).toHaveLength(2);
+ expect(result.data[0].role).toBe("assistant");
+ expect(result.data[1].role).toBe("tool");
+ }
+ });
+
+ it("should handle placeholder messages", () => {
+ const input = [
+ {
+ role: "user",
+ content: "Hello",
+ },
+ {
+ type: "placeholder",
+ name: "Processing...",
+ },
+ {
+ role: "assistant",
+ content: "Hi there!",
+ },
+ ];
+
+ const result = mapToChatMl(input);
+
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data).toHaveLength(3);
+ expect(result.data[1].type).toBe("placeholder");
+ }
+ });
+ });
+
+ describe("mapOutputToChatMl", () => {
+ it("should parse direct output array", () => {
+ const output = [{ role: "assistant", content: "Hello there!" }];
+
+ const result = mapOutputToChatMl(output);
+
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data).toHaveLength(1);
+ expect(result.data[0].role).toBe("assistant");
+ }
+ });
+
+ it("should parse single output object as array", () => {
+ const output = { role: "assistant", content: "Hello there!" };
+
+ const result = mapOutputToChatMl(output);
+
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data).toHaveLength(1);
+ expect(result.data[0].role).toBe("assistant");
+ }
+ });
+
+ it("should handle legacy completion format {completion: string}", () => {
+ const output = { completion: "This is a legacy completion response" };
+
+ const result = mapOutputToChatMl(output);
+
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data).toHaveLength(1);
+ // ChatML schema transforms the object, putting extra fields in json
+ expect(result.data[0]).toEqual({
+ audio: undefined,
+ content: undefined,
+ json: { completion: "This is a legacy completion response" },
+ name: undefined,
+ role: undefined,
+ type: undefined,
+ });
+ }
+ });
+
+ it("should handle string output", () => {
+ const output = "Simple string response";
+
+ const result = mapOutputToChatMl(output);
+
+ // Strings don't pass ChatML validation
+ expect(result.success).toBe(false);
+ });
+
+ it("should handle output with metadata", () => {
+ const output = {
+ role: "assistant",
+ content: "Response with metadata",
+ usage: { prompt_tokens: 10, completion_tokens: 5 },
+ };
+
+ const result = mapOutputToChatMl(output);
+
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data).toHaveLength(1);
+ expect(result.data[0].role).toBe("assistant");
+ expect(result.data[0].json).toEqual({
+ usage: { prompt_tokens: 10, completion_tokens: 5 },
+ });
+ }
+ });
+
+ it("should handle null/undefined output", () => {
+ const result1 = mapOutputToChatMl(null);
+ const result2 = mapOutputToChatMl(undefined);
+
+ // null/undefined don't pass ChatML validation
+ expect(result1.success).toBe(false);
+ expect(result2.success).toBe(false);
+ });
+ });
+
+ describe("error scenarios", () => {
+ it("should handle deeply nested invalid structures", () => {
+ const input = {
+ messages: {
+ nested: {
+ deeply: "invalid structure",
+ },
+ },
+ };
+
+ const result = mapToChatMl(input);
+
+ expect(result.success).toBe(false);
+ });
+
+ it("should handle circular references gracefully", () => {
+ const input: any = { role: "user", content: "test" };
+ input.circular = input;
+
+ // Should not crash, though parsing may fail
+ expect(() => mapToChatMl([input])).not.toThrow();
+ });
+
+ it("should handle very large inputs", () => {
+ const largeContent = "x".repeat(1000000); // 1million chars
+ const input = [{ role: "user", content: largeContent }];
+
+ const result = mapToChatMl(input);
+
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data[0].content).toHaveLength(1000000);
+ }
+ });
+
+ it("should preserve all original data in json field for complex objects", () => {
+ const input = [
+ {
+ role: "assistant",
+ content: "Response",
+ model: "gpt-4",
+ temperature: 0.7,
+ custom_metadata: { key: "value" },
+ additional_kwargs: { extra: "data" },
+ },
+ ];
+
+ const result = mapToChatMl(input);
+
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data[0].json).toEqual({
+ model: "gpt-4",
+ temperature: 0.7,
+ custom_metadata: { key: "value" },
+ extra: "data", // additional_kwargs gets flattened
+ });
+ }
+ });
+ });
+
+ describe("cleanLegacyOutput", () => {
+ it("should clean legacy completion format", () => {
+ const output = { completion: "This is a legacy completion response" };
+ const result = cleanLegacyOutput(output, "fallback");
+
+ expect(result).toEqual({
+ completion: "This is a legacy completion response",
+ });
+ });
+
+ it("should return fallback for non-legacy format", () => {
+ const output = { role: "assistant", content: "Regular response" };
+ const fallback = "fallback value";
+ const result = cleanLegacyOutput(output, fallback);
+
+ expect(result).toBe(fallback);
+ });
+
+ it("should handle null/undefined output", () => {
+ const fallback = "fallback value";
+ expect(cleanLegacyOutput(null, fallback)).toBe(fallback);
+ expect(cleanLegacyOutput(undefined, fallback)).toBe(fallback);
+ });
+ });
+
+ describe("extractAdditionalInput", () => {
+ it("should extract additional fields from object", () => {
+ const input = {
+ messages: [{ role: "user", content: "Hello" }],
+ temperature: 0.7,
+ model: "gpt-4",
+ custom_param: "value",
+ };
+
+ const result = extractAdditionalInput(input);
+
+ expect(result).toEqual({
+ temperature: 0.7,
+ model: "gpt-4",
+ custom_param: "value",
+ });
+ });
+
+ it("should return undefined for array input", () => {
+ const input = [{ role: "user", content: "Hello" }];
+ const result = extractAdditionalInput(input);
+
+ expect(result).toBeUndefined();
+ });
+
+ it("should return undefined for non-object input", () => {
+ expect(extractAdditionalInput("string")).toBeUndefined();
+ expect(extractAdditionalInput(42)).toBeUndefined();
+ expect(extractAdditionalInput(null)).toBeUndefined();
+ });
+
+ it("should return empty object when only messages field present", () => {
+ const input = { messages: [{ role: "user", content: "Hello" }] };
+ const result = extractAdditionalInput(input);
+
+ expect(result).toEqual({});
+ });
+ });
+
+ describe("combineInputOutputMessages", () => {
+ it("should combine successful input and output", () => {
+ const inputResult = {
+ success: true,
+ data: [{ role: "user", content: "Hello" }],
+ } as any;
+ const outputResult = {
+ success: true,
+ data: [{ content: "Hi there!" }],
+ } as any;
+ const cleanOutput = "fallback";
+
+ const result = combineInputOutputMessages(
+ inputResult,
+ outputResult,
+ cleanOutput,
+ );
+
+ expect(result).toHaveLength(2);
+ expect(result[0]).toEqual({ role: "user", content: "Hello" });
+ expect(result[1]).toEqual({ content: "Hi there!", role: "assistant" }); // role gets defaulted
+ });
+
+ it("should handle failed output with string fallback", () => {
+ const inputResult = {
+ success: true,
+ data: [{ role: "user", content: "Hello" }],
+ } as any;
+ const outputResult = { success: false, error: "error" } as any;
+ const cleanOutput = "String response";
+
+ const result = combineInputOutputMessages(
+ inputResult,
+ outputResult,
+ cleanOutput,
+ );
+
+ expect(result).toHaveLength(2);
+ expect(result[0]).toEqual({ role: "user", content: "Hello" });
+ expect(result[1]).toEqual({
+ role: "assistant",
+ content: "String response",
+ });
+ });
+
+ it("should handle failed output with object fallback", () => {
+ const inputResult = {
+ success: true,
+ data: [{ role: "user", content: "Hello" }],
+ } as any;
+ const outputResult = { success: false, error: "error" } as any;
+ const cleanOutput = { metadata: "extra info" };
+
+ const result = combineInputOutputMessages(
+ inputResult,
+ outputResult,
+ cleanOutput,
+ );
+
+ expect(result).toHaveLength(2);
+ expect(result[0]).toEqual({ role: "user", content: "Hello" });
+ expect(result[1]).toEqual({
+ role: "assistant",
+ json: { metadata: "extra info" },
+ });
+ });
+
+ it("should warn when called with failed input parsing", () => {
+ const inputResult = { success: false, error: "error" } as any;
+ const outputResult = { success: true, data: [{ content: "Hi" }] } as any;
+ const cleanOutput = "fallback";
+
+ // Should not crash even with failed input
+ expect(() =>
+ combineInputOutputMessages(inputResult, outputResult, cleanOutput),
+ ).not.toThrow();
+ });
+ });
+
+ describe("isLangGraphTrace", () => {
+ it("should return false for null metadata", () => {
+ const generation = { metadata: null };
+ const result = isLangGraphTrace(generation);
+ expect(result).toBe(false);
+ });
+
+ it("should return true for metadata containing LANGGRAPH_NODE_TAG", () => {
+ const generation = {
+ metadata: JSON.stringify({ langgraph_node: "some_node" }),
+ };
+ const result = isLangGraphTrace(generation);
+ expect(result).toBe(true);
+ });
+
+ it("should return true for metadata containing LANGGRAPH_STEP_TAG", () => {
+ const generation = {
+ metadata: JSON.stringify({ langgraph_step: 1 }),
+ };
+ const result = isLangGraphTrace(generation);
+ expect(result).toBe(true);
+ });
+
+ it("should return false for metadata without LangGraph tags", () => {
+ const generation = {
+ metadata: JSON.stringify({ other_field: "value" }),
+ };
+ const result = isLangGraphTrace(generation);
+ expect(result).toBe(false);
+ });
+ });
+
+ describe("normalizeLangGraphMessage", () => {
+ it("should return message as-is if null", () => {
+ const result = normalizeLangGraphMessage(null);
+ expect(result).toBe(null);
+ });
+
+ it("should return message as-is if not an object", () => {
+ const result = normalizeLangGraphMessage("not an object");
+ expect(result).toBe("not an object");
+ });
+
+ it("should convert Google/Gemini 'model' role to 'assistant'", () => {
+ const message = { role: "model", content: "response" };
+ const result = normalizeLangGraphMessage(message);
+ expect(result).toEqual({
+ role: "assistant",
+ content: "response",
+ });
+ });
+
+ it("should convert Google/Gemini 'parts' field to 'content'", () => {
+ const message = {
+ role: "user",
+ parts: [{ text: "Hello" }, { text: " world" }],
+ };
+ const result = normalizeLangGraphMessage(message);
+ expect(result).toEqual({
+ role: "user",
+ content: "Hello world",
+ });
+ });
+
+ it("should convert invalid LangGraph roles to 'tool' when isLangGraph=true", () => {
+ const message = { role: "custom_tool_name", content: "tool result" };
+ const result = normalizeLangGraphMessage(message, true);
+ expect(result).toEqual({
+ role: "tool",
+ content: "tool result",
+ _originalRole: "custom_tool_name",
+ });
+ });
+
+ it("should not convert invalid roles when isLangGraph=false", () => {
+ const message = { role: "custom_tool_name", content: "tool result" };
+ const result = normalizeLangGraphMessage(message, false);
+ expect(result).toEqual({
+ role: "custom_tool_name",
+ content: "tool result",
+ });
+ });
+ });
+});
diff --git a/web/src/utils/chatMlMappers.ts b/web/src/utils/chatMlMappers.ts
new file mode 100644
index 0000000000..95539eeec5
--- /dev/null
+++ b/web/src/utils/chatMlMappers.ts
@@ -0,0 +1,198 @@
+import { z } from "zod/v4";
+import {
+ ChatMlArraySchema,
+ type ChatMlMessageSchema,
+} from "@/src/components/schemas/ChatMlSchema";
+import {
+ LANGGRAPH_NODE_TAG,
+ LANGGRAPH_STEP_TAG,
+} from "@/src/features/trace-graph-view/types";
+import { ChatMessageRole } from "@langfuse/shared";
+
+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
+}
+
+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;
+
+ // Return raw result - filtering (Object.keys().length > 0) done at usage site
+ return additionalInput;
+}
+
+/**
+ * Combines input and output messages into a single chat conversation
+ * NOTE: Original only calls this when inputResult.success === true
+ */
+export function combineInputOutputMessages(
+ inputResult: ReturnType<typeof mapToChatMl>,
+ outputResult: ReturnType<typeof mapOutputToChatMl>,
+ cleanOutput: unknown,
+): ChatMlMessageSchema[] {
+ // IMPORTANT: Original only calls this function when inputResult.success === true
+ // So we can safely assume inputResult.data exists
+ if (!inputResult.success) {
+ // Return empty array to prevent crash - this should never happen in normal usage
+ return [];
+ }
+
+ const combinedMessages = [
+ ...inputResult.data, // Original assumes success, so no conditional here
+ ...(outputResult.success
+ ? outputResult.data.map((m) => ({
+ ...m,
+ role: m.role ?? "assistant",
+ }))
+ : [
+ {
+ role: "assistant",
+ ...(typeof cleanOutput === "string"
+ ? { content: cleanOutput }
+ : { json: cleanOutput }),
+ } as ChatMlMessageSchema,
+ ]),
+ ];
+
+ return combinedMessages;
+}
+
+/**
+ * Framework detection: Is LangGraph Trace?
+ * If so, we recognise roles as tool names
+ */
+export function isLangGraphTrace(generation: {
+ metadata: string | null;
+}): boolean {
+ if (!generation.metadata) return false;
+
+ try {
+ let metadata = generation.metadata;
+ if (typeof metadata === "string") {
+ metadata = JSON.parse(metadata);
+ }
+
+ if (typeof metadata === "object" && metadata !== null) {
+ return LANGGRAPH_NODE_TAG in metadata || LANGGRAPH_STEP_TAG in metadata;
+ }
+ } catch {
+ // Ignore JSON parsing errors
+ }
+
+ return false;
+}
+
+/**
+ * Normalize LangGraph tool messages by converting tool-name roles to "tool"
+ * and normalize Google/Gemini format (model role + parts field)
+ */
+export 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;
+}