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(openapi): normalize Claude metadata for model relays (#19170)

AmAzing-5b9ef458e1fb
diff --git a/packages/openapi/src/routes/anthropic.route.ts b/packages/openapi/src/routes/anthropic.route.ts
index 5277d6c0a35..4777ebaa85c 100644
--- a/packages/openapi/src/routes/anthropic.route.ts
+++ b/packages/openapi/src/routes/anthropic.route.ts
@@ -1,3 +1,4 @@
+import { parseOpenAIModelId } from '@lobechat/model-runtime/providers/openai/modelId';
import {
formatServerDefaultHeterogeneousModel,
isServerDefaultHeterogeneousModel,
@@ -37,6 +38,8 @@ app.post('/v1/messages', requireHeteroModelInvocation('anthropic-messages'), asy
const workspaceId = context.get('workspaceId');
const agentType = context.get('heteroAgentType');
const requestModel = formatServerDefaultHeterogeneousModel(claims.model);
+ const unwrapSystemReminders =
+ agentType === 'claude-code' && parseOpenAIModelId(claims.model) !== undefined;
// Anything the model runtime throws has to be turned into an Anthropic error
// envelope here. Letting it escape hands the client a bodyless 500 — see
@@ -46,7 +49,9 @@ app.post('/v1/messages', requireHeteroModelInvocation('anthropic-messages'), asy
const { response } = await invokeServerDefaultModel({
agentType,
model: claims.model,
- payload: normalizeAnthropicRequest(request, SERVER_DEFAULT_MODEL_ALIAS),
+ payload: normalizeAnthropicRequest(request, SERVER_DEFAULT_MODEL_ALIAS, {
+ unwrapSystemReminders,
+ }),
signal: c.req.raw.signal,
userId: String(context.get('userId')),
workspaceId: typeof workspaceId === 'string' ? workspaceId : undefined,
diff --git a/packages/openapi/src/routes/heterogeneous-relay.route.test.ts b/packages/openapi/src/routes/heterogeneous-relay.route.test.ts
index cf30bb0047c..ec2300668a9 100644
--- a/packages/openapi/src/routes/heterogeneous-relay.route.test.ts
+++ b/packages/openapi/src/routes/heterogeneous-relay.route.test.ts
@@ -5,6 +5,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import type * as HeterogeneousDirectService from '../services/heterogeneous-direct.service';
const invokeServerDefaultModel = vi.hoisted(() => vi.fn());
+const relayContext = vi.hoisted(() => ({
+ anthropicAgentType: 'kimi-code',
+ model: 'deepseek-v4-pro',
+}));
vi.mock('@/server/modules/ModelRuntime', () => ({
initModelRuntimeFromServerConfig: vi.fn(),
@@ -16,11 +20,13 @@ vi.mock('../middleware/hetero-operation-auth', () => {
async (c, next) => {
c.set(
'heteroOperationClaims' as never,
- { model: 'deepseek-v4-pro', provider_id: 'lobehub' } as never,
+ { model: relayContext.model, provider_id: 'lobehub' } as never,
);
c.set(
'heteroAgentType' as never,
- (ingress === 'anthropic-messages' ? 'kimi-code' : 'grok-build') as never,
+ (ingress === 'anthropic-messages'
+ ? relayContext.anthropicAgentType
+ : 'grok-build') as never,
);
c.set('userId' as never, 'user-1' as never);
await next();
@@ -52,6 +58,8 @@ const failureMessage = '[volcengine] ProviderBizError: invalid value adaptive';
describe('heterogeneous relay route failures', () => {
beforeEach(() => {
vi.clearAllMocks();
+ relayContext.anthropicAgentType = 'kimi-code';
+ relayContext.model = 'deepseek-v4-pro';
invokeServerDefaultModel.mockRejectedValue(runtimeFailure);
});
@@ -76,6 +84,58 @@ describe('heterogeneous relay route failures', () => {
);
});
+ it('unwraps Claude Code system reminders before invoking a GPT model', async () => {
+ relayContext.anthropicAgentType = 'claude-code';
+ relayContext.model = 'gpt-6-astra';
+
+ await app.request('/anthropic/v1/messages', {
+ body: JSON.stringify({
+ messages: [
+ {
+ content: '<system-reminder>Current date context</system-reminder>\n\nMarker prompt',
+ role: 'user',
+ },
+ ],
+ model: 'lobehub/gpt-6-astra',
+ stream: true,
+ }),
+ headers: { 'content-type': 'application/json' },
+ method: 'POST',
+ });
+
+ expect(invokeServerDefaultModel).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentType: 'claude-code',
+ model: 'gpt-6-astra',
+ payload: expect.objectContaining({
+ messages: [{ content: 'Current date context\n\nMarker prompt', role: 'user' }],
+ }),
+ }),
+ );
+ });
+
+ it('preserves Claude Code system reminder markup for Claude models', async () => {
+ relayContext.anthropicAgentType = 'claude-code';
+ relayContext.model = 'claude-fable-5-1';
+ const content = '<system-reminder>Current date context</system-reminder>\n\nMarker prompt';
+
+ await app.request('/anthropic/v1/messages', {
+ body: JSON.stringify({
+ messages: [{ content, role: 'user' }],
+ model: 'lobehub/claude-fable-5-1',
+ stream: true,
+ }),
+ headers: { 'content-type': 'application/json' },
+ method: 'POST',
+ });
+
+ expect(invokeServerDefaultModel).toHaveBeenCalledWith(
+ expect.objectContaining({
+ payload: expect.objectContaining({ messages: [{ content, role: 'user' }] }),
+ }),
+ );
+ });
+
it('returns an OpenAI error envelope when model invocation rejects', async () => {
const response = await app.request('/openai/v1/responses', {
body: JSON.stringify({
diff --git a/packages/openapi/src/services/heterogeneous-direct.service.test.ts b/packages/openapi/src/services/heterogeneous-direct.service.test.ts
index 711b83a0057..b247a4243ea 100644
--- a/packages/openapi/src/services/heterogeneous-direct.service.test.ts
+++ b/packages/openapi/src/services/heterogeneous-direct.service.test.ts
@@ -318,6 +318,177 @@ describe('heterogeneous direct invocation protocol', () => {
});
});
+ it.each([
+ {
+ expected: 'Claude Code system prompt',
+ name: 'an array block preceded by an empty text block',
+ system: [
+ { text: '', type: 'text' },
+ {
+ text: 'x-anthropic-billing-header: cc_version=2.1.231; cc_entrypoint=sdk-cli;',
+ type: 'text',
+ },
+ { text: 'Claude Code system prompt', type: 'text' },
+ ],
+ },
+ {
+ expected: 'Claude Code system prompt',
+ name: 'a standalone array block',
+ system: [
+ {
+ text: 'x-anthropic-billing-header: cc_version=2.1.231; cc_entrypoint=sdk-cli;',
+ type: 'text',
+ },
+ { text: 'Claude Code system prompt', type: 'text' },
+ ],
+ },
+ {
+ expected: 'Claude Code system prompt',
+ name: 'a string followed by an LF blank line',
+ system:
+ 'x-anthropic-billing-header: cc_version=2.1.231; cc_entrypoint=sdk-cli;\n\nClaude Code system prompt',
+ },
+ {
+ expected: 'Claude Code system prompt',
+ name: 'an array block followed by a CRLF blank line',
+ system: [
+ {
+ text: 'x-anthropic-billing-header: cc_version=2.1.231;\r\n\r\nClaude Code system prompt',
+ type: 'text',
+ },
+ ],
+ },
+ {
+ expected: undefined,
+ name: 'the entire system prompt',
+ system: 'x-anthropic-billing-header: cc_version=2.1.231;',
+ },
+ ])('strips the Claude Code billing attribution when it is $name', ({ expected, system }) => {
+ const payload = normalizeAnthropicRequest({ messages: [], system }, 'lobehub-default');
+
+ expect(payload.messages).toEqual(expected ? [{ content: expected, role: 'system' }] : []);
+ });
+
+ it('preserves non-leading Anthropic billing header text as user-authored system content', () => {
+ const system =
+ 'Keep this text\nx-anthropic-billing-header: this non-leading occurrence is user content';
+ const payload = normalizeAnthropicRequest({ messages: [], system }, 'lobehub-default');
+
+ expect(payload.messages).toEqual([{ content: system, role: 'system' }]);
+ });
+
+ it('preserves an Anthropic billing header in a later system text block', () => {
+ const payload = normalizeAnthropicRequest(
+ {
+ messages: [],
+ system: [
+ { text: 'Keep this text\n', type: 'text' },
+ { text: 'x-anthropic-billing-header: this later block is user content', type: 'text' },
+ ],
+ },
+ 'lobehub-default',
+ );
+
+ expect(payload.messages).toEqual([
+ {
+ content: 'Keep this text\nx-anthropic-billing-header: this later block is user content',
+ role: 'system',
+ },
+ ]);
+ });
+
+ it('unwraps a leading Claude Code system reminder for GPT relay models', () => {
+ const payload = normalizeAnthropicRequest(
+ {
+ messages: [
+ {
+ content: [
+ {
+ text: [
+ '<system-reminder>',
+ 'As you answer the user, you can use the following context:',
+ '# currentDate',
+ "Today's date is 2026-09-05.",
+ '</system-reminder>',
+ '',
+ ].join('\r\n'),
+ type: 'text',
+ },
+ { text: 'Reply with exactly LOBEHUB_HETERO_SMOKE_OK.', type: 'text' },
+ ],
+ role: 'user',
+ },
+ ],
+ },
+ 'lobehub-default',
+ { unwrapSystemReminders: true },
+ );
+
+ expect(payload.messages).toEqual([
+ {
+ content: [
+ '',
+ 'As you answer the user, you can use the following context:',
+ '# currentDate',
+ "Today's date is 2026-09-05.",
+ '',
+ 'Reply with exactly LOBEHUB_HETERO_SMOKE_OK.',
+ ].join('\r\n'),
+ role: 'user',
+ },
+ ]);
+ });
+
+ it('preserves system reminder markup unless unwrapping is explicitly enabled', () => {
+ const content = 'Preface\n<system-reminder>user-authored text</system-reminder>';
+ const payload = normalizeAnthropicRequest(
+ { messages: [{ content, role: 'user' }] },
+ 'lobehub-default',
+ { unwrapSystemReminders: true },
+ );
+ const defaultPayload = normalizeAnthropicRequest(
+ {
+ messages: [
+ { content: '<system-reminder>Claude context</system-reminder>\n\nPrompt', role: 'user' },
+ ],
+ },
+ 'lobehub-default',
+ );
+
+ expect(payload.messages).toEqual([{ content, role: 'user' }]);
+ expect(defaultPayload.messages).toEqual([
+ {
+ content: '<system-reminder>Claude context</system-reminder>\n\nPrompt',
+ role: 'user',
+ },
+ ]);
+ });
+
+ it('does not unwrap a system reminder in a later text block', () => {
+ const payload = normalizeAnthropicRequest(
+ {
+ messages: [
+ {
+ content: [
+ { text: 'User preface\n', type: 'text' },
+ { text: '<system-reminder>user-authored text</system-reminder>', type: 'text' },
+ ],
+ role: 'user',
+ },
+ ],
+ },
+ 'lobehub-default',
+ { unwrapSystemReminders: true },
+ );
+
+ expect(payload.messages).toEqual([
+ {
+ content: 'User preface\n<system-reminder>user-authored text</system-reminder>',
+ role: 'user',
+ },
+ ]);
+ });
+
it('preserves Anthropic thinking history across tool rounds', () => {
const payload = normalizeAnthropicRequest(
{
diff --git a/packages/openapi/src/services/heterogeneous-direct.service.ts b/packages/openapi/src/services/heterogeneous-direct.service.ts
index bdb6fb4a0b6..f314ae9fca8 100644
--- a/packages/openapi/src/services/heterogeneous-direct.service.ts
+++ b/packages/openapi/src/services/heterogeneous-direct.service.ts
@@ -24,20 +24,32 @@ import type { BaseStreamEvent, ResponseUsage } from '../types/responses.type';
export const SERVER_DEFAULT_MODEL_ALIAS = SERVER_DEFAULT_HETEROGENEOUS_MODEL_ALIAS;
-const textFromParts = (content: unknown): string => {
- if (typeof content === 'string') return content;
+const textFromParts = (content: unknown, transformFirst = (text: string) => text): string => {
+ if (typeof content === 'string') return transformFirst(content);
if (!Array.isArray(content)) return '';
+ let foundText = false;
return content
- .map((part) =>
- isRecord(part) &&
- typeof part.text === 'string' &&
- ['text', 'input_text', 'output_text'].includes(String(part.type))
- ? part.text
- : '',
- )
+ .map((part) => {
+ if (
+ !isRecord(part) ||
+ typeof part.text !== 'string' ||
+ !['text', 'input_text', 'output_text'].includes(String(part.type))
+ ) {
+ return '';
+ }
+ const text = foundText ? part.text : transformFirst(part.text);
+ if (part.text) foundText = true;
+ return text;
+ })
.join('');
};
+const stripLeadingAnthropicBillingHeader = (text: string) =>
+ text.replace(/^x-anthropic-billing-header:[^\r\n]*(?:\r?\n(?:\r?\n)?)?/, '');
+
+const unwrapLeadingSystemReminder = (text: string) =>
+ text.replace(/^<system-reminder>([\s\S]*?)<\/system-reminder>/, '$1');
+
const imageParts = (content: unknown) => {
if (!Array.isArray(content)) return [];
return content.flatMap((part) => {
@@ -57,9 +69,12 @@ const imageParts = (content: unknown) => {
});
};
-const contentWithImages = (content: unknown): OpenAIChatMessage['content'] => {
+const contentWithImages = (
+ content: unknown,
+ transform = (text: string) => text,
+): OpenAIChatMessage['content'] => {
const images = imageParts(content);
- const text = textFromParts(content);
+ const text = transform(textFromParts(content));
return images.length > 0 ? [...(text ? [{ text, type: 'text' as const }] : []), ...images] : text;
};
@@ -95,10 +110,21 @@ const contentWithAnthropicThinking = (content: unknown): OpenAIChatMessage['cont
];
};
-export const normalizeAnthropicRequest = (request: Record<string, unknown>, model: string) => {
+interface NormalizeAnthropicRequestOptions {
+ unwrapSystemReminders?: boolean;
+}
+
+export const normalizeAnthropicRequest = (
+ request: Record<string, unknown>,
+ model: string,
+ options?: NormalizeAnthropicRequestOptions,
+) => {
const messages: OpenAIChatMessage[] = [];
- const system = textFromParts(request.system);
+ const system = textFromParts(request.system, stripLeadingAnthropicBillingHeader);
if (system) messages.push({ content: system, role: 'system' });
+ const transformUserText = options?.unwrapSystemReminders
+ ? unwrapLeadingSystemReminder
+ : undefined;
for (const rawMessage of Array.isArray(request.messages) ? request.messages : []) {
if (!isRecord(rawMessage) || !['assistant', 'user'].includes(String(rawMessage.role))) continue;
@@ -133,12 +159,15 @@ export const normalizeAnthropicRequest = (request: Record<string, unknown>, mode
}
const remaining = contentWithImages(
(content as unknown[]).filter((part) => !isRecord(part) || part.type !== 'tool_result'),
+ transformUserText,
);
if (remaining.length) messages.push({ content: remaining, role: 'user' });
continue;
}
const normalizedContent =
- role === 'assistant' ? contentWithAnthropicThinking(content) : contentWithImages(content);
+ role === 'assistant'
+ ? contentWithAnthropicThinking(content)
+ : contentWithImages(content, transformUserText);
const hasAnthropicThinking =
Array.isArray(normalizedContent) &&
normalizedContent.some(