Skip to content

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

feat(playground/evals): handle thinking parts (#12233)

Nimar34c7a8a00504
diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.ts
index e91a6455cf..3f950ce6ae 100644
--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts
+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts
@@ -47,8 +47,21 @@ import { decryptAndParseExtraHeaders } from "./utils";
import { logger } from "../logger";
import { LLMCompletionError } from "./errors";
+export type CompletionWithReasoning = { text: string; reasoning?: string };
+
const isLangfuseCloud = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);
+// Maps adapters to the content block types that represent "thinking".
+// Used to extract reasoning separately and strip thinking parts from parsed output.
+const THINKING_BLOCK_TYPES: Partial<Record<LLMAdapter, Set<string>>> = {
+ [LLMAdapter.VertexAI]: new Set(["reasoning"]),
+ [LLMAdapter.GoogleAIStudio]: new Set(["reasoning"]),
+};
+
+function getThinkingBlockTypes(adapter: LLMAdapter): Set<string> | undefined {
+ return THINKING_BLOCK_TYPES[adapter];
+}
+
const PROVIDERS_WITH_REQUIRED_USER_MESSAGE = [
LLMAdapter.VertexAI,
LLMAdapter.GoogleAIStudio,
@@ -106,7 +119,7 @@ export async function fetchLLMCompletion(
params: LLMCompletionParams & {
streaming: false;
},
-): Promise<string>;
+): Promise<string | CompletionWithReasoning>;
export async function fetchLLMCompletion(
params: LLMCompletionParams & {
@@ -120,12 +133,13 @@ export async function fetchLLMCompletion(
streaming: false;
tools: LLMToolDefinition[];
},
-): Promise<ToolCallResponse>;
+): Promise<ToolCallResponse & { reasoning?: string }>;
export async function fetchLLMCompletion(
params: FetchLLMCompletionParams,
): Promise<
| string
+ | CompletionWithReasoning
| IterableReadableStream<Uint8Array>
| Record<string, unknown>
| ToolCallResponse
@@ -439,11 +453,23 @@ export async function fetchLLMCompletion(
metadata: traceSinkParams?.metadata,
};
+ const thinkingTypes = getThinkingBlockTypes(modelParams.adapter);
+
try {
// Important: await all generations in the try block as otherwise `processTracedEvents` will run too early in finally block
if (params.structuredOutputSchema) {
+ // Thinking-capable adapters may produce reasoning blocks that corrupt JSON schema
+ // parsing. Force function calling so the parser reads from tool_calls instead.
+ const structuredOutputConfig =
+ thinkingTypes != null
+ ? { method: "functionCalling" as const }
+ : undefined;
+
const structuredOutput = await chatModel
- .withStructuredOutput(params.structuredOutputSchema)
+ .withStructuredOutput(
+ params.structuredOutputSchema,
+ structuredOutputConfig,
+ )
.invoke(finalMessages, runConfig);
return structuredOutput;
@@ -459,6 +485,26 @@ export async function fetchLLMCompletion(
.bindTools(langchainTools)
.invoke(finalMessages, runConfig);
+ // For thinking adapters, strip reasoning blocks from content before parsing
+ // so ToolCallResponseSchema can validate. Extract reasoning separately.
+ if (thinkingTypes != null && Array.isArray(result.content)) {
+ const reasoning = extractReasoning(result.content, thinkingTypes);
+ // mutates Langchain AIMessage in place, not ideal but safe because only used for parsing below
+ result.content = result.content.filter(
+ (block) =>
+ typeof block === "string" || !thinkingTypes.has(block.type),
+ );
+
+ const parsed = ToolCallResponseSchema.safeParse(result);
+ if (!parsed.success)
+ throw Error("Failed to parse LLM tool call result");
+
+ return {
+ ...parsed.data,
+ ...(reasoning ? { reasoning } : {}),
+ };
+ }
+
const parsed = ToolCallResponseSchema.safeParse(result);
if (!parsed.success) throw Error("Failed to parse LLM tool call result");
@@ -470,6 +516,13 @@ export async function fetchLLMCompletion(
.pipe(new BytesOutputParser())
.stream(finalMessages, runConfig);
+ // content with thinking blocks can't be handled by StringOutputParser
+ // Invoke model directly and extract text + reasoning separately.
+ if (thinkingTypes != null) {
+ const aiMessage = await chatModel.invoke(finalMessages, runConfig);
+ return extractCompletionWithReasoning(aiMessage, thinkingTypes);
+ }
+
const completion = await chatModel
.pipe(new StringOutputParser())
.invoke(finalMessages, runConfig);
@@ -529,6 +582,54 @@ export async function fetchLLMCompletion(
}
}
+// extracts reasoning text from an array of content blocks.
+// returns concatenated reasoning or undefined if no reasoning blocks are found
+function extractReasoning(
+ content: AIMessage["content"],
+ thinkingBlockTypes: Set<string>,
+): string | undefined {
+ if (typeof content === "string" || !Array.isArray(content)) return undefined;
+ const parts: string[] = [];
+ for (const block of content) {
+ if (typeof block !== "string" && thinkingBlockTypes.has(block.type)) {
+ const text = (block as any).text ?? (block as any).reasoning;
+ if (typeof text === "string") parts.push(text);
+ }
+ }
+ return parts.length > 0 ? parts.join("") : undefined;
+}
+
+/**
+ * Splits AIMessage content into text and reasoning parts.
+ * Text parts are concatenated into `text`, thinking-type parts into `reasoning`.
+ */
+function extractCompletionWithReasoning(
+ message: AIMessage,
+ thinkingBlockTypes: Set<string>,
+): CompletionWithReasoning {
+ const { content } = message;
+
+ if (typeof content === "string") return { text: content };
+ if (!Array.isArray(content)) return { text: String(content) };
+
+ const reasoning = extractReasoning(content, thinkingBlockTypes);
+
+ const textParts: string[] = [];
+ for (const block of content) {
+ if (typeof block === "string") {
+ textParts.push(block);
+ } else if (!thinkingBlockTypes.has(block.type)) {
+ const text = (block as any).text ?? (block as any).reasoning;
+ if (typeof text === "string") textParts.push(text);
+ }
+ }
+
+ return {
+ text: textParts.join(""),
+ ...(reasoning ? { reasoning } : {}),
+ };
+}
+
/**
* Process baseURL template for OpenAI adapter only.
* Replaces {model} placeholder with actual model name.
diff --git a/web/src/components/ModelParameters/index.tsx b/web/src/components/ModelParameters/index.tsx
index e2d430cfe0..0b49e230de 100644
--- a/web/src/components/ModelParameters/index.tsx
+++ b/web/src/components/ModelParameters/index.tsx
@@ -185,10 +185,10 @@ export const ModelParameters: React.FC<ModelParamsContext> = ({
enabled={modelParams.maxReasoningTokens.enabled}
setModelParamEnabled={setModelParamEnabled}
value={modelParams.maxReasoningTokens.value}
- min={0}
+ min={-1}
max={24576}
step={1}
- tooltip="Maximum tokens for model thinking/reasoning. Set to 0 to disable. Only supported on Gemini 2.5+ models."
+ tooltip="Maximum tokens for model thinking/reasoning. Set to -1 for default (auto) thinking, 0 to disable. Only supported on Gemini 2.5+ models."
updateModelParam={updateModelParamValue}
/>
)}
diff --git a/web/src/features/playground/page/components/GenerationOutput.tsx b/web/src/features/playground/page/components/GenerationOutput.tsx
index 19f646c9af..81cf5acdb3 100644
--- a/web/src/features/playground/page/components/GenerationOutput.tsx
+++ b/web/src/features/playground/page/components/GenerationOutput.tsx
@@ -5,13 +5,14 @@ import { ChatMessageRole, ChatMessageType } from "@langfuse/shared";
import { BracesIcon, Check, Copy, Plus } from "lucide-react";
import { ToolCallCard } from "@/src/components/ChatMessages/ToolCallCard";
import { copyTextToClipboard } from "@/src/utils/clipboard";
+import { ThinkingBlock } from "@/src/components/trace2/components/IOPreview/components/ThinkingBlock";
export const GenerationOutput = () => {
const [isCopied, setIsCopied] = useState(false);
const [isAdded, setIsAdded] = useState(false);
const [isJson, setIsJson] = useState(false);
const scrollAreaRef = useRef<HTMLDivElement | null>(null);
- const { output, outputJson, addMessage, outputToolCalls } =
+ const { output, outputReasoning, outputJson, addMessage, outputToolCalls } =
usePlaygroundContext();
const handleCopy = () => {
@@ -100,6 +101,11 @@ export const GenerationOutput = () => {
</div>
</div>
<div className="px-4">
+ {outputReasoning && !isJson && (
+ <div className="-ml-1">
+ <ThinkingBlock content={outputReasoning} />
+ </div>
+ )}
<pre className="whitespace-break-spaces break-words text-xs">
{isJson ? outputJson : output}
</pre>
diff --git a/web/src/features/playground/page/context/index.tsx b/web/src/features/playground/page/context/index.tsx
index c867d4df5b..47e0a3826c 100644
--- a/web/src/features/playground/page/context/index.tsx
+++ b/web/src/features/playground/page/context/index.tsx
@@ -65,6 +65,7 @@ type PlaygroundContextType = {
setStructuredOutputSchema: (schema: PlaygroundSchema | null) => void;
output: string;
+ outputReasoning: string;
outputJson: string;
outputToolCalls: LLMToolCall[];
@@ -99,6 +100,7 @@ export const PlaygroundProvider: React.FC<PlaygroundProviderProps> = ({
PlaceholderMessageFillIn[]
>([]);
const [output, setOutput] = useState("");
+ const [outputReasoning, setOutputReasoning] = useState("");
const [outputToolCalls, setOutputToolCalls] = useState<LLMToolCall[]>([]);
const [outputJson, setOutputJson] = useState("");
const [isStreaming, setIsStreaming] = useState(false);
@@ -310,6 +312,7 @@ export const PlaygroundProvider: React.FC<PlaygroundProviderProps> = ({
try {
setIsStreaming(true);
setOutput("");
+ setOutputReasoning("");
setOutputJson("");
setOutputToolCalls([]);
@@ -388,12 +391,14 @@ export const PlaygroundProvider: React.FC<PlaygroundProviderProps> = ({
setOutput(response);
}
} else {
- response = await getChatCompletionNonStreaming(
+ const result = await getChatCompletionNonStreaming(
projectId,
finalMessages,
modelParams,
);
- setOutput(response);
+ response = result.content;
+ setOutput(result.content);
+ if (result.reasoning) setOutputReasoning(result.reasoning);
}
}
@@ -684,6 +689,7 @@ export const PlaygroundProvider: React.FC<PlaygroundProviderProps> = ({
providerModelCombinations,
output,
+ outputReasoning,
outputJson,
outputToolCalls,
handleSubmit,
@@ -846,7 +852,7 @@ async function getChatCompletionNonStreaming(
projectId: string | undefined,
messages: ChatMessageWithId[],
modelParams: UIModelParams,
-): Promise<string> {
+): Promise<{ content: string; reasoning?: string }> {
if (!projectId) {
throw new Error("Project ID is not set");
}
@@ -880,7 +886,10 @@ async function getChatCompletionNonStreaming(
}
const responseData = await result.json();
- return responseData.content || "";
+ return {
+ content: responseData.content || "",
+ reasoning: responseData.reasoning,
+ };
}
function getFinalMessages(
diff --git a/web/src/features/playground/server/chatCompletionHandler.ts b/web/src/features/playground/server/chatCompletionHandler.ts
index b45727391e..b47724c0f4 100644
--- a/web/src/features/playground/server/chatCompletionHandler.ts
+++ b/web/src/features/playground/server/chatCompletionHandler.ts
@@ -138,7 +138,14 @@ export default async function chatCompletionHandler(req: NextRequest) {
streaming,
});
- return NextResponse.json({ content: completion });
+ if (typeof completion === "string") {
+ return NextResponse.json({ content: completion });
+ } else {
+ return NextResponse.json({
+ content: completion.text,
+ reasoning: completion.reasoning,
+ });
+ }
}
});
} catch (err) {
diff --git a/worker/src/__tests__/llmConnections.test.ts b/worker/src/__tests__/llmConnections.test.ts
index 4011809d2d..78a7aff991 100644
--- a/worker/src/__tests__/llmConnections.test.ts
+++ b/worker/src/__tests__/llmConnections.test.ts
@@ -1,5 +1,8 @@
import { describe, test, expect } from "vitest";
-import { fetchLLMCompletion } from "@langfuse/shared/src/server";
+import {
+ fetchLLMCompletion,
+ type CompletionWithReasoning,
+} from "@langfuse/shared/src/server";
import { encrypt } from "@langfuse/shared/encryption";
import { ChatMessageType, LLMAdapter } from "@langfuse/shared";
import { z } from "zod/v4";
@@ -727,8 +730,9 @@ describe("LLM Connection Tests", () => {
},
});
- expect(typeof completion).toBe("string");
- expect(completion).toContain("4");
+ // VertexAI always returns CompletionWithReasoning (text + optional reasoning)
+ expect(typeof completion).toBe("object");
+ expect((completion as CompletionWithReasoning).text).toContain("4");
}, 30_000);
test("streaming completion", async () => {
@@ -837,6 +841,78 @@ describe("LLM Connection Tests", () => {
expect(completion.tool_calls[0].name).toBe("get_weather");
expect(completion.tool_calls[0].args).toHaveProperty("location");
}, 30_000);
+
+ test("thinking model with tool calling strips reasoning from content and parses tool calls", async () => {
+ checkEnvVar();
+
+ const completion = await fetchLLMCompletion({
+ streaming: false,
+ messages: [
+ {
+ role: "user",
+ content: "What's the weather like in Paris?",
+ type: ChatMessageType.PublicAPICreated,
+ },
+ ],
+ modelParams: {
+ provider: "google-vertex-ai",
+ adapter: LLMAdapter.VertexAI,
+ model: "gemini-2.5-flash",
+ temperature: 0,
+ max_tokens: 2048,
+ maxReasoningTokens: 1024,
+ },
+ tools: [weatherTool],
+ llmConnection: {
+ secretKey: encrypt(process.env.LANGFUSE_LLM_CONNECTION_VERTEXAI_KEY!),
+ config: null,
+ },
+ });
+
+ // Should parse tool calls successfully despite reasoning blocks in content
+ expect(completion).toHaveProperty("tool_calls");
+ expect(Array.isArray(completion.tool_calls)).toBe(true);
+ expect(completion.tool_calls.length).toBeGreaterThan(0);
+ expect(completion.tool_calls[0].name).toBe("get_weather");
+ // Reasoning should be extracted separately
+ if ((completion as any).reasoning) {
+ expect(typeof (completion as any).reasoning).toBe("string");
+ }
+ }, 60_000);
+
+ test("thinking model returns CompletionWithReasoning with separate text and reasoning", async () => {
+ checkEnvVar();
+
+ const completion = await fetchLLMCompletion({
+ streaming: false,
+ messages: [
+ {
+ role: "user",
+ content: "What is 2+2? Answer only with the number.",
+ type: ChatMessageType.PublicAPICreated,
+ },
+ ],
+ modelParams: {
+ provider: "google-vertex-ai",
+ adapter: LLMAdapter.VertexAI,
+ model: "gemini-2.5-flash",
+ temperature: 0,
+ max_tokens: 2048,
+ maxReasoningTokens: 1024,
+ },
+ llmConnection: {
+ secretKey: encrypt(process.env.LANGFUSE_LLM_CONNECTION_VERTEXAI_KEY!),
+ config: null,
+ },
+ });
+
+ // Always returns CompletionWithReasoning for VertexAI
+ expect(typeof completion).toBe("object");
+ const result = completion as CompletionWithReasoning;
+ expect(result.text).toContain("4");
+ // With maxReasoningTokens > 0, reasoning should be present
+ // Note: this depends on the model actually producing reasoning output
+ }, 60_000);
});
describe("GoogleAIStudio", () => {
@@ -878,8 +954,9 @@ describe("LLM Connection Tests", () => {
},
});
- expect(typeof completion).toBe("string");
- expect(completion).toContain("4");
+ // GoogleAIStudio always returns CompletionWithReasoning (text + optional reasoning)
+ expect(typeof completion).toBe("object");
+ expect((completion as CompletionWithReasoning).text).toContain("4");
}, 30_000);
test("streaming completion", async () => {
@@ -1021,8 +1098,9 @@ describe("LLM Connection Tests", () => {
},
});
- expect(typeof completion).toBe("string");
- expect(completion).toContain("4");
+ // GoogleAIStudio always returns CompletionWithReasoning
+ expect(typeof completion).toBe("object");
+ expect((completion as CompletionWithReasoning).text).toContain("4");
}, 30_000);
});
});