🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(trace): render thinking / reasoning parts in trace detail (#11615)
Nimar4e0208813565
diff --git a/packages/shared/src/utils/IORepresentation/chatML/types.ts b/packages/shared/src/utils/IORepresentation/chatML/types.tsindex 3764eb715d..a541fecf0a 100644--- a/packages/shared/src/utils/IORepresentation/chatML/types.ts+++ b/packages/shared/src/utils/IORepresentation/chatML/types.ts@@ -92,6 +92,31 @@ const OpenAIInputAudioContentPart = z.object({}),});+/**+ * Thinking content part schema.+ * Used to represent model reasoning/thinking output from various providers.+ * Normalized format across the different adapters by the providers+ */+export const ThinkingContentPartSchema = z.object({+ type: z.literal("thinking"),+ content: z.string(),+ signature: z.string().optional(), // Anthropic's cryptographic signature+ summary: z.string().optional(), // OpenAI provides summaries+});+export type ThinkingContentPart = z.infer<typeof ThinkingContentPartSchema>;++/**+ * Redacted thinking content part.+ * Anthropic sometimes encrypts thinking content for safety reasons.+ */+export const RedactedThinkingContentPartSchema = z.object({+ type: z.literal("redacted_thinking"),+ data: z.string(), // Encrypted blob+});+export type RedactedThinkingContentPart = z.infer<+ typeof RedactedThinkingContentPartSchema+>;+/*** OpenAI text content part.* Used in content arrays for text portions of messages.@@ -211,6 +236,9 @@ export const BaseChatMlMessageSchema = ztools: z.array(ToolDefinitionSchema).optional(),tool_calls: z.array(ToolCallSchema).optional(),tool_call_id: z.string().optional(),+ // Thinking/reasoning content from models+ thinking: z.array(ThinkingContentPartSchema).optional(),+ redacted_thinking: z.array(RedactedThinkingContentPartSchema).optional(),}).passthrough();@@ -277,6 +305,8 @@ export const ChatMlMessageSchema = BaseChatMlMessageSchema.refine(tools,tool_calls,tool_call_id,+ thinking,+ redacted_thinking,...other}) => ({role,@@ -287,6 +317,8 @@ export const ChatMlMessageSchema = BaseChatMlMessageSchema.refine(tools,tool_calls,tool_call_id,+ thinking,+ redacted_thinking,...(Object.keys(other).length === 0 ? {} : { json: other }),}),);diff --git a/packages/shared/src/utils/chatml/adapters/gemini.ts b/packages/shared/src/utils/chatml/adapters/gemini.tsindex 686556a5c7..8d3a8a7872 100644--- a/packages/shared/src/utils/chatml/adapters/gemini.ts+++ b/packages/shared/src/utils/chatml/adapters/gemini.ts@@ -67,15 +67,25 @@ function getField(obj: unknown, snakeName: string, camelName: string): unknown {// The format {role: "tool", content: {type: "function"}} is LangGraph, handled by langgraph adapter/**- * Extract both tool calls and text from parts array- * Handles: function_call/functionCall, text, function_response/functionResponse+ * Thinking part structure for Gemini+ */+type ThinkingPart = {+ content: string;+};++/**+ * Extract tool calls, text, and thinking from parts array+ * Handles: function_call/functionCall, text, function_response/functionResponse, thought* snake_case is from python SDK while camelCase is from JavaScript SDK / REST+ * Gemini indicates thinking with `thought: true` flag on text parts*/function extractFromParts(parts: unknown[]): {toolCalls: Array<Record<string, unknown>>;+ thinkingParts: ThinkingPart[];text: string;} {const toolCalls: Array<Record<string, unknown>> = [];+ const thinkingParts: ThinkingPart[] = [];const textParts: string[] = [];for (const part of parts) {@@ -105,10 +115,17 @@ function extractFromParts(parts: unknown[]): {// {text: "..."} or {type: "text", text: "..."}// text can be a string (normal response) or an object (when responseMimeType: "application/json")+ // Check for thought flag (Gemini thinking indicator)if (p.text !== undefined && p.text !== null) {- textParts.push(- typeof p.text === "string" ? p.text : JSON.stringify(p.text, null, 2),- );+ const textContent =+ typeof p.text === "string" ? p.text : JSON.stringify(p.text, null, 2);++ // Gemini uses `thought: true` flag to indicate thinking content+ if (p.thought === true) {+ thinkingParts.push({ content: textContent });+ } else {+ textParts.push(textContent);+ }continue;}@@ -122,6 +139,7 @@ function extractFromParts(parts: unknown[]): {return {toolCalls,+ thinkingParts,text: textParts.join(""),};}@@ -235,15 +253,23 @@ function normalizeGeminiMessage(msg: unknown): Record<string, unknown> {// process top-level parts array// Gemini format: {parts: [{function_call/text/function_response}], role: "..."}if (normalized.parts && Array.isArray(normalized.parts)) {- const { toolCalls, text } = extractFromParts(normalized.parts);+ const { toolCalls, thinkingParts, text } = extractFromParts(+ normalized.parts,+ );if (toolCalls.length > 0) {normalized.tool_calls = toolCalls;}+ if (thinkingParts.length > 0) {+ normalized.thinking = thinkingParts.map((t) => ({+ type: "thinking" as const,+ content: t.content,+ }));+ }if (text) {normalized.content = text;- // Remove parts to avoid showing in passthrough- delete normalized.parts;}+ // Remove parts to avoid showing in passthrough (regardless of content)+ delete normalized.parts;}// process nested content.parts[]@@ -256,10 +282,16 @@ function normalizeGeminiMessage(msg: unknown): Record<string, unknown> {) {const content = normalized.content as Record<string, unknown>;if (Array.isArray(content.parts)) {- const { toolCalls } = extractFromParts(content.parts);+ const { toolCalls, thinkingParts } = extractFromParts(content.parts);if (toolCalls.length > 0) {normalized.tool_calls = toolCalls;}+ if (thinkingParts.length > 0) {+ normalized.thinking = thinkingParts.map((t) => ({+ type: "thinking" as const,+ content: t.content,+ }));+ }// Extract role if nestedif (content.role && typeof content.role === "string") {@@ -271,10 +303,16 @@ function normalizeGeminiMessage(msg: unknown): Record<string, unknown> {// process content as array (structured content format)// Gemini format: {content: [{type: "text", text: "..."}]}if (Array.isArray(normalized.content)) {- const { text } = extractFromParts(normalized.content);+ const { text, thinkingParts } = extractFromParts(normalized.content);if (text) {normalized.content = text;}+ if (thinkingParts.length > 0) {+ normalized.thinking = thinkingParts.map((t) => ({+ type: "thinking" as const,+ content: t.content,+ }));+ }}// For tool messages with rich object content, spread into messagediff --git a/packages/shared/src/utils/chatml/adapters/openai.ts b/packages/shared/src/utils/chatml/adapters/openai.tsindex 9a190a3898..210c9e34a9 100644--- a/packages/shared/src/utils/chatml/adapters/openai.ts+++ b/packages/shared/src/utils/chatml/adapters/openai.ts@@ -62,6 +62,55 @@ const OpenAIOutputSingleMessageSchema = z.looseObject({),});+/**+ * Extract thinking content from OpenAI Responses API reasoning item+ * Format: { type: "reasoning", content: [...], summary: [...] }+ */+function extractReasoningContent(item: Record<string, unknown>): {+ thinking: Array<{ type: "thinking"; content: string; summary?: string }>;+} | null {+ if (item.type !== "reasoning") return null;++ const contentArr = Array.isArray(item.content) ? item.content : [];+ const summaryArr = Array.isArray(item.summary) ? item.summary : [];++ // Extract text from content array (may contain {type: "text", text: "..."})+ const contentText = contentArr+ .map((c: unknown) => {+ if (typeof c === "string") return c;+ if (c && typeof c === "object" && "text" in c) {+ return (c as { text: string }).text;+ }+ return "";+ })+ .filter(Boolean)+ .join("\n");++ // Extract summary text+ const summaryText = summaryArr+ .map((s: unknown) => {+ if (typeof s === "string") return s;+ if (s && typeof s === "object" && "text" in s) {+ return (s as { text: string }).text;+ }+ return "";+ })+ .filter(Boolean)+ .join("\n");++ if (!contentText && !summaryText) return null;++ return {+ thinking: [+ {+ type: "thinking" as const,+ content: contentText || summaryText,+ ...(summaryText && contentText ? { summary: summaryText } : {}),+ },+ ],+ };+}+function normalizeMessage(msg: unknown): Record<string, unknown> {if (!msg || typeof msg !== "object") return {};@@ -69,6 +118,17 @@ function normalizeMessage(msg: unknown): Record<string, unknown> {// because removeNullFields moves unrecognized fields to json passthroughlet working = msg as Record<string, unknown>;+ // Handle OpenAI Responses API reasoning item+ // Format: { type: "reasoning", content: [...], summary: [...] }+ const reasoningContent = extractReasoningContent(working);+ if (reasoningContent) {+ return {+ role: "assistant",+ content: "",+ ...reasoningContent,+ };+ }+// Convert direct function call message to tool_calls array format// Format: { type: "function_call", name: "...", arguments: {...}, call_id: "..." }// Convert to: { role: "assistant", tool_calls: [{ id, name, arguments, type }] }diff --git a/packages/shared/src/utils/chatml/adapters/pydantic-ai.ts b/packages/shared/src/utils/chatml/adapters/pydantic-ai.tsindex 9db49e6453..6df2f3176e 100644--- a/packages/shared/src/utils/chatml/adapters/pydantic-ai.ts+++ b/packages/shared/src/utils/chatml/adapters/pydantic-ai.ts@@ -22,15 +22,34 @@ const PydanticAIMessagesSchema = z.array();/**- * Extract tool calls, text, and tool responses from parts array+ * Thinking part structure+ */+type ThinkingPart = {+ content: string;+ signature?: string;+};++/**+ * Redacted thinking part structure+ */+type RedactedThinkingPart = {+ data: string;+};++/**+ * Extract tool calls, text, thinking, and tool responses from parts array*/function extractFromParts(parts: unknown[]): {toolCalls: Array<Record<string, unknown>>;toolResponses: Array<Record<string, unknown>>;+ thinkingParts: ThinkingPart[];+ redactedThinkingParts: RedactedThinkingPart[];text: string;} {const toolCalls: Array<Record<string, unknown>> = [];const toolResponses: Array<Record<string, unknown>> = [];+ const thinkingParts: ThinkingPart[] = [];+ const redactedThinkingParts: RedactedThinkingPart[] = [];const textParts: string[] = [];for (const part of parts) {@@ -39,6 +58,25 @@ function extractFromParts(parts: unknown[]): {if (p.type === "text" && typeof p.content === "string") {textParts.push(p.content);+ } else if (p.type === "thinking") {+ // Handle thinking parts - content can be in 'content' or 'thinking' field+ const thinkingContent =+ typeof p.content === "string"+ ? p.content+ : typeof p.thinking === "string"+ ? p.thinking+ : "";+ if (thinkingContent) {+ thinkingParts.push({+ content: thinkingContent,+ signature: typeof p.signature === "string" ? p.signature : undefined,+ });+ }+ } else if (p.type === "redacted_thinking") {+ // Handle redacted/encrypted thinking+ if (typeof p.data === "string") {+ redactedThinkingParts.push({ data: p.data });+ }} else if (p.type === "tool_call") {toolCalls.push({id: p.id,@@ -60,7 +98,13 @@ function extractFromParts(parts: unknown[]): {}}- return { toolCalls, toolResponses, text: textParts.join("") };+ return {+ toolCalls,+ toolResponses,+ thinkingParts,+ redactedThinkingParts,+ text: textParts.join(""),+ };}/**@@ -123,17 +167,40 @@ function normalizeMessage(return removeNullFields(message);}- const { toolCalls, toolResponses, text } = extractFromParts(message.parts);+ const {+ toolCalls,+ toolResponses,+ thinkingParts,+ redactedThinkingParts,+ text,+ } = extractFromParts(message.parts);// Extract other fields (exclude role and parts)const { role: _role, parts: _parts, ...rest } = message;+ // Build thinking fields if present+ const thinkingFields: Record<string, unknown> = {};+ if (thinkingParts.length > 0) {+ thinkingFields.thinking = thinkingParts.map((t) => ({+ type: "thinking" as const,+ content: t.content,+ ...(t.signature ? { signature: t.signature } : {}),+ }));+ }+ if (redactedThinkingParts.length > 0) {+ thinkingFields.redacted_thinking = redactedThinkingParts.map((t) => ({+ type: "redacted_thinking" as const,+ data: t.data,+ }));+ }+// Assistant message with tool callsif (message.role === "assistant" && toolCalls.length > 0) {return removeNullFields({role: "assistant",content: text || "",tool_calls: toolCalls,+ ...thinkingFields,...rest,});}@@ -148,10 +215,11 @@ function normalizeMessage();}- // Regular text message+ // Regular text message (may include thinking for assistant messages)return removeNullFields({role: message.role,content: text || "",+ ...thinkingFields,...rest,});}diff --git a/web/src/components/trace2/components/IOPreview/components/ChatMessage.tsx b/web/src/components/trace2/components/IOPreview/components/ChatMessage.tsxindex 81cb88c2b2..879c57e7c0 100644--- a/web/src/components/trace2/components/IOPreview/components/ChatMessage.tsx+++ b/web/src/components/trace2/components/IOPreview/components/ChatMessage.tsx@@ -18,7 +18,10 @@ import {isPlaceholderMessage,isOnlyJsonMessage,parseToolCallsFromMessage,+ hasThinkingContent,+ hasRedactedThinkingContent,} from "./chat-message-utils";+import { ThinkingBlock, RedactedThinkingBlock } from "./ThinkingBlock";// View mode for pretty/json toggleexport type ViewMode = "pretty" | "json";@@ -148,8 +151,30 @@ export function ChatMessage({);}- // Content message (with optional tool calls)- if (hasContent) {+ // Content message (with optional tool calls and thinking)+ if (+ hasContent ||+ hasThinkingContent(message) ||+ hasRedactedThinkingContent(message)+ ) {+ // Thinking blocks to render after header+ const thinkingBlocks = (+ <>+ {hasThinkingContent(message) &&+ message.thinking?.map((t, i) => (+ <ThinkingBlock+ key={`thinking-${i}`}+ content={t.content}+ summary={t.summary}+ />+ ))}+ {hasRedactedThinkingContent(message) &&+ message.redacted_thinking?.map((t, i) => (+ <RedactedThinkingBlock key={`redacted-${i}`} data={t.data} />+ ))}+ </>+ );+return (<div className={cn("transition-colors hover:bg-muted")}>{/* Markdown view */}@@ -163,6 +188,7 @@ export function ChatMessage({)}audio={message.audio}controlButtons={passthroughToggleButton}+ afterHeader={thinkingBlocks}/>{toolCalls.length > 0 && (<div className="mt-2">@@ -182,6 +208,7 @@ export function ChatMessage({projectIdForPromptButtons={projectIdForPromptButtons}currentView={currentView}controlButtons={passthroughToggleButton}+ afterHeader={thinkingBlocks}/>{toolCalls.length > 0 && (<div className="mt-2">diff --git a/web/src/components/trace2/components/IOPreview/components/ThinkingBlock.tsx b/web/src/components/trace2/components/IOPreview/components/ThinkingBlock.tsxnew file mode 100644index 0000000000..bc6db25548--- /dev/null+++ b/web/src/components/trace2/components/IOPreview/components/ThinkingBlock.tsx@@ -0,0 +1,87 @@+import { useState } from "react";+import { ChevronRight } from "lucide-react";+import { cn } from "@/src/utils/tailwind";++interface ThinkingBlockProps {+ content: string;+ summary?: string;+ defaultExpanded?: boolean;+}++export function ThinkingBlock({+ content,+ summary,+ defaultExpanded = false,+}: ThinkingBlockProps) {+ const [expanded, setExpanded] = useState(defaultExpanded);+ const displayContent = summary || content;++ return (+ <div className="my-2 px-1">+ <button+ type="button"+ className="flex w-full cursor-pointer items-start gap-1 text-left text-muted-foreground hover:text-foreground"+ onClick={() => setExpanded(!expanded)}+ aria-expanded={expanded}+ >+ <ChevronRight+ className={cn(+ "mt-0.5 h-3 w-3 flex-shrink-0 transition-transform",+ expanded && "rotate-90",+ )}+ />+ <span className="text-xs font-medium">Thinking</span>+ {!expanded && (+ <span className="line-clamp-1 text-xs italic">{displayContent}</span>+ )}+ </button>++ {expanded && (+ <div className="ml-4 mt-1 whitespace-pre-wrap text-sm italic text-muted-foreground">+ {content}+ </div>+ )}+ </div>+ );+}++interface RedactedThinkingBlockProps {+ data: string;+ defaultExpanded?: boolean;+}++// redactedThinkingBlock renders redacted thinking content if flagged by Anthropic+export function RedactedThinkingBlock({+ data,+ defaultExpanded = false,+}: RedactedThinkingBlockProps) {+ const [expanded, setExpanded] = useState(defaultExpanded);++ return (+ <div className="my-2 px-1">+ <button+ type="button"+ className="flex w-full cursor-pointer items-start gap-1 text-left text-muted-foreground hover:text-foreground"+ onClick={() => setExpanded(!expanded)}+ aria-expanded={expanded}+ >+ <ChevronRight+ className={cn(+ "mt-0.5 h-3 w-3 flex-shrink-0 transition-transform",+ expanded && "rotate-90",+ )}+ />+ <span className="text-xs font-medium">Thinking (redacted)</span>+ {!expanded && (+ <span className="text-xs italic">[Encrypted thinking data]</span>+ )}+ </button>++ {expanded && (+ <div className="ml-4 mt-1 break-all rounded bg-muted/50 p-2 font-mono text-xs text-muted-foreground">+ {data}+ </div>+ )}+ </div>+ );+}diff --git a/web/src/components/trace2/components/IOPreview/components/chat-message-utils.ts b/web/src/components/trace2/components/IOPreview/components/chat-message-utils.tsindex 947cdb6f83..92a23b7631 100644--- a/web/src/components/trace2/components/IOPreview/components/chat-message-utils.ts+++ b/web/src/components/trace2/components/IOPreview/components/chat-message-utils.ts@@ -80,3 +80,20 @@ export function parseToolCallsFromMessage(? message.json.tool_calls: [];}++/**+ * Check if message has thinking content.+ */+export function hasThinkingContent(message: ChatMlMessage): boolean {+ return Array.isArray(message.thinking) && message.thinking.length > 0;+}++/**+ * Check if message has redacted thinking content.+ */+export function hasRedactedThinkingContent(message: ChatMlMessage): boolean {+ return (+ Array.isArray(message.redacted_thinking) &&+ message.redacted_thinking.length > 0+ );+}diff --git a/web/src/components/ui/MarkdownJsonView.tsx b/web/src/components/ui/MarkdownJsonView.tsxindex 89ed5ce358..53507062a1 100644--- a/web/src/components/ui/MarkdownJsonView.tsx+++ b/web/src/components/ui/MarkdownJsonView.tsx@@ -88,6 +88,7 @@ export function MarkdownJsonView({audio,media,controlButtons,+ afterHeader,}: {content?: unknown;title?: string;@@ -97,6 +98,8 @@ export function MarkdownJsonView({audio?: OpenAIOutputAudioType;media?: MediaReturnType[];controlButtons?: React.ReactNode;+ /** Content to render between header and main content (e.g., thinking blocks) */+ afterHeader?: React.ReactNode;}) {const stringOrValidatedMarkdown = useMemo(() => StringOrMarkdownSchema.safeParse(content),@@ -123,6 +126,7 @@ export function MarkdownJsonView({audio={audio}media={media}controlButtons={controlButtons}+ afterHeader={afterHeader}/>) : (<PrettyJsonView@@ -133,6 +137,7 @@ export function MarkdownJsonView({media={media}currentView="pretty"controlButtons={controlButtons}+ afterHeader={afterHeader}/>)}</>diff --git a/web/src/components/ui/MarkdownViewer.tsx b/web/src/components/ui/MarkdownViewer.tsxindex 4ad408ed29..3e6af7f4fd 100644--- a/web/src/components/ui/MarkdownViewer.tsx+++ b/web/src/components/ui/MarkdownViewer.tsx@@ -321,6 +321,7 @@ export function MarkdownView({media,className,controlButtons,+ afterHeader,}: {markdown: string | z.infer<typeof OpenAIContentSchema>;title?: string;@@ -330,6 +331,8 @@ export function MarkdownView({media?: MediaReturnType[];className?: string;controlButtons?: React.ReactNode;+ /** Content to render between header and main content (e.g., thinking blocks) */+ afterHeader?: React.ReactNode;}) {const capture = usePostHogClientCapture();const { resolvedTheme: theme } = useTheme();@@ -373,6 +376,7 @@ export function MarkdownView({<div className="border-t" /></>) : null}+ {afterHeader}<divclassName={cn("io-message-content grid grid-flow-row gap-2 px-1 py-2",diff --git a/web/src/components/ui/PrettyJsonView.tsx b/web/src/components/ui/PrettyJsonView.tsxindex f97a1fdc54..d07eaec1c0 100644--- a/web/src/components/ui/PrettyJsonView.tsx+++ b/web/src/components/ui/PrettyJsonView.tsx@@ -761,6 +761,8 @@ export function PrettyJsonView(props: {showNullValues?: boolean;stickyTopLevelKey?: boolean;showObservationTypeBadge?: boolean;+ /** Content to render between header and main content (e.g., thinking blocks) */+ afterHeader?: React.ReactNode;}) {// Use pre-parsed data if available, otherwise parse on-demandconst parsedJson = useMemo(() => {@@ -1352,6 +1354,7 @@ export function PrettyJsonView(props: {}/>) : null}+ {props.afterHeader}{props.scrollable ? (<divclassName={cn(