Skip to content

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

fix(llm-completions): handle Bedrock reasoning content (#13527)

Hassieb Pakzad10c975805493
diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.ts
index 630459c99e..e5e8edbd7c 100644
--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts
+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts
@@ -53,6 +53,13 @@ import { logger } from "../logger";
import { LLMCompletionError } from "./errors";
export type CompletionWithReasoning = { text: string; reasoning?: string };
+type AIMessageContent = AIMessage["content"];
+type AIMessageContentBlock = Exclude<AIMessageContent, string>[number];
+type SplitAIMessageContent = {
+ text: string;
+ contentWithoutThinking: AIMessageContent;
+ reasoning?: string;
+};
const NON_RETRYABLE_LLM_ERROR_PATTERNS = [
"Request timed out",
@@ -67,6 +74,7 @@ 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.Bedrock]: new Set(["reasoning_content"]),
[LLMAdapter.VertexAI]: new Set(["reasoning"]),
[LLMAdapter.GoogleAIStudio]: new Set(["reasoning"]),
};
@@ -570,17 +578,15 @@ export async function fetchLLMCompletion(
.invoke(finalMessages, runConfigWithTimeout),
});
- // 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 { contentWithoutThinking, reasoning } = splitAIMessageContent(
+ result.content,
+ thinkingTypes,
);
-
- const parsed = ToolCallResponseSchema.safeParse(result);
+ const parsed = ToolCallResponseSchema.safeParse({
+ content: contentWithoutThinking,
+ tool_calls: result.tool_calls,
+ });
if (!parsed.success)
throw Error("Failed to parse LLM tool call result");
@@ -603,7 +609,7 @@ export async function fetchLLMCompletion(
abortController: runtimeTimeoutController,
operation: () =>
chatModel
- .pipe(new BytesOutputParser())
+ .pipe(createBytesOutputParser(thinkingTypes))
.stream(finalMessages, runConfigWithTimeout),
});
@@ -616,7 +622,21 @@ export async function fetchLLMCompletion(
abortController: runtimeTimeoutController,
operation: () => chatModel.invoke(finalMessages, runConfigWithTimeout),
});
- return extractCompletionWithReasoning(aiMessage, thinkingTypes);
+ const completion = extractCompletionWithReasoning(
+ aiMessage,
+ thinkingTypes,
+ );
+
+ // Bedrock only returns reasoning blocks for selected models. Preserve the
+ // historical plain-string shape when the response contains no reasoning.
+ if (
+ modelParams.adapter === LLMAdapter.Bedrock &&
+ completion.reasoning == null
+ ) {
+ return completion.text;
+ }
+
+ return completion;
}
const completion = await executeWithRuntimeTimeout({
@@ -681,54 +701,93 @@ 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;
+ const { text, reasoning } = splitAIMessageContent(
+ message.content,
+ thinkingBlockTypes,
+ );
+
+ return {
+ text,
+ ...(reasoning ? { reasoning } : {}),
+ };
+}
- if (typeof content === "string") return { text: content };
- if (!Array.isArray(content)) return { text: String(content) };
+function createBytesOutputParser(
+ thinkingBlockTypes: Set<string> | undefined,
+): BytesOutputParser {
+ return thinkingBlockTypes != null
+ ? new ThinkingBlockFilteringBytesOutputParser(thinkingBlockTypes)
+ : new BytesOutputParser();
+}
- const reasoning = extractReasoning(content, thinkingBlockTypes);
+class ThinkingBlockFilteringBytesOutputParser extends BytesOutputParser {
+ constructor(private readonly thinkingBlockTypes: Set<string>) {
+ super();
+ }
+
+ protected _baseMessageContentToString(
+ content: Exclude<AIMessageContent, string>,
+ ): string {
+ return splitAIMessageContent(content, this.thinkingBlockTypes).text;
+ }
+}
+
+function splitAIMessageContent(
+ content: AIMessageContent,
+ thinkingBlockTypes: Set<string>,
+): SplitAIMessageContent {
+ if (typeof content === "string") {
+ return { text: content, contentWithoutThinking: content };
+ }
+
+ if (!Array.isArray(content)) {
+ return { text: String(content), contentWithoutThinking: content };
+ }
const textParts: string[] = [];
+ const reasoningParts: string[] = [];
+ const contentWithoutThinking: AIMessageContentBlock[] = [];
+
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;
+ contentWithoutThinking.push(block as AIMessageContentBlock);
+ } else if (thinkingBlockTypes.has(block.type)) {
+ const reasoning = extractReasoningBlockText(block);
+ if (typeof reasoning === "string") reasoningParts.push(reasoning);
+ } else {
+ const text = extractTextBlockText(block);
if (typeof text === "string") textParts.push(text);
+ contentWithoutThinking.push(block);
}
}
return {
text: textParts.join(""),
- ...(reasoning ? { reasoning } : {}),
+ contentWithoutThinking,
+ ...(reasoningParts.length > 0
+ ? { reasoning: reasoningParts.join("") }
+ : {}),
};
}
+function extractTextBlockText(block: AIMessageContentBlock) {
+ return (block as any).text ?? (block as any).reasoning;
+}
+
+function extractReasoningBlockText(block: AIMessageContentBlock) {
+ const reasoningText = (block as any).reasoningText;
+
+ if (typeof reasoningText === "string") return reasoningText;
+ if (typeof reasoningText?.text === "string") return reasoningText.text;
+
+ return extractTextBlockText(block);
+}
+
/**
* Process baseURL template for OpenAI adapter only.
* Replaces {model} placeholder with actual model name.
diff --git a/worker/src/__tests__/fetchLLMCompletionReasoning.test.ts b/worker/src/__tests__/fetchLLMCompletionReasoning.test.ts
new file mode 100644
index 0000000000..d75dc49e30
--- /dev/null
+++ b/worker/src/__tests__/fetchLLMCompletionReasoning.test.ts
@@ -0,0 +1,279 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const invokeMock = vi.fn();
+const streamMock = vi.fn();
+const pipeMock = vi.fn().mockImplementation((parser) => ({
+ invoke: invokeMock,
+ stream: (...args: any[]) => parser.transform(streamMock(...args), {}),
+}));
+const bindToolsInvokeMock = vi.fn();
+const bindToolsMock = vi.fn().mockReturnValue({
+ invoke: bindToolsInvokeMock,
+});
+const chatBedrockConverseConstructorMock = vi
+ .fn()
+ .mockImplementation(function () {
+ return {
+ invoke: invokeMock,
+ bindTools: bindToolsMock,
+ pipe: pipeMock,
+ };
+ });
+
+class MockLLMCompletionError extends Error {
+ responseStatusCode: number;
+ isRetryable: boolean;
+ blockReason: null;
+
+ constructor(params: {
+ message: string;
+ responseStatusCode?: number;
+ isRetryable?: boolean;
+ }) {
+ super(params.message);
+ this.name = "LLMCompletionError";
+ this.responseStatusCode = params.responseStatusCode ?? 500;
+ this.isRetryable = params.isRetryable ?? false;
+ this.blockReason = null;
+ }
+
+ shouldBlockConfig() {
+ return false;
+ }
+
+ getEvaluatorBlockReason() {
+ return null;
+ }
+}
+
+process.env.CLICKHOUSE_URL ??= "http://localhost:8123";
+process.env.CLICKHOUSE_USER ??= "default";
+process.env.CLICKHOUSE_PASSWORD ??= "password";
+process.env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET ??= "test-bucket";
+process.env.ENCRYPTION_KEY ??=
+ "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
+
+describe("fetchLLMCompletion Bedrock reasoning blocks", () => {
+ let originalCloudRegion: string | undefined;
+ let encrypt: typeof import("../../../packages/shared/src/encryption").encrypt;
+ let fetchLLMCompletion: typeof import("../../../packages/shared/src/server/llm/fetchLLMCompletion").fetchLLMCompletion;
+
+ beforeEach(async () => {
+ invokeMock.mockReset();
+ streamMock.mockReset();
+ pipeMock.mockClear();
+ bindToolsInvokeMock.mockReset();
+ bindToolsMock.mockClear();
+ chatBedrockConverseConstructorMock.mockClear();
+ vi.resetModules();
+ originalCloudRegion = process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
+ delete process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
+ vi.doMock("../../../packages/shared/node_modules/@langchain/aws", () => ({
+ ChatBedrockConverse: chatBedrockConverseConstructorMock,
+ }));
+ vi.doMock("../../../packages/shared/src/server/llm/errors", () => ({
+ LLMCompletionError: MockLLMCompletionError,
+ }));
+
+ ({ encrypt } = await import("../../../packages/shared/src/encryption"));
+ ({ fetchLLMCompletion } =
+ await import("../../../packages/shared/src/server/llm/fetchLLMCompletion"));
+ });
+
+ afterEach(() => {
+ if (originalCloudRegion === undefined) {
+ delete process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
+ } else {
+ process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;
+ }
+ });
+
+ it("preserves plain string completions when Bedrock returns no reasoning", async () => {
+ invokeMock.mockResolvedValue({
+ content: "4",
+ });
+
+ const completion = await fetchLLMCompletion({
+ streaming: false,
+ messages: [
+ {
+ role: "user",
+ content: "What is 2+2? Answer only with the number.",
+ type: "public-api-created",
+ },
+ ],
+ modelParams: {
+ provider: "bedrock",
+ adapter: "bedrock",
+ model: "openai.gpt-oss-120b-1:0",
+ temperature: 0,
+ max_tokens: 10,
+ },
+ llmConnection: {
+ secretKey: encrypt(JSON.stringify({ apiKey: "test-api-key" })),
+ config: {
+ region: "us-east-1",
+ },
+ },
+ });
+
+ expect(completion).toBe("4");
+ });
+
+ it("returns Bedrock GPT OSS reasoning separately from text", async () => {
+ invokeMock.mockResolvedValue({
+ content: [
+ {
+ type: "reasoning_content",
+ reasoningText: { text: "Compute the arithmetic." },
+ },
+ { type: "text", text: "4" },
+ ],
+ });
+
+ const completion = await fetchLLMCompletion({
+ streaming: false,
+ messages: [
+ {
+ role: "user",
+ content: "What is 2+2? Answer only with the number.",
+ type: "public-api-created",
+ },
+ ],
+ modelParams: {
+ provider: "bedrock",
+ adapter: "bedrock",
+ model: "openai.gpt-oss-120b-1:0",
+ temperature: 0,
+ max_tokens: 10,
+ },
+ llmConnection: {
+ secretKey: encrypt(JSON.stringify({ apiKey: "test-api-key" })),
+ config: {
+ region: "us-east-1",
+ },
+ },
+ });
+
+ expect(completion).toEqual({
+ text: "4",
+ reasoning: "Compute the arithmetic.",
+ });
+ });
+
+ it("strips Bedrock reasoning blocks before parsing tool calls", async () => {
+ bindToolsInvokeMock.mockResolvedValue({
+ content: [
+ {
+ type: "reasoning_content",
+ reasoningText: { text: "Need the weather tool." },
+ },
+ { type: "text", text: "" },
+ ],
+ tool_calls: [
+ {
+ id: "tool-use-1",
+ name: "get_weather",
+ args: { location: "Paris" },
+ },
+ ],
+ });
+
+ const completion = await fetchLLMCompletion({
+ streaming: false,
+ messages: [
+ {
+ role: "user",
+ content: "What's the weather like in Paris?",
+ type: "public-api-created",
+ },
+ ],
+ modelParams: {
+ provider: "bedrock",
+ adapter: "bedrock",
+ model: "openai.gpt-oss-120b-1:0",
+ temperature: 0,
+ max_tokens: 100,
+ },
+ tools: [
+ {
+ name: "get_weather",
+ description: "Get the current weather for a location",
+ parameters: {
+ type: "object",
+ properties: {
+ location: { type: "string" },
+ },
+ required: ["location"],
+ },
+ },
+ ],
+ llmConnection: {
+ secretKey: encrypt(JSON.stringify({ apiKey: "test-api-key" })),
+ config: {
+ region: "us-east-1",
+ },
+ },
+ });
+
+ expect(completion).toEqual({
+ content: [{ type: "text", text: "" }],
+ tool_calls: [
+ {
+ id: "tool-use-1",
+ name: "get_weather",
+ args: { location: "Paris" },
+ },
+ ],
+ reasoning: "Need the weather tool.",
+ });
+ });
+
+ it("filters Bedrock reasoning blocks out of streaming output", async () => {
+ streamMock.mockImplementation(async function* () {
+ yield {
+ content: [
+ {
+ type: "reasoning_content",
+ reasoningText: { text: "Do not show this in the playground." },
+ },
+ ],
+ };
+ yield {
+ content: [{ type: "text", text: "Hello!" }],
+ };
+ } as any);
+
+ const stream = await fetchLLMCompletion({
+ streaming: true,
+ messages: [
+ {
+ role: "user",
+ content: "hi",
+ type: "public-api-created",
+ },
+ ],
+ modelParams: {
+ provider: "bedrock",
+ adapter: "bedrock",
+ model: "openai.gpt-oss-120b-1:0",
+ temperature: 0,
+ max_tokens: 100,
+ },
+ llmConnection: {
+ secretKey: encrypt(JSON.stringify({ apiKey: "test-api-key" })),
+ config: {
+ region: "us-east-1",
+ },
+ },
+ });
+
+ const decoder = new TextDecoder();
+ let text = "";
+ for await (const chunk of stream) {
+ text += decoder.decode(chunk);
+ }
+
+ expect(text).toBe("Hello!");
+ });
+});