Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix: sanitize Claude thinking history signatures (#14499)

YuTengjing6989e8f9e6d1
diff --git a/packages/model-runtime/src/providers/anthropic/claudeThinkingHistory.ts b/packages/model-runtime/src/providers/anthropic/claudeThinkingHistory.ts
new file mode 100644
index 00000000000..7cfefcf9fb0
--- /dev/null
+++ b/packages/model-runtime/src/providers/anthropic/claudeThinkingHistory.ts
@@ -0,0 +1,85 @@
+import { isThinkingWithToolClaudeModel } from '../../const/models';
+import type { ChatStreamPayload, OpenAIChatMessage, UserMessageContentPart } from '../../types';
+
+interface ClaudeThinkingHistoryMessageMetadata {
+ model?: null | string;
+ provider?: null | string;
+ reasoning?: {
+ content?: string;
+ signature?: string;
+ };
+}
+
+/**
+ * Determine whether a historical assistant message was generated by Claude and
+ * can safely be replayed as Claude signed thinking.
+ */
+const isClaudeThinkingHistoryMessage = (message: OpenAIChatMessage): boolean => {
+ const { model, provider } = message as OpenAIChatMessage & ClaudeThinkingHistoryMessageMetadata;
+
+ // Prefer the source model when it is available. Router conversations can switch
+ // target providers mid-thread, and only Claude thinking-capable history can be
+ // replayed to Claude as a signed `thinking` block.
+ if (typeof model === 'string' && model) return isThinkingWithToolClaudeModel(model);
+
+ return provider === 'anthropic' || provider === 'bedrock';
+};
+
+const hasSignedThinkingPart = (content: UserMessageContentPart[]): boolean =>
+ content.some((part) => part.type === 'thinking' && !!part.signature);
+
+const filterSignedThinkingParts = (content: UserMessageContentPart[]): UserMessageContentPart[] =>
+ content.filter((part) => part.type !== 'thinking' || !part.signature);
+
+const toContentParts = (
+ content: OpenAIChatMessage['content'],
+): UserMessageContentPart[] | undefined => {
+ if (Array.isArray(content)) return content;
+ if (typeof content === 'string' && content.trim()) return [{ text: content, type: 'text' }];
+};
+
+/**
+ * Normalize historical assistant thinking only for Claude target runtimes.
+ *
+ * Anthropic validates `thinking.signature` against Claude-generated thinking.
+ * Signatures from other providers (for example DeepSeek UUID-like values) must
+ * not be forwarded as Claude thinking blocks, otherwise Claude rejects the
+ * request before generation starts.
+ *
+ * Keep this out of the shared Anthropic-compatible context builder because
+ * providers such as DeepSeek and Moonshot have their own thinking contracts.
+ */
+export const normalizeClaudeThinkingHistoryMessages = (
+ messages: ChatStreamPayload['messages'],
+): ChatStreamPayload['messages'] => {
+ return messages.map((message) => {
+ if (message.role !== 'assistant') return message;
+
+ const content = toContentParts(message.content);
+ const isClaudeThinkingMessage = isClaudeThinkingHistoryMessage(message);
+
+ if (!isClaudeThinkingMessage && Array.isArray(content) && hasSignedThinkingPart(content)) {
+ return {
+ ...message,
+ content: filterSignedThinkingParts(content),
+ };
+ }
+
+ const { reasoning } = message as OpenAIChatMessage & ClaudeThinkingHistoryMessageMetadata;
+
+ if (!isClaudeThinkingMessage || !reasoning?.content || !reasoning.signature) return message;
+ if (content && hasSignedThinkingPart(content)) return message;
+
+ return {
+ ...message,
+ content: [
+ {
+ signature: reasoning.signature,
+ thinking: reasoning.content,
+ type: 'thinking',
+ },
+ ...(content ?? []),
+ ],
+ };
+ });
+};
diff --git a/packages/model-runtime/src/providers/anthropic/index.test.ts b/packages/model-runtime/src/providers/anthropic/index.test.ts
index b9cb98a8e8a..8a46f2ac821 100644
--- a/packages/model-runtime/src/providers/anthropic/index.test.ts
+++ b/packages/model-runtime/src/providers/anthropic/index.test.ts
@@ -278,6 +278,68 @@ describe('LobeAnthropicAI', () => {
process.env.DEBUG_ANTHROPIC_CHAT_COMPLETION = originalDebugValue;
});
+ it('should convert Claude assistant reasoning signatures to thinking content', async () => {
+ await instance.chat({
+ messages: [
+ { content: 'Hello', role: 'user' },
+ {
+ content: 'Here is my response.',
+ model: 'claude-opus-4-7',
+ reasoning: {
+ content: 'Let me think about this...',
+ signature: 'EuYBCkQYAiJAHnHRJG4nPBrdTlo6CmXoyE8WYoQ=',
+ },
+ role: 'assistant',
+ } as any,
+ { content: 'Continue', role: 'user' },
+ ],
+ model: 'claude-opus-4-7',
+ temperature: 0,
+ });
+
+ const payload = (instance['client'].messages.create as Mock).mock.calls[0][0];
+
+ expect(payload.messages[1]).toEqual({
+ content: [
+ {
+ signature: 'EuYBCkQYAiJAHnHRJG4nPBrdTlo6CmXoyE8WYoQ=',
+ thinking: 'Let me think about this...',
+ type: 'thinking',
+ },
+ { text: 'Here is my response.', type: 'text' },
+ ],
+ role: 'assistant',
+ });
+ });
+
+ it('should not convert non-Claude reasoning signatures to thinking content', async () => {
+ await instance.chat({
+ messages: [
+ { content: 'Hello', role: 'user' },
+ {
+ content: 'Here is my response.',
+ model: 'deepseek-v4-pro',
+ provider: 'lobehub',
+ reasoning: {
+ content: 'DeepSeek reasoning',
+ signature: '340acffe-0000-4000-8000-000000000000',
+ },
+ role: 'assistant',
+ } as any,
+ { content: 'Continue', role: 'user' },
+ ],
+ model: 'claude-opus-4-7',
+ temperature: 0,
+ });
+
+ const payload = (instance['client'].messages.create as Mock).mock.calls[0][0];
+
+ expect(payload.messages[1]).toEqual({
+ content: 'Here is my response.',
+ role: 'assistant',
+ });
+ });
+
describe('chat with tools', () => {
it('should call tools when tools are provided', async () => {
// Arrange
diff --git a/packages/model-runtime/src/providers/anthropic/index.ts b/packages/model-runtime/src/providers/anthropic/index.ts
index 83cec6a124b..609aa2a68b3 100644
--- a/packages/model-runtime/src/providers/anthropic/index.ts
+++ b/packages/model-runtime/src/providers/anthropic/index.ts
@@ -1,11 +1,24 @@
import { ModelProvider } from 'model-bank';
import {
+ buildDefaultAnthropicPayload,
createAnthropicCompatibleParams,
createAnthropicCompatibleRuntime,
} from '../../core/anthropicCompatibleFactory';
+import type { ChatStreamPayload } from '../../types';
+import { normalizeClaudeThinkingHistoryMessages } from './claudeThinkingHistory';
+
+const buildAnthropicPayload = (payload: ChatStreamPayload) => {
+ return buildDefaultAnthropicPayload({
+ ...payload,
+ messages: normalizeClaudeThinkingHistoryMessages(payload.messages),
+ });
+};
export const params = createAnthropicCompatibleParams({
+ chatCompletion: {
+ handlePayload: buildAnthropicPayload,
+ },
debug: {
chatCompletion: () => process.env.DEBUG_ANTHROPIC_CHAT_COMPLETION === '1',
},
diff --git a/packages/model-runtime/src/providers/bedrock/index.test.ts b/packages/model-runtime/src/providers/bedrock/index.test.ts
index 72804777998..c941693e88c 100644
--- a/packages/model-runtime/src/providers/bedrock/index.test.ts
+++ b/packages/model-runtime/src/providers/bedrock/index.test.ts
@@ -222,6 +222,86 @@ describe('LobeBedrockAI', () => {
]);
});
+ it('should convert Claude assistant reasoning signatures to thinking content', async () => {
+ const mockStream = new ReadableStream({
+ start(controller) {
+ controller.enqueue('Hello, world!');
+ controller.close();
+ },
+ });
+ (instance['client'].send as Mock).mockResolvedValue(Promise.resolve(mockStream));
+
+ await instance.chat({
+ messages: [
+ { content: 'Hello', role: 'user' },
+ {
+ content: 'Here is my response.',
+ model: 'claude-opus-4-7',
+ reasoning: {
+ content: 'Let me think about this...',
+ signature: 'EuYBCkQYAiJAHnHRJG4nPBrdTlo6CmXoyE8WYoQ=',
+ },
+ role: 'assistant',
+ } as any,
+ { content: 'Continue', role: 'user' },
+ ],
+ model: 'anthropic.claude-sonnet-4-20250514-v1:0',
+ });
+
+ const commandInput = (InvokeModelWithResponseStreamCommand as unknown as Mock).mock
+ .calls[0][0];
+ const body = JSON.parse(commandInput.body);
+
+ expect(body.messages[1]).toEqual({
+ content: [
+ {
+ signature: 'EuYBCkQYAiJAHnHRJG4nPBrdTlo6CmXoyE8WYoQ=',
+ thinking: 'Let me think about this...',
+ type: 'thinking',
+ },
+ { text: 'Here is my response.', type: 'text' },
+ ],
+ role: 'assistant',
+ });
+ });
+
+ it('should not convert non-Claude reasoning signatures to thinking content', async () => {
+ const mockStream = new ReadableStream({
+ start(controller) {
+ controller.enqueue('Hello, world!');
+ controller.close();
+ },
+ });
+ (instance['client'].send as Mock).mockResolvedValue(Promise.resolve(mockStream));
+
+ await instance.chat({
+ messages: [
+ { content: 'Hello', role: 'user' },
+ {
+ content: 'Here is my response.',
+ model: 'deepseek-v4-pro',
+ provider: 'lobehub',
+ reasoning: {
+ content: 'DeepSeek reasoning',
+ signature: '340acffe-0000-4000-8000-000000000000',
+ },
+ role: 'assistant',
+ } as any,
+ { content: 'Continue', role: 'user' },
+ ],
+ model: 'anthropic.claude-sonnet-4-20250514-v1:0',
+ });
+
+ const commandInput = (InvokeModelWithResponseStreamCommand as unknown as Mock).mock
+ .calls[0][0];
+ const body = JSON.parse(commandInput.body);
+
+ expect(body.messages[1]).toEqual({
+ content: 'Here is my response.',
+ role: 'assistant',
+ });
+ });
+
it('should handle system prompt correctly', async () => {
// Arrange
const mockStream = new ReadableStream({
diff --git a/packages/model-runtime/src/providers/bedrock/index.ts b/packages/model-runtime/src/providers/bedrock/index.ts
index db04f8bdd40..b7d8dee0dbf 100644
--- a/packages/model-runtime/src/providers/bedrock/index.ts
+++ b/packages/model-runtime/src/providers/bedrock/index.ts
@@ -31,6 +31,7 @@ import { debugStream } from '../../utils/debugStream';
import { getModelPricing } from '../../utils/getModelPricing';
import { isExceededContextWindowError } from '../../utils/isExceededContextWindowError';
import { StreamingResponse } from '../../utils/response';
+import { normalizeClaudeThinkingHistoryMessages } from '../anthropic/claudeThinkingHistory';
/**
* A prompt constructor for HuggingFace LLama 2 chat models.
@@ -173,7 +174,9 @@ export class LobeBedrockAI implements LobeRuntimeAI {
} = payload;
const inputStartAt = Date.now();
const system_message = messages.find((m) => m.role === 'system');
- const user_messages = messages.filter((m) => m.role !== 'system');
+ const user_messages = normalizeClaudeThinkingHistoryMessages(
+ messages.filter((m) => m.role !== 'system'),
+ );
// Filter out empty/whitespace-only system prompts — Anthropic API rejects them
const systemPromptText =
typeof system_message?.content === 'string' && system_message.content.trim()