Skip to content

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

feat(io-table-cell): IO read-time extraction of compact representation (#10217)

marliessophie51d2e14444a1
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 8b6fce3fc4..602a27eea8 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -81,3 +81,6 @@ export * from "./interfaces/search";
// domain
export * from "./domain";
+
+// io representation
+export * from "./utils/IORepresentation";
diff --git a/packages/shared/src/utils/IORepresentation/chatML/toCompactVerbosityChatML.ts b/packages/shared/src/utils/IORepresentation/chatML/toCompactVerbosityChatML.ts
new file mode 100644
index 0000000000..8adfcd0ca1
--- /dev/null
+++ b/packages/shared/src/utils/IORepresentation/chatML/toCompactVerbosityChatML.ts
@@ -0,0 +1,69 @@
+import { SimpleChatMlArraySchema } from "./types";
+
+/**
+ * Extracts a preview string from ChatML-formatted IO data.
+ * Returns the last message's content or null if not ChatML.
+ *
+ * Detection order (first match wins):
+ * 1. Direct array: [{role, content}, ...]
+ * 2. Single message object: {role, content} → return content directly
+ * 3. Object with 'messages' key: {messages: [...]}
+ * 4. Otherwise: null
+ *
+ * @param io - The input or output data to extract compact representation from
+ * @returns Compact string representation or null if no data
+ */
+export function toCompactVerbosityChatML(io: unknown): {
+ success: boolean;
+ data: string | null;
+} {
+ try {
+ if (!io) return { success: false, data: null };
+
+ // Case 1: Direct array
+ if (Array.isArray(io)) {
+ const parsed = SimpleChatMlArraySchema.safeParse(io);
+ if (parsed.success && parsed.data.length > 0) {
+ const lastMessage = parsed.data[parsed.data.length - 1];
+ return {
+ success: true,
+ data: JSON.stringify(lastMessage.content) ?? null,
+ };
+ }
+ return { success: false, data: null };
+ }
+
+ // Case 2: Single message object with role+content
+ if (io && typeof io === "object" && !Array.isArray(io)) {
+ const obj = io as Record<string, unknown>;
+
+ // Check for direct role+content structure
+ if (
+ "role" in obj &&
+ typeof obj.role === "string" &&
+ "content" in obj &&
+ obj.content !== undefined
+ ) {
+ return { success: true, data: JSON.stringify(obj.content) ?? null };
+ }
+
+ // Case 3: Object with 'messages' key
+ if ("messages" in obj && Array.isArray(obj.messages)) {
+ const messages = obj.messages;
+ const parsed = SimpleChatMlArraySchema.safeParse(messages);
+ if (parsed.success && parsed.data.length > 0) {
+ const lastMessage = parsed.data[parsed.data.length - 1];
+ return {
+ success: true,
+ data: JSON.stringify(lastMessage.content) ?? null,
+ };
+ }
+ }
+ }
+
+ return { success: false, data: null };
+ } catch (error) {
+ // Schema validation can throw on malformed data (e.g., invalid media references in transforms)
+ return { success: false, data: null };
+ }
+}
diff --git a/packages/shared/src/utils/IORepresentation/chatML/types.ts b/packages/shared/src/utils/IORepresentation/chatML/types.ts
new file mode 100644
index 0000000000..2ddc38f8f6
--- /dev/null
+++ b/packages/shared/src/utils/IORepresentation/chatML/types.ts
@@ -0,0 +1,248 @@
+import { z } from "zod/v4";
+
+/**
+ * Schema for tool/function definitions in ChatML.
+ * Used to define available tools for LLM function calling.
+ */
+const ToolDefinitionSchema = z.object({
+ name: z.string(),
+ description: z.string().optional(),
+ parameters: z.record(z.string(), z.any()).optional(),
+});
+
+/**
+ * Schema for tool/function call invocations in ChatML.
+ * Represents an LLM's request to call a specific tool.
+ */
+const ToolCallSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ arguments: z.string(), // JSON string of arguments
+ type: z.string().optional(),
+ index: z.number().optional(),
+});
+
+/**
+ * Parsed Langfuse media reference.
+ * Extracted from magic string format: @@@langfuseMedia:type=X|id=Y|source=Z@@@
+ */
+export const ParsedMediaReferenceSchema = z.object({
+ type: z.string(),
+ id: z.string(),
+ source: z.string(),
+ referenceString: z.string(),
+});
+export type ParsedMediaReferenceType = z.infer<
+ typeof ParsedMediaReferenceSchema
+>;
+
+/**
+ * Schema that parses Langfuse media reference magic strings.
+ * Format: @@@langfuseMedia:type=image/jpeg|id=<uuid>|source=base64@@@
+ *
+ * Note: This schema uses transforms that can throw errors during validation
+ * if the magic string format is invalid. Always use with try-catch or safeParse.
+ */
+export const MediaReferenceStringSchema = z
+ .string()
+ .transform((str, ctx) => {
+ // @@@langfuseMedia:type=image/jpeg|id=cc48838a-3da8-4ca4-a007-2cf8df930e69|source=base64@@@
+ const magicStringPattern = /^@@@langfuseMedia:(.*)@@@$/;
+
+ const match = str.match(magicStringPattern);
+ if (!match) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Invalid langfuseMedia magic string format",
+ });
+ return z.NEVER;
+ }
+
+ const content = match[1];
+ const parts = content.split("|").filter(Boolean);
+
+ const metadata: Record<string, string> = {
+ referenceString: str,
+ };
+
+ for (const part of parts) {
+ const [key, value] = part.split("=");
+ if (key && value !== undefined) {
+ metadata[key.trim()] = value.trim();
+ } else {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `Invalid key-value pair: ${part}`,
+ });
+ return z.NEVER;
+ }
+ }
+ return metadata;
+ })
+ .pipe(ParsedMediaReferenceSchema);
+
+/**
+ * OpenAI input audio content part.
+ * Used for audio inputs in multimodal chat completions.
+ */
+const OpenAIInputAudioContentPart = z.object({
+ type: z.literal("input_audio"),
+ input_audio: z.object({
+ data: MediaReferenceStringSchema,
+ }),
+});
+
+/**
+ * OpenAI text content part.
+ * Used in content arrays for text portions of messages.
+ * Defined as per https://platform.openai.com/docs/api-reference/chat/create#chat-create-messages
+ */
+const OpenAITextContentPart = z.object({
+ type: z.union([
+ z.literal("text"),
+ z.literal("input_text"),
+ z.literal("output_text"),
+ ]),
+ text: z.string(),
+});
+export type OpenAITextContentPartType = z.infer<typeof OpenAITextContentPart>;
+
+/**
+ * URL for image content (http/https only).
+ */
+export const OpenAIUrlImageUrl = z.string().regex(/^https?:/);
+
+/**
+ * Base64-encoded image data URL.
+ * Supported formats: png, jpeg, jpg, gif, webp
+ */
+const OpenAIBase64ImageUrl = z
+ .string()
+ .regex(/^data:image\/(png|jpeg|jpg|gif|webp);base64,/);
+
+/**
+ * OpenAI image content part for vision-enabled models.
+ * Supports URL, Langfuse media reference, or base64-encoded images.
+ */
+const OpenAIImageContentPart = z.object({
+ type: z.literal("image_url"),
+ image_url: z.object({
+ url: z.union([
+ OpenAIUrlImageUrl,
+ MediaReferenceStringSchema,
+ OpenAIBase64ImageUrl,
+ ]),
+ detail: z.enum(["low", "high", "auto"]).optional(), // Controls how the model processes the image. Defaults to "auto". [https://platform.openai.com/docs/guides/vision/low-or-high-fidelity-image-understanding]
+ }),
+});
+export type OpenAIImageContentPartType = z.infer<typeof OpenAIImageContentPart>;
+
+/**
+ * Array of OpenAI content parts (text, image, audio).
+ * Used when message content is structured with multiple parts.
+ */
+export const OpenAIContentParts = z.array(
+ z.union([
+ OpenAITextContentPart,
+ OpenAIImageContentPart,
+ OpenAIInputAudioContentPart,
+ ]),
+);
+
+/**
+ * OpenAI output audio schema.
+ * Represents audio generated by the model.
+ */
+const OpenAIOutputAudioSchema = z.object({
+ data: MediaReferenceStringSchema,
+ transcript: z.string().optional(),
+});
+export type OpenAIOutputAudioType = z.infer<typeof OpenAIOutputAudioSchema>;
+
+/**
+ * OpenAI content schema for message content field.
+ * Can be either a simple string or an array of structured content parts.
+ * Nullable to support messages without content (e.g., tool call only).
+ */
+export const OpenAIContentSchema = z
+ .union([z.string(), OpenAIContentParts])
+ .nullable();
+export type OpenAIContentSchema = z.infer<typeof OpenAIContentSchema>;
+
+export const isOpenAITextContentPart = (
+ content: any,
+): content is z.infer<typeof OpenAITextContentPart> => {
+ return OpenAITextContentPart.safeParse(content).success;
+};
+
+export const isOpenAIImageContentPart = (
+ content: any,
+): content is z.infer<typeof OpenAIImageContentPart> => {
+ return OpenAIImageContentPart.safeParse(content).success;
+};
+
+/**
+ * Base ChatML message schema with full OpenAI API support.
+ *
+ * This schema validates messages from OpenAI's Chat Completions API and similar formats.
+ * It includes support for:
+ * - Text, image, and audio content (multimodal)
+ * - Tool/function calling (definitions and invocations)
+ * - Additional framework-specific metadata (via passthrough)
+ *
+ * Used primarily for frontend rendering where full message structure is needed.
+ * For simple content extraction, use SimpleChatMessageSchema instead.
+ *
+ */
+export const BaseChatMlMessageSchema = z
+ .object({
+ role: z.string().optional(),
+ name: z.string().optional(),
+ content: z
+ .union([
+ z.record(z.string(), z.any()),
+ z.string(),
+ z.array(z.any()),
+ OpenAIContentSchema,
+ ])
+ .nullish(),
+ audio: OpenAIOutputAudioSchema.optional(),
+ additional_kwargs: z.record(z.string(), z.any()).optional(),
+ tools: z.array(ToolDefinitionSchema).optional(),
+ tool_calls: z.array(ToolCallSchema).optional(),
+ tool_call_id: z.string().optional(),
+ })
+ .passthrough();
+
+/**
+ * Minimal ChatML message schema for backend content extraction.
+ *
+ * This schema is intentionally permissive and lightweight, designed for:
+ * - Fast validation during compact representation extraction
+ * - Accepting multiple chat formats (OpenAI, LangChain, Anthropic, etc.)
+ * - Avoiding expensive validation of media, audio, and tool structures
+ *
+ * Only validates the minimal structure needed to extract displayable content:
+ * - Presence of content field (string, array, or object)
+ * - Optional role field (not strictly required)
+ *
+ * Use this for backend operations. For frontend rendering, use BaseChatMlMessageSchema.
+ */
+const SimpleChatMessageSchema = z
+ .object({
+ role: z.string().optional(),
+ content: z
+ .union([
+ z.string(), // Simple string content
+ z.array(z.any()), // Content parts array (text/image/audio)
+ z.record(z.string(), z.any()), // Structured content object
+ ])
+ .nullish(),
+ })
+ .loose(); // Allow any extra fields
+
+/**
+ * Array of minimal ChatML messages.
+ * Used for backend extraction - validates array has at least one message.
+ */
+export const SimpleChatMlArraySchema = z.array(SimpleChatMessageSchema).min(1);
diff --git a/packages/shared/src/utils/IORepresentation/index.ts b/packages/shared/src/utils/IORepresentation/index.ts
new file mode 100644
index 0000000000..73f6309bc5
--- /dev/null
+++ b/packages/shared/src/utils/IORepresentation/index.ts
@@ -0,0 +1,2 @@
+export * from "./parseIO";
+export * from "./chatML/types";
diff --git a/packages/shared/src/utils/IORepresentation/parseIO.ts b/packages/shared/src/utils/IORepresentation/parseIO.ts
new file mode 100644
index 0000000000..3c2c22a9f4
--- /dev/null
+++ b/packages/shared/src/utils/IORepresentation/parseIO.ts
@@ -0,0 +1,14 @@
+import { toCompactVerbosity } from "./toCompactVerbosity";
+
+export const parseIO = (
+ io: unknown,
+ verbosity: "compact" | "truncated" | "full",
+) => {
+ if (verbosity === "compact") {
+ const compact = toCompactVerbosity(io);
+ if (compact.success) {
+ return compact.data;
+ }
+ }
+ return io;
+};
diff --git a/packages/shared/src/utils/IORepresentation/toCompactVerbosity.ts b/packages/shared/src/utils/IORepresentation/toCompactVerbosity.ts
new file mode 100644
index 0000000000..56e6028b05
--- /dev/null
+++ b/packages/shared/src/utils/IORepresentation/toCompactVerbosity.ts
@@ -0,0 +1,33 @@
+import { toCompactVerbosityChatML } from "./chatML/toCompactVerbosityChatML";
+
+/**
+ * Returns a compact representation of IO data for display in tables.
+ * Strategy: Try ChatML extraction if possible.
+ *
+ * @param io - The input or output data to compact
+ * @returns Compact representation or null if no data
+ */
+export function toCompactVerbosity(io: unknown): {
+ success: boolean;
+ data: string | null;
+} {
+ if (io === undefined || io === null) return { success: false, data: null };
+
+ // Parse stringified JSON if needed
+ let parsedIO = io;
+ if (typeof io === "string") {
+ try {
+ parsedIO = JSON.parse(io);
+ } catch {
+ // Continue with original input
+ }
+ }
+
+ // Try ChatML compact representation extraction
+ const chatMLCompact = toCompactVerbosityChatML(parsedIO);
+ if (chatMLCompact.success) {
+ return { success: true, data: chatMLCompact.data };
+ }
+
+ return { success: false, data: null };
+}
diff --git a/web/src/components/schemas/ChatMlSchema.ts b/web/src/components/schemas/ChatMlSchema.ts
index a6c82de4bc..0796d72a7f 100644
--- a/web/src/components/schemas/ChatMlSchema.ts
+++ b/web/src/components/schemas/ChatMlSchema.ts
@@ -1,143 +1,9 @@
+import { BaseChatMlMessageSchema } from "@langfuse/shared";
import { z } from "zod/v4";
-// OpenAI API Content Schema defined as per https://platform.openai.com/docs/api-reference/chat/create#chat-create-messages, 28.04.2025
-const OpenAITextContentPart = z.object({
- type: z.union([
- z.literal("text"),
- z.literal("input_text"),
- z.literal("output_text"),
- ]),
- text: z.string(),
-});
-export type OpenAITextContentPartType = z.infer<typeof OpenAITextContentPart>;
-
-export const OpenAIUrlImageUrl = z.string().regex(/^https?:/);
-
-export const ParsedMediaReferenceSchema = z.object({
- type: z.string(),
- id: z.string(),
- source: z.string(),
- referenceString: z.string(),
-});
-export type ParsedMediaReferenceType = z.infer<
- typeof ParsedMediaReferenceSchema
->;
-
-export const MediaReferenceStringSchema = z
- .string()
- .transform((str, ctx) => {
- // @@@langfuseMedia:type=image/jpeg|id=cc48838a-3da8-4ca4-a007-2cf8df930e69|source=base64@@@
- const magicStringPattern = /^@@@langfuseMedia:(.*)@@@$/;
-
- const match = str.match(magicStringPattern);
- if (!match) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- message: "Invalid langfuseMedia magic string format",
- });
- return z.NEVER;
- }
-
- const content = match[1];
- const parts = content.split("|").filter(Boolean);
-
- const metadata: Record<string, string> = {
- referenceString: str,
- };
-
- for (const part of parts) {
- const [key, value] = part.split("=");
- if (key && value !== undefined) {
- metadata[key.trim()] = value.trim();
- } else {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- message: `Invalid key-value pair: ${part}`,
- });
- return z.NEVER;
- }
- }
- return metadata;
- })
- .pipe(ParsedMediaReferenceSchema);
-
-const OpenAIBase64ImageUrl = z
- .string()
- .regex(/^data:image\/(png|jpeg|jpg|gif|webp);base64,/);
-
-const OpenAIImageContentPart = z.object({
- type: z.literal("image_url"),
- image_url: z.object({
- url: z.union([
- OpenAIUrlImageUrl,
- MediaReferenceStringSchema,
- OpenAIBase64ImageUrl,
- ]),
- detail: z.enum(["low", "high", "auto"]).optional(), // Controls how the model processes the image. Defaults to "auto". [https://platform.openai.com/docs/guides/vision/low-or-high-fidelity-image-understanding]
- }),
-});
-export type OpenAIImageContentPartType = z.infer<typeof OpenAIImageContentPart>;
-
-const OpenAIInputAudioContentPart = z.object({
- type: z.literal("input_audio"),
- input_audio: z.object({
- data: MediaReferenceStringSchema,
- }),
-});
-
-const OpenAIOutputAudioSchema = z.object({
- data: MediaReferenceStringSchema,
- transcript: z.string().optional(),
-});
-export type OpenAIOutputAudioType = z.infer<typeof OpenAIOutputAudioSchema>;
-
-export const OpenAIContentParts = z.array(
- z.union([
- OpenAITextContentPart,
- OpenAIImageContentPart,
- OpenAIInputAudioContentPart,
- ]),
-);
-
-export const OpenAIContentSchema = z
- .union([z.string(), OpenAIContentParts])
- .nullable();
-export type OpenAIContentSchema = z.infer<typeof OpenAIContentSchema>;
-
-const ToolDefinitionSchema = z.object({
- name: z.string(),
- description: z.string().optional(),
- parameters: z.record(z.string(), z.any()).optional(),
-});
-
-const ToolCallSchema = z.object({
- id: z.string(),
- name: z.string(),
- arguments: z.string(), // JSON string
- type: z.string().optional(),
- index: z.number().optional(),
-});
-
-export const ChatMlMessageSchema = z
- .object({
- role: z.string().optional(),
- name: z.string().optional(),
- content: z
- .union([
- z.record(z.string(), z.any()),
- z.string(),
- z.array(z.any()),
- OpenAIContentSchema,
- ])
- .nullish(),
- audio: OpenAIOutputAudioSchema.optional(),
- additional_kwargs: z.record(z.string(), z.any()).optional(),
- tools: z.array(ToolDefinitionSchema).optional(),
- tool_calls: z.array(ToolCallSchema).optional(),
- tool_call_id: z.string().optional(),
- })
- .passthrough()
- .refine((value) => value.content !== null || value.role !== undefined)
+export const ChatMlMessageSchema = BaseChatMlMessageSchema.refine(
+ (value) => value.content !== null || value.role !== undefined,
+)
.transform(({ additional_kwargs, ...other }) => ({
...other,
...additional_kwargs,
@@ -169,16 +35,3 @@ export type ChatMlMessageSchema = z.infer<typeof ChatMlMessageSchema>;
export const ChatMlArraySchema = z.array(ChatMlMessageSchema).min(1);
export type ChatMlArraySchema = z.infer<typeof ChatMlArraySchema>;
-
-// Typeguards to help with type inference in components
-export const isOpenAITextContentPart = (
- content: any,
-): content is z.infer<typeof OpenAITextContentPart> => {
- return OpenAITextContentPart.safeParse(content).success;
-};
-
-export const isOpenAIImageContentPart = (
- content: any,
-): content is z.infer<typeof OpenAIImageContentPart> => {
- return OpenAIImageContentPart.safeParse(content).success;
-};
diff --git a/web/src/components/table/use-cases/observations.tsx b/web/src/components/table/use-cases/observations.tsx
index c653593790..33448b252f 100644
--- a/web/src/components/table/use-cases/observations.tsx
+++ b/web/src/components/table/use-cases/observations.tsx
@@ -1302,7 +1302,7 @@ const GenerationsDynamicCell = ({
traceId,
projectId,
startTime,
- truncated: true,
+ verbosity: "compact",
},
{
enabled: typeof traceId === "string" && typeof observationId === "string",
diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsx
index 9433aa8a4e..282ee3abe3 100644
--- a/web/src/components/table/use-cases/traces.tsx
+++ b/web/src/components/table/use-cases/traces.tsx
@@ -1296,7 +1296,7 @@ const TracesDynamicCell = ({
singleLine?: boolean;
}) => {
const trace = api.traces.byId.useQuery(
- { traceId, projectId, timestamp, truncated: true },
+ { traceId, projectId, timestamp, verbosity: "compact" },
{
refetchOnMount: false, // prevents refetching loops
staleTime: 60 * 1000, // 1 minute
diff --git a/web/src/components/ui/LangfuseMediaView.tsx b/web/src/components/ui/LangfuseMediaView.tsx
index 8c3bc569cc..db3d108bc1 100644
--- a/web/src/components/ui/LangfuseMediaView.tsx
+++ b/web/src/components/ui/LangfuseMediaView.tsx
@@ -4,7 +4,7 @@ import { ImageOff } from "lucide-react";
import {
MediaReferenceStringSchema,
type ParsedMediaReferenceType,
-} from "@/src/components/schemas/ChatMlSchema";
+} from "@langfuse/shared";
import { ResizableImage } from "@/src/components/ui/resizable-image";
import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
import {
diff --git a/web/src/components/ui/MarkdownJsonView.tsx b/web/src/components/ui/MarkdownJsonView.tsx
index c74402047b..707317a324 100644
--- a/web/src/components/ui/MarkdownJsonView.tsx
+++ b/web/src/components/ui/MarkdownJsonView.tsx
@@ -1,7 +1,7 @@
import {
OpenAIContentSchema,
type OpenAIOutputAudioType,
-} from "@/src/components/schemas/ChatMlSchema";
+} from "@langfuse/shared";
import { StringOrMarkdownSchema } from "@/src/components/schemas/MarkdownSchema";
import { Button } from "@/src/components/ui/button";
import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";
diff --git a/web/src/components/ui/MarkdownViewer.tsx b/web/src/components/ui/MarkdownViewer.tsx
index edfd1a3712..da71c6a72f 100644
--- a/web/src/components/ui/MarkdownViewer.tsx
+++ b/web/src/components/ui/MarkdownViewer.tsx
@@ -26,7 +26,7 @@ import {
type OpenAIOutputAudioType,
isOpenAITextContentPart,
isOpenAIImageContentPart,
-} from "@/src/components/schemas/ChatMlSchema";
+} from "@langfuse/shared";
import { type z } from "zod/v4";
import { ResizableImage } from "@/src/components/ui/resizable-image";
import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";
diff --git a/web/src/server/api/routers/observations.ts b/web/src/server/api/routers/observations.ts
index 4c4a785fa9..77402be841 100644
--- a/web/src/server/api/routers/observations.ts
+++ b/web/src/server/api/routers/observations.ts
@@ -3,7 +3,7 @@ import {
createTRPCRouter,
protectedGetTraceProcedure,
} from "@/src/server/api/trpc";
-import { LangfuseNotFoundError } from "@langfuse/shared";
+import { LangfuseNotFoundError, parseIO } from "@langfuse/shared";
import {
getObservationById,
getObservationByIdFromEventsTable,
@@ -19,7 +19,7 @@ export const observationsRouter = createTRPCRouter({
traceId: z.string(), // required for protectedGetTraceProcedure
projectId: z.string(), // required for protectedGetTraceProcedure
startTime: z.date().nullish(),
- truncated: z.boolean().default(false), // used to truncate the input and output
+ verbosity: z.enum(["compact", "truncated", "full"]).default("full"),
}),
)
.query(async ({ input }) => {
@@ -30,7 +30,7 @@ export const observationsRouter = createTRPCRouter({
traceId: input.traceId,
startTime: input.startTime ?? undefined,
renderingProps: {
- truncated: input.truncated,
+ truncated: input.verbosity === "truncated",
shouldJsonParse: false,
},
};
@@ -45,8 +45,8 @@ export const observationsRouter = createTRPCRouter({
}
return {
...toDomainWithStringifiedMetadata(obs),
- input: obs.input as string,
- output: obs.output as string,
+ input: parseIO(obs.input, input.verbosity) as string,
+ output: parseIO(obs.output, input.verbosity) as string,
internalModel: obs?.internalModelId,
};
}),
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index fbc8781511..199628a607 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -252,7 +252,7 @@ export const traceRouter = createTRPCRouter({
projectId: z.string(), // used for security check
timestamp: z.date().nullish(), // timestamp of the trace. Used to query CH more efficiently
fromTimestamp: z.date().nullish(), // min timestamp of the trace. Used to query CH more efficiently
- truncated: z.boolean().default(false), // used to truncate the input and output
+ verbosity: z.enum(["compact", "truncated", "full"]).default("full"),
}),
)
.query(async ({ ctx }) => {
diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.ts
index e61684cc9a..66e6ca4b96 100644
--- a/web/src/server/api/trpc.ts
+++ b/web/src/server/api/trpc.ts
@@ -94,7 +94,7 @@ import {
import { AdminApiAuthService } from "@/src/ee/features/admin-api/server/adminApiAuth";
import { env } from "@/src/env.mjs";
-import { BaseError } from "@langfuse/shared";
+import { BaseError, parseIO } from "@langfuse/shared";
setUpSuperjson();
@@ -401,6 +401,7 @@ const inputTraceSchema = z.object({
timestamp: z.date().nullish(),
fromTimestamp: z.date().nullish(),
truncated: z.boolean().default(false),
+ verbosity: z.enum(["compact", "truncated", "full"]).default("full"),
});
const enforceTraceAccess = t.middleware(async (opts) => {
@@ -420,20 +421,21 @@ const enforceTraceAccess = t.middleware(async (opts) => {
const projectId = result.data.projectId;
const timestamp = result.data.timestamp;
const fromTimestamp = result.data.fromTimestamp;
+ const verbosity = result.data.verbosity;
- const trace = await getTraceById({
+ const clickhouseTrace = await getTraceById({
traceId,
projectId,
timestamp: timestamp ?? undefined,
fromTimestamp: fromTimestamp ?? undefined,
renderingProps: {
- truncated: result.data.truncated,
+ truncated: verbosity === "truncated",
shouldJsonParse: false, // we do not want to parse the input/output for tRPC
},
clickhouseFeatureTag: "tracing-trpc",
});
- if (!trace) {
+ if (!clickhouseTrace) {
logger.error(`Trace with id ${traceId} not found for project ${projectId}`);
throw new TRPCError({
code: "NOT_FOUND",
@@ -441,6 +443,12 @@ const enforceTraceAccess = t.middleware(async (opts) => {
});
}
+ const trace = {
+ ...clickhouseTrace,
+ input: parseIO(clickhouseTrace.input, verbosity),
+ output: parseIO(clickhouseTrace.output, verbosity),
+ };
+
const sessionProject = ctx.session?.user?.organizations
.flatMap((org) => org.projects)
.find(({ id }) => id === projectId);
@@ -481,7 +489,7 @@ const enforceTraceAccess = t.middleware(async (opts) => {
projectRole:
ctx.session?.user?.admin === true ? Role.OWNER : sessionProject?.role,
},
- trace: trace, // pass the trace to the next middleware so we do not need to fetch it again
+ trace, // pass the trace to the next middleware so we do not need to fetch it again
},
});
});
diff --git a/web/src/utils/chatml/adapters/aisdk.clienttest.ts b/web/src/utils/chatml/adapters/aisdk.clienttest.ts
index 6380d1f1a7..b19b01bf64 100644
--- a/web/src/utils/chatml/adapters/aisdk.clienttest.ts
+++ b/web/src/utils/chatml/adapters/aisdk.clienttest.ts
@@ -1,13 +1,36 @@
-jest.mock("@langfuse/shared", () => ({
- ChatMessageRole: {
- System: "system",
- Developer: "developer",
- User: "user",
- Assistant: "assistant",
- Tool: "tool",
- Model: "model",
- },
-}));
+jest.mock("@langfuse/shared", () => {
+ const { z } = require("zod/v4");
+
+ return {
+ ChatMessageRole: {
+ System: "system",
+ Developer: "developer",
+ User: "user",
+ Assistant: "assistant",
+ Tool: "tool",
+ Model: "model",
+ },
+ BaseChatMlMessageSchema: z
+ .object({
+ role: z.string().optional(),
+ name: z.string().optional(),
+ content: z
+ .union([
+ z.record(z.string(), z.any()),
+ z.string(),
+ z.array(z.any()),
+ z.any(), // Simplified - was OpenAIContentSchema
+ ])
+ .nullish(),
+ audio: z.any().optional(),
+ additional_kwargs: z.record(z.string(), z.any()).optional(),
+ tools: z.array(z.any()).optional(),
+ tool_calls: z.array(z.any()).optional(),
+ tool_call_id: z.string().optional(),
+ })
+ .passthrough(),
+ };
+});
import { normalizeInput } from "./index";
import { aisdkAdapter } from "./aisdk";
diff --git a/web/src/utils/chatml/adapters/gemini.clienttest.ts b/web/src/utils/chatml/adapters/gemini.clienttest.ts
index 3dfd6e4df8..4bf5e18d87 100644
--- a/web/src/utils/chatml/adapters/gemini.clienttest.ts
+++ b/web/src/utils/chatml/adapters/gemini.clienttest.ts
@@ -1,3 +1,37 @@
+jest.mock("@langfuse/shared", () => {
+ const { z } = require("zod/v4");
+
+ return {
+ ChatMessageRole: {
+ System: "system",
+ Developer: "developer",
+ User: "user",
+ Assistant: "assistant",
+ Tool: "tool",
+ Model: "model",
+ },
+ BaseChatMlMessageSchema: z
+ .object({
+ role: z.string().optional(),
+ name: z.string().optional(),
+ content: z
+ .union([
+ z.record(z.string(), z.any()),
+ z.string(),
+ z.array(z.any()),
+ z.any(), // Simplified - was OpenAIContentSchema
+ ])
+ .nullish(),
+ audio: z.any().optional(),
+ additional_kwargs: z.record(z.string(), z.any()).optional(),
+ tools: z.array(z.any()).optional(),
+ tool_calls: z.array(z.any()).optional(),
+ tool_call_id: z.string().optional(),
+ })
+ .passthrough(),
+ };
+});
+
import { geminiAdapter } from "./gemini";
import type { NormalizerContext } from "../types";
import { normalizeInput } from "./index";
diff --git a/web/src/utils/chatml/adapters/generic.clienttest.ts b/web/src/utils/chatml/adapters/generic.clienttest.ts
index 72578aa18b..9ed5a234e9 100644
--- a/web/src/utils/chatml/adapters/generic.clienttest.ts
+++ b/web/src/utils/chatml/adapters/generic.clienttest.ts
@@ -1,13 +1,36 @@
-jest.mock("@langfuse/shared", () => ({
- ChatMessageRole: {
- System: "system",
- Developer: "developer",
- User: "user",
- Assistant: "assistant",
- Tool: "tool",
- Model: "model",
- },
-}));
+jest.mock("@langfuse/shared", () => {
+ const { z } = require("zod/v4");
+
+ return {
+ ChatMessageRole: {
+ System: "system",
+ Developer: "developer",
+ User: "user",
+ Assistant: "assistant",
+ Tool: "tool",
+ Model: "model",
+ },
+ BaseChatMlMessageSchema: z
+ .object({
+ role: z.string().optional(),
+ name: z.string().optional(),
+ content: z
+ .union([
+ z.record(z.string(), z.any()),
+ z.string(),
+ z.array(z.any()),
+ z.any(), // Simplified - was OpenAIContentSchema
+ ])
+ .nullish(),
+ audio: z.any().optional(),
+ additional_kwargs: z.record(z.string(), z.any()).optional(),
+ tools: z.array(z.any()).optional(),
+ tool_calls: z.array(z.any()).optional(),
+ tool_call_id: z.string().optional(),
+ })
+ .passthrough(),
+ };
+});
import { normalizeInput, normalizeOutput } from "./index";
import { combineInputOutputMessages, cleanLegacyOutput } from "../core";
diff --git a/web/src/utils/chatml/adapters/langgraph.clienttest.ts b/web/src/utils/chatml/adapters/langgraph.clienttest.ts
index 89911f8351..591fb9d113 100644
--- a/web/src/utils/chatml/adapters/langgraph.clienttest.ts
+++ b/web/src/utils/chatml/adapters/langgraph.clienttest.ts
@@ -1,13 +1,36 @@
-jest.mock("@langfuse/shared", () => ({
- ChatMessageRole: {
- System: "system",
- Developer: "developer",
- User: "user",
- Assistant: "assistant",
- Tool: "tool",
- Model: "model",
- },
-}));
+jest.mock("@langfuse/shared", () => {
+ const { z } = require("zod/v4");
+
+ return {
+ ChatMessageRole: {
+ System: "system",
+ Developer: "developer",
+ User: "user",
+ Assistant: "assistant",
+ Tool: "tool",
+ Model: "model",
+ },
+ BaseChatMlMessageSchema: z
+ .object({
+ role: z.string().optional(),
+ name: z.string().optional(),
+ content: z
+ .union([
+ z.record(z.string(), z.any()),
+ z.string(),
+ z.array(z.any()),
+ z.any(), // Simplified - was OpenAIContentSchema
+ ])
+ .nullish(),
+ audio: z.any().optional(),
+ additional_kwargs: z.record(z.string(), z.any()).optional(),
+ tools: z.array(z.any()).optional(),
+ tool_calls: z.array(z.any()).optional(),
+ tool_call_id: z.string().optional(),
+ })
+ .passthrough(),
+ };
+});
import { normalizeInput } from "./index";
import { langgraphAdapter } from "./langgraph";
diff --git a/web/src/utils/chatml/adapters/microsoft-agent.clienttest.ts b/web/src/utils/chatml/adapters/microsoft-agent.clienttest.ts
index c98e4d35d4..f76c4652b2 100644
--- a/web/src/utils/chatml/adapters/microsoft-agent.clienttest.ts
+++ b/web/src/utils/chatml/adapters/microsoft-agent.clienttest.ts
@@ -1,13 +1,36 @@
-jest.mock("@langfuse/shared", () => ({
- ChatMessageRole: {
- System: "system",
- Developer: "developer",
- User: "user",
- Assistant: "assistant",
- Tool: "tool",
- Model: "model",
- },
-}));
+jest.mock("@langfuse/shared", () => {
+ const { z } = require("zod/v4");
+
+ return {
+ ChatMessageRole: {
+ System: "system",
+ Developer: "developer",
+ User: "user",
+ Assistant: "assistant",
+ Tool: "tool",
+ Model: "model",
+ },
+ BaseChatMlMessageSchema: z
+ .object({
+ role: z.string().optional(),
+ name: z.string().optional(),
+ content: z
+ .union([
+ z.record(z.string(), z.any()),
+ z.string(),
+ z.array(z.any()),
+ z.any(), // Simplified - was OpenAIContentSchema
+ ])
+ .nullish(),
+ audio: z.any().optional(),
+ additional_kwargs: z.record(z.string(), z.any()).optional(),
+ tools: z.array(z.any()).optional(),
+ tool_calls: z.array(z.any()).optional(),
+ tool_call_id: z.string().optional(),
+ })
+ .passthrough(),
+ };
+});
import { normalizeInput, normalizeOutput } from "./index";
import { microsoftAgentAdapter } from "./microsoft-agent";
diff --git a/web/src/utils/chatml/adapters/openai.clienttest.ts b/web/src/utils/chatml/adapters/openai.clienttest.ts
index f9cadbdd46..37663e36f0 100644
--- a/web/src/utils/chatml/adapters/openai.clienttest.ts
+++ b/web/src/utils/chatml/adapters/openai.clienttest.ts
@@ -1,13 +1,36 @@
-jest.mock("@langfuse/shared", () => ({
- ChatMessageRole: {
- System: "system",
- Developer: "developer",
- User: "user",
- Assistant: "assistant",
- Tool: "tool",
- Model: "model",
- },
-}));
+jest.mock("@langfuse/shared", () => {
+ const { z } = require("zod/v4");
+
+ return {
+ ChatMessageRole: {
+ System: "system",
+ Developer: "developer",
+ User: "user",
+ Assistant: "assistant",
+ Tool: "tool",
+ Model: "model",
+ },
+ BaseChatMlMessageSchema: z
+ .object({
+ role: z.string().optional(),
+ name: z.string().optional(),
+ content: z
+ .union([
+ z.record(z.string(), z.any()),
+ z.string(),
+ z.array(z.any()),
+ z.any(), // Simplified - was OpenAIContentSchema
+ ])
+ .nullish(),
+ audio: z.any().optional(),
+ additional_kwargs: z.record(z.string(), z.any()).optional(),
+ tools: z.array(z.any()).optional(),
+ tool_calls: z.array(z.any()).optional(),
+ tool_call_id: z.string().optional(),
+ })
+ .passthrough(),
+ };
+});
import { normalizeInput, normalizeOutput } from "./index";
import { openAIAdapter } from "./openai";
diff --git a/web/src/utils/chatml/integration.clienttest.ts b/web/src/utils/chatml/integration.clienttest.ts
index 088cb9fb27..c591c2b680 100644
--- a/web/src/utils/chatml/integration.clienttest.ts
+++ b/web/src/utils/chatml/integration.clienttest.ts
@@ -1,13 +1,36 @@
-jest.mock("@langfuse/shared", () => ({
- ChatMessageRole: {
- System: "system",
- Developer: "developer",
- User: "user",
- Assistant: "assistant",
- Tool: "tool",
- Model: "model",
- },
-}));
+jest.mock("@langfuse/shared", () => {
+ const { z } = require("zod/v4");
+
+ return {
+ ChatMessageRole: {
+ System: "system",
+ Developer: "developer",
+ User: "user",
+ Assistant: "assistant",
+ Tool: "tool",
+ Model: "model",
+ },
+ BaseChatMlMessageSchema: z
+ .object({
+ role: z.string().optional(),
+ name: z.string().optional(),
+ content: z
+ .union([
+ z.record(z.string(), z.any()),
+ z.string(),
+ z.array(z.any()),
+ z.any(), // Simplified - was OpenAIContentSchema
+ ])
+ .nullish(),
+ audio: z.any().optional(),
+ additional_kwargs: z.record(z.string(), z.any()).optional(),
+ tools: z.array(z.any()).optional(),
+ tool_calls: z.array(z.any()).optional(),
+ tool_call_id: z.string().optional(),
+ })
+ .passthrough(),
+ };
+});
import { normalizeInput, normalizeOutput } from "./adapters";
import {
diff --git a/web/src/utils/chatml/jumptoplayground.clienttest.ts b/web/src/utils/chatml/jumptoplayground.clienttest.ts
index a40a6272ba..d3f1501a0b 100644
--- a/web/src/utils/chatml/jumptoplayground.clienttest.ts
+++ b/web/src/utils/chatml/jumptoplayground.clienttest.ts
@@ -1,6 +1,23 @@
// Mock the problematic @langfuse/shared import before importing our functions
jest.mock("@langfuse/shared", () => {
const { z } = require("zod/v4");
+
+ const OpenAITextContentPart = z.object({
+ type: z.literal("text"),
+ text: z.string(),
+ });
+
+ const OpenAIImageContentPart = z.object({
+ type: z.literal("image_url"),
+ image_url: z.union([
+ z.string(),
+ z.object({
+ url: z.string(),
+ detail: z.enum(["auto", "low", "high"]).optional(),
+ }),
+ ]),
+ });
+
return {
ChatMessageRole: {
System: "system",
@@ -25,6 +42,31 @@ jest.mock("@langfuse/shared", () => {
parameters: z.any().optional(),
}),
}),
+ BaseChatMlMessageSchema: z
+ .object({
+ role: z.string().optional(),
+ name: z.string().optional(),
+ content: z
+ .union([
+ z.record(z.string(), z.any()),
+ z.string(),
+ z.array(z.any()),
+ z.any(), // Simplified - was OpenAIContentSchema
+ ])
+ .nullish(),
+ audio: z.any().optional(),
+ additional_kwargs: z.record(z.string(), z.any()).optional(),
+ tools: z.array(z.any()).optional(),
+ tool_calls: z.array(z.any()).optional(),
+ tool_call_id: z.string().optional(),
+ })
+ .passthrough(),
+ isOpenAITextContentPart: (content: any) => {
+ return OpenAITextContentPart.safeParse(content).success;
+ },
+ isOpenAIImageContentPart: (content: any) => {
+ return OpenAIImageContentPart.safeParse(content).success;
+ },
};
});
diff --git a/web/src/utils/chatml/playgroundConverter.ts b/web/src/utils/chatml/playgroundConverter.ts
index 07879e2737..9ea096597a 100644
--- a/web/src/utils/chatml/playgroundConverter.ts
+++ b/web/src/utils/chatml/playgroundConverter.ts
@@ -1,11 +1,9 @@
import type { ChatMlMessageSchema } from "@/src/components/schemas/ChatMlSchema";
-import {
- isOpenAITextContentPart,
- isOpenAIImageContentPart,
-} from "@/src/components/schemas/ChatMlSchema";
import {
ChatMessageRole,
ChatMessageType,
+ isOpenAITextContentPart,
+ isOpenAIImageContentPart,
type ChatMessage,
type PlaceholderMessage,
} from "@langfuse/shared";