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: preserve heterogeneous agent tool calls (#20956)

AmAzing-1550771da046
diff --git a/packages/model-runtime/package.json b/packages/model-runtime/package.json
index d7166ef1dd5..1fcc3d2d407 100644
--- a/packages/model-runtime/package.json
+++ b/packages/model-runtime/package.json
@@ -15,6 +15,7 @@
"./resolveImageSinglePrice": "./src/core/usageConverters/utils/resolveImageSinglePrice.ts",
"./resolveVideoSinglePrice": "./src/core/usageConverters/utils/resolveVideoSinglePrice.ts",
"./types/error": "./src/types/error.ts",
+ "./utils/anthropicToolSchema": "./src/utils/anthropicToolSchema.ts",
"./utils/createError": "./src/utils/createError.ts",
"./utils/modelExtendParams": "./src/utils/modelExtendParams.ts",
"./utils/uriParser": "./src/utils/uriParser.ts",
diff --git a/packages/model-runtime/src/core/contextBuilders/anthropic.ts b/packages/model-runtime/src/core/contextBuilders/anthropic.ts
index 286d3c5093f..06b592c3562 100644
--- a/packages/model-runtime/src/core/contextBuilders/anthropic.ts
+++ b/packages/model-runtime/src/core/contextBuilders/anthropic.ts
@@ -3,6 +3,7 @@ import { imageUrlToBase64, resolveImageMimeTypeFromBase64 } from '@lobechat/util
import type OpenAI from 'openai';
import type { OpenAIChatMessage, UserMessageContentPart } from '../../types';
+import { normalizeAnthropicToolSchema } from '../../utils/anthropicToolSchema';
import { parseDataUri } from '../../utils/uriParser';
const ANTHROPIC_SUPPORTED_IMAGE_TYPES = new Set([
@@ -470,7 +471,7 @@ export const buildAnthropicTools = (
? { type: 'ephemeral' }
: undefined,
description: fn.description,
- input_schema: fn.parameters as Anthropic.Tool.InputSchema,
+ input_schema: normalizeAnthropicToolSchema(fn.parameters) as Anthropic.Tool.InputSchema,
name: fn.name,
};
});
diff --git a/packages/model-runtime/src/core/contextBuilders/openai.responsesTools.test.ts b/packages/model-runtime/src/core/contextBuilders/openai.responsesTools.test.ts
new file mode 100644
index 00000000000..b3b60425e46
--- /dev/null
+++ b/packages/model-runtime/src/core/contextBuilders/openai.responsesTools.test.ts
@@ -0,0 +1,88 @@
+import type OpenAI from 'openai';
+import { describe, expect, it } from 'vitest';
+
+import { convertOpenAIResponseInputs } from './openai';
+
+export const nativeTools: OpenAI.Responses.Tool[] = [
+ {
+ type: 'namespace',
+ name: 'functions',
+ description: '',
+ tools: [{ type: 'custom', name: 'exec', format: { type: 'text' } }],
+ },
+];
+
+describe('Responses native tools', () => {
+ it('retains dynamic tools in order, raw custom input, namespace, and matching custom outputs', async () => {
+ const input = await convertOpenAIResponseInputs(
+ [
+ { role: 'user', content: 'Read file' },
+ { role: 'system', content: '', responsesTools: nativeTools },
+ {
+ role: 'assistant',
+ content: '',
+ tool_calls: [
+ {
+ id: 'custom-1',
+ type: 'custom',
+ namespace: 'functions',
+ function: { name: 'exec', arguments: 'read("probe.txt")' },
+ },
+ {
+ id: 'function-1',
+ type: 'function',
+ namespace: 'clock',
+ function: { name: 'now', arguments: '{}' },
+ },
+ { id: 'unpaired', type: 'custom', function: { name: 'exec', arguments: 'drop' } },
+ ],
+ },
+ { role: 'tool', content: 'file contents', tool_call_id: 'custom-1' },
+ { role: 'tool', content: 'time', tool_call_id: 'function-1' },
+ { role: 'tool', content: 'drop', tool_call_id: 'orphan' },
+ ],
+ { strictToolPairing: true },
+ );
+ expect(input).toEqual([
+ { role: 'user', content: 'Read file' },
+ { type: 'additional_tools', role: 'developer', tools: nativeTools },
+ {
+ type: 'custom_tool_call',
+ call_id: 'custom-1',
+ name: 'exec',
+ namespace: 'functions',
+ input: 'read("probe.txt")',
+ },
+ {
+ type: 'function_call',
+ call_id: 'function-1',
+ name: 'now',
+ namespace: 'clock',
+ arguments: '{}',
+ },
+ { type: 'custom_tool_call_output', call_id: 'custom-1', output: 'file contents' },
+ { type: 'function_call_output', call_id: 'function-1', output: 'time' },
+ ]);
+ });
+ it('replays native text, image and file tool-output parts without stringification or relocation', async () => {
+ const output: OpenAI.Responses.ResponseCustomToolCallOutput['output'] = [
+ { type: 'input_text', text: 'contents' },
+ { type: 'input_image', image_url: 'https://example.com/image.png', detail: 'high' },
+ { type: 'input_file', file_id: 'file-1' },
+ ];
+ const result = await convertOpenAIResponseInputs(
+ [
+ {
+ role: 'assistant',
+ content: '',
+ tool_calls: [
+ { id: 'call-1', type: 'custom', function: { name: 'exec', arguments: 'read()' } },
+ ],
+ },
+ { role: 'tool', tool_call_id: 'call-1', content: 'contents', responsesOutput: output },
+ ],
+ { strictToolPairing: true },
+ );
+ expect(result[1]).toEqual({ type: 'custom_tool_call_output', call_id: 'call-1', output });
+ });
+});
diff --git a/packages/model-runtime/src/core/contextBuilders/openai.ts b/packages/model-runtime/src/core/contextBuilders/openai.ts
index 638b7085c4f..9d12ff8c8ac 100644
--- a/packages/model-runtime/src/core/contextBuilders/openai.ts
+++ b/packages/model-runtime/src/core/contextBuilders/openai.ts
@@ -304,11 +304,13 @@ export const convertOpenAIResponseInputs = async (
// "No tool output found for function call call_w5odMFjtXEYBBVyBUAQNMOh5."
const validToolCallIds = new Set<string>();
const pairedToolOutputIds = new Set<string>();
+ const customToolCallIds = new Set<string>();
for (const message of messages) {
if (message.role === 'assistant' && message.tool_calls?.length) {
message.tool_calls.forEach((tool) => {
if (tool.id) validToolCallIds.add(tool.id);
+ if (tool.id && tool.type === 'custom') customToolCallIds.add(tool.id);
});
}
}
@@ -327,6 +329,15 @@ export const convertOpenAIResponseInputs = async (
messages.map(async (message) => {
const items: OpenAI.Responses.ResponseInputItem[] = [];
const reasoning = message.reasoning;
+ if (message.responsesTools) {
+ return [
+ {
+ type: 'additional_tools',
+ role: 'developer',
+ tools: message.responsesTools,
+ } satisfies OpenAI.Responses.ResponseInputItem,
+ ];
+ }
/**
* Resolve persisted Responses reasoning items for stateless replay. Encrypted
@@ -393,12 +404,24 @@ export const convertOpenAIResponseInputs = async (
: message.tool_calls;
toolCalls.forEach((tool) => {
- items.push({
- arguments: strictToolPairing ? tool.function.arguments : tool.function.name,
+ const identity = {
call_id: tool.id,
name: tool.function.name,
- type: 'function_call',
- });
+ ...(tool.namespace ? { namespace: tool.namespace } : {}),
+ };
+ items.push(
+ tool.type === 'custom'
+ ? {
+ ...identity,
+ input: tool.function.arguments,
+ type: 'custom_tool_call',
+ }
+ : {
+ ...identity,
+ arguments: strictToolPairing ? tool.function.arguments : tool.function.name,
+ type: 'function_call',
+ },
+ );
});
return items;
@@ -411,6 +434,17 @@ export const convertOpenAIResponseInputs = async (
)
return items;
+ if (message.responsesOutput !== undefined) {
+ items.push({
+ call_id: message.tool_call_id!,
+ output: message.responsesOutput,
+ type: customToolCallIds.has(message.tool_call_id!)
+ ? 'custom_tool_call_output'
+ : 'function_call_output',
+ });
+ return items;
+ }
+
// `function_call_output.output` is text-only. When the tool result
// carries images (e.g. builtin `readFile` on an image file), keep the
// output textual and re-attach the images as a follow-up user message
@@ -432,8 +466,10 @@ export const convertOpenAIResponseInputs = async (
items.push({
call_id: message.tool_call_id,
output: outputText,
- type: 'function_call_output',
- } as OpenAI.Responses.ResponseFunctionToolCallOutputItem);
+ type: customToolCallIds.has(message.tool_call_id!)
+ ? 'custom_tool_call_output'
+ : 'function_call_output',
+ } as OpenAI.Responses.ResponseInputItem);
if (imageParts.length > 0) {
const imageContent = (
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
index 9bbb994c593..32851cf3531 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
@@ -93,6 +93,10 @@ import {
recordOpenAIResponsesResponse,
resolveOpenAIResponseWithMetadata,
} from './providerDiagnostics';
+import {
+ convertChatCompletionToolToResponseTool,
+ stripChatCompletionParameters,
+} from './responseTools';
import {
parseStructuredOutputText,
parseStructuredToolArguments,
@@ -1579,10 +1583,18 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
const inputStartAt = Date.now();
- const { messages, reasoning_effort, tools, reasoning, responseMode, max_tokens, ...res } =
- responses?.handlePayload
- ? (responses?.handlePayload(payload, this._options) as ChatStreamPayload)
- : payload;
+ const {
+ messages,
+ reasoning_effort,
+ tools,
+ responsesTools,
+ reasoning,
+ responseMode,
+ max_tokens,
+ ...res
+ } = responses?.handlePayload
+ ? (responses?.handlePayload(payload, this._options) as ChatStreamPayload)
+ : payload;
const requestModel =
this.withMappedRequestModel({ model: res.model }, usageModel).model ?? usageModel;
const reasoningSignatureScope = await this.getSignatureScope(
@@ -1591,12 +1603,6 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
'responses',
);
- // remove penalty params and chat completion specific params
- delete res.apiMode;
- delete res.frequency_penalty;
- delete res.presence_penalty;
- delete res.preserveThinking;
-
const input = await convertOpenAIResponseInputs(messages as any, {
forceImageBase64: chatCompletion?.forceImageBase64,
forceVideoBase64: chatCompletion?.forceVideoBase64,
@@ -1614,7 +1620,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
);
const postPayload = {
- ...res,
+ ...stripChatCompletionParameters(res),
...(reasoning || reasoning_effort
? {
reasoning: {
@@ -1627,7 +1633,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
...(max_tokens && { max_output_tokens: max_tokens }),
store: false,
stream: isStreaming || undefined,
- tools: tools?.map((tool) => this.convertChatCompletionToolToResponseTool(tool)),
+ tools: responsesTools ?? tools?.map(convertChatCompletionToolToResponseTool),
...this.resolvePromptCacheKeyParams(
res.model,
options?.user,
@@ -1748,12 +1754,6 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
);
}
- private convertChatCompletionToolToResponseTool = (
- tool: ChatCompletionTool,
- ): OpenAI.Responses.Tool => {
- return { type: tool.type, ...tool.function } as any;
- };
-
private async generateObjectWithTools(
payload: GenerateObjectPayload,
options?: GenerateObjectOptions,
@@ -1809,7 +1809,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
model,
...this.resolvePromptCacheKeyParams(model, options?.user),
tool_choice: 'required',
- tools: tools!.map((tool) => this.convertChatCompletionToolToResponseTool(tool)),
+ tools: tools!.map(convertChatCompletionToolToResponseTool),
// Responses API replaced `user` with `safety_identifier`; some endpoints reject `user`
safety_identifier: options?.user,
} as any,
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.ts
index c580dcd2605..af6734ddaff 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.ts
@@ -131,10 +131,11 @@ export const transformResponseAPIToStream = (data: OpenAI.Responses.Response) =>
break;
}
/**
- * A completed function call already carries its full arguments. The stream parser
+ * A completed tool call already carries its full arguments/input. The stream parser
* reads them from `output_item.added`, so no argument deltas are needed; dropping
* this item would turn a tool-call-only response into an empty completion.
*/
+ case 'custom_tool_call':
case 'function_call': {
controller.enqueue({
item: output,
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/responseTools.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/responseTools.test.ts
new file mode 100644
index 00000000000..0752316ecc7
--- /dev/null
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/responseTools.test.ts
@@ -0,0 +1,129 @@
+// @vitest-environment node
+import type OpenAI from 'openai';
+import { describe, expect, it, vi } from 'vitest';
+
+import { LobeChatGPTAI } from '../../providers/chatGPT';
+import { createOpenAICompatibleRuntime } from './index';
+
+vi.mock('@lobechat/business-model-bank/model-config', () => ({
+ loadModels: vi.fn().mockResolvedValue([]),
+}));
+
+const tools: OpenAI.Responses.Tool[] = [
+ {
+ type: 'namespace',
+ name: 'functions',
+ description: '',
+ tools: [{ type: 'custom', name: 'exec', format: { type: 'text' } }],
+ },
+];
+const closedStream = () =>
+ new ReadableStream({
+ start(controller) {
+ controller.close();
+ },
+ });
+
+describe('Responses native tool payload', () => {
+ it.each(['gpt-5.6-luna', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-6-astra'])(
+ 'forwards top-level and in-context native tools for %s',
+ async (model) => {
+ const create = vi.fn().mockImplementation(async () => closedStream());
+ const Runtime = createOpenAICompatibleRuntime({
+ provider: 'test',
+ customClient: { createClient: () => ({ responses: { create } }) as unknown as OpenAI },
+ });
+ const runtime = new Runtime({ apiKey: 'test' });
+ const response = await runtime.chat({
+ model,
+ apiMode: 'responses',
+ stream: true,
+ responsesTools: tools,
+ messages: [
+ { role: 'system', content: '', responsesTools: tools },
+ { role: 'user', content: 'Read the file.' },
+ ],
+ });
+ await response.text();
+ expect(create.mock.calls[0][0]).toMatchObject({
+ tools,
+ input: [
+ { type: 'additional_tools', role: 'developer', tools },
+ { role: 'user', content: 'Read the file.' },
+ ],
+ });
+ expect(create.mock.calls[0][0]).not.toHaveProperty('responsesTools');
+ },
+ );
+
+ it('preserves a custom-tool-only response when streaming is disabled', async () => {
+ const input = 'read("probe.txt")\n';
+ const create = vi.fn().mockResolvedValue({
+ id: 'resp-custom',
+ status: 'completed',
+ output: [
+ {
+ id: 'ct-1',
+ type: 'custom_tool_call',
+ call_id: 'call-1',
+ namespace: 'functions',
+ name: 'exec',
+ input,
+ },
+ ],
+ });
+ const Runtime = createOpenAICompatibleRuntime({
+ provider: 'test',
+ customClient: { createClient: () => ({ responses: { create } }) as unknown as OpenAI },
+ });
+ const response = await new Runtime({ apiKey: 'test' }).chat({
+ model: 'gpt-5.6-sol',
+ apiMode: 'responses',
+ stream: false,
+ responsesTools: tools,
+ messages: [{ role: 'user', content: 'Read the file.' }],
+ });
+ const raw = await response.text();
+ const calls = raw
+ .split('\n\n')
+ .filter((block) => block.includes('event: tool_calls'))
+ .flatMap((block) =>
+ JSON.parse(
+ block
+ .split('\n')
+ .find((line) => line.startsWith('data: '))!
+ .slice(6),
+ ),
+ );
+ expect(calls).toEqual([
+ {
+ id: 'call-1',
+ index: 0,
+ namespace: 'functions',
+ type: 'custom',
+ function: { name: 'exec', arguments: input },
+ },
+ ]);
+ expect(create.mock.calls[0][0].stream).toBeUndefined();
+ });
+
+ it('does not prepend an empty tool update to existing Responses Lite tool updates', async () => {
+ const runtime = new LobeChatGPTAI({ apiKey: 'test', chatgptAccountId: 'test' });
+ const create = vi
+ .spyOn(runtime['client'].responses, 'create')
+ .mockResolvedValue(closedStream() as never);
+ const response = await runtime.chat({
+ model: 'gpt-5.6-sol',
+ stream: true,
+ messages: [
+ { role: 'system', content: '', responsesTools: tools },
+ { role: 'user', content: 'Read the file.' },
+ ],
+ });
+ await response.text();
+ const input = create.mock.calls[0][0].input as OpenAI.Responses.ResponseInputItem[];
+ expect(input.filter((item) => item.type === 'additional_tools')).toEqual([
+ { role: 'developer', type: 'additional_tools', tools },
+ ]);
+ });
+});
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/responseTools.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/responseTools.ts
new file mode 100644
index 00000000000..bcf4b326247
--- /dev/null
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/responseTools.ts
@@ -0,0 +1,19 @@
+import type OpenAI from 'openai';
+
+import type { ChatCompletionTool, ChatStreamPayload } from '../../types';
+
+export const convertChatCompletionToolToResponseTool = (
+ tool: ChatCompletionTool,
+): OpenAI.Responses.Tool => ({ type: tool.type, ...tool.function }) as OpenAI.Responses.Tool;
+
+/** Remove Chat Completions-only fields before sending a Responses request. */
+export const stripChatCompletionParameters = (payload: Partial<ChatStreamPayload>) => {
+ const {
+ apiMode: _apiMode,
+ frequency_penalty: _frequency,
+ presence_penalty: _presence,
+ preserveThinking: _thinking,
+ ...rest
+ } = payload;
+ return rest;
+};
diff --git a/packages/model-runtime/src/core/streams/openai/responsesStream.tools.test.ts b/packages/model-runtime/src/core/streams/openai/responsesStream.tools.test.ts
new file mode 100644
index 00000000000..b82038e2142
--- /dev/null
+++ b/packages/model-runtime/src/core/streams/openai/responsesStream.tools.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from 'vitest';
+
+import { createReadableStream } from '../utils';
+import { OpenAIResponsesStream } from './responsesStream';
+
+describe('Responses custom tool streaming', () => {
+ it('keeps interleaved custom/function deltas attached to their own calls', async () => {
+ const stream = OpenAIResponsesStream(
+ createReadableStream([
+ { type: 'response.created', response: { id: 'response-1', status: 'in_progress' } },
+ {
+ type: 'response.output_item.added',
+ output_index: 1,
+ item: {
+ id: 'ct-1',
+ type: 'custom_tool_call',
+ call_id: 'call-1',
+ namespace: 'functions',
+ name: 'exec',
+ input: '',
+ },
+ },
+ {
+ type: 'response.output_item.added',
+ output_index: 2,
+ item: {
+ id: 'fc-1',
+ type: 'function_call',
+ call_id: 'call-2',
+ namespace: 'clock',
+ name: 'now',
+ arguments: '',
+ },
+ },
+ {
+ type: 'response.custom_tool_call_input.delta',
+ output_index: 1,
+ item_id: 'ct-1',
+ delta: 'read(',
+ },
+ {
+ type: 'response.function_call_arguments.delta',
+ output_index: 2,
+ item_id: 'fc-1',
+ delta: '{}',
+ },
+ {
+ type: 'response.custom_tool_call_input.delta',
+ output_index: 1,
+ item_id: 'ct-1',
+ delta: '"probe.txt")',
+ },
+ ]),
+ );
+ const raw = await new Response(stream).text();
+ const calls = raw
+ .split('\n\n')
+ .filter((block) => block.includes('event: tool_calls'))
+ .flatMap((block) =>
+ JSON.parse(
+ block
+ .split('\n')
+ .find((line) => line.startsWith('data: '))!
+ .slice(6),
+ ),
+ );
+ expect(calls.map((call) => [call.id, call.index, call.type, call.function.arguments])).toEqual([
+ ['call-1', 0, 'custom', ''],
+ ['call-2', 1, 'function', ''],
+ ['call-1', 0, 'custom', 'read('],
+ ['call-2', 1, 'function', '{}'],
+ ['call-1', 0, 'custom', '"probe.txt")'],
+ ]);
+ expect(calls[0].namespace).toBe('functions');
+ expect(calls[1].namespace).toBe('clock');
+ });
+});
diff --git a/packages/model-runtime/src/core/streams/openai/responsesStream.ts b/packages/model-runtime/src/core/streams/openai/responsesStream.ts
index 020254afd63..e2c0ac74edf 100644
--- a/packages/model-runtime/src/core/streams/openai/responsesStream.ts
+++ b/packages/model-runtime/src/core/streams/openai/responsesStream.ts
@@ -29,6 +29,10 @@ const toResponsesError = (error: { code?: string | null; message?: string | null
type: AgentRuntimeErrorType.ProviderBizError,
}) satisfies ChatMessageError;
+type ResponsesStreamContext = StreamContext & {
+ responseTools?: Map<number, { id: string; index: number; name: string; namespace?: string }>;
+};
+
const transformOpenAIStream = (
chunk:
| OpenAI.Responses.ResponseStreamEvent
@@ -48,7 +52,7 @@ const transformOpenAIStream = (
item_id: string;
type: 'response.output_text.annotation.added';
},
- streamContext: StreamContext,
+ streamContext: ResponsesStreamContext,
payload?: ChatPayloadForTransformStream,
): StreamProtocolChunk | StreamProtocolChunk[] => {
// handle the first chunk error
@@ -86,6 +90,7 @@ const transformOpenAIStream = (
case 'response.output_item.added': {
switch (chunk.item.type) {
+ case 'custom_tool_call':
case 'function_call': {
streamContext.toolIndex =
typeof streamContext.toolIndex === 'undefined' ? 0 : streamContext.toolIndex + 1;
@@ -94,14 +99,27 @@ const transformOpenAIStream = (
index: streamContext.toolIndex,
name: chunk.item.name,
};
+ const namespace = chunk.item.namespace ? { namespace: chunk.item.namespace } : {};
+ streamContext.responseTools ??= new Map();
+ streamContext.responseTools.set(chunk.output_index, {
+ ...streamContext.tool,
+ ...namespace,
+ });
return {
data: [
{
- function: { arguments: chunk.item.arguments, name: chunk.item.name },
+ function: {
+ arguments:
+ chunk.item.type === 'custom_tool_call'
+ ? chunk.item.input
+ : chunk.item.arguments,
+ name: chunk.item.name,
+ },
+ ...namespace,
id: chunk.item.call_id,
index: streamContext.toolIndex!,
- type: 'function',
+ type: chunk.item.type === 'custom_tool_call' ? 'custom' : 'function',
} satisfies StreamToolCallChunkData,
],
id: streamContext.id,
@@ -113,14 +131,16 @@ const transformOpenAIStream = (
return { data: chunk.item, id: streamContext.id, type: 'data' };
}
+ case 'response.custom_tool_call_input.delta':
case 'response.function_call_arguments.delta': {
+ const tool = streamContext.responseTools?.get(chunk.output_index) ?? streamContext.tool;
return {
data: [
{
- function: { arguments: chunk.delta, name: streamContext.tool?.name },
- id: streamContext.tool?.id,
- index: streamContext.toolIndex!,
- type: 'function',
+ function: { arguments: chunk.delta, name: tool?.name },
+ id: tool?.id,
+ index: tool?.index ?? streamContext.toolIndex!,
+ type: chunk.type === 'response.custom_tool_call_input.delta' ? 'custom' : 'function',
} satisfies StreamToolCallChunkData,
],
id: streamContext.id,
diff --git a/packages/model-runtime/src/providers/chatGPT/index.ts b/packages/model-runtime/src/providers/chatGPT/index.ts
index 6a7a5443f19..ce281d458f7 100644
--- a/packages/model-runtime/src/providers/chatGPT/index.ts
+++ b/packages/model-runtime/src/providers/chatGPT/index.ts
@@ -100,9 +100,7 @@ export const LobeChatGPTAI = createOpenAICompatibleRuntime<ChatGPTClientOptions>
if (!isResponsesLiteModel(subscriptionPayload.model)) {
return {
payload:
- reasoning === undefined
- ? subscriptionPayload
- : { ...subscriptionPayload, reasoning },
+ reasoning === undefined ? subscriptionPayload : { ...subscriptionPayload, reasoning },
};
}
@@ -138,7 +136,11 @@ export const LobeChatGPTAI = createOpenAICompatibleRuntime<ChatGPTClientOptions>
payload: {
...rest,
input: [
- additionalTools as OpenAI.Responses.ResponseInputItem,
+ ...(tools?.length ||
+ !Array.isArray(input) ||
+ !input.some((item) => item.type === 'additional_tools')
+ ? [additionalTools as OpenAI.Responses.ResponseInputItem]
+ : []),
...developerInstructions,
...(Array.isArray(input) ? input : []),
],
diff --git a/packages/model-runtime/src/types/chat.ts b/packages/model-runtime/src/types/chat.ts
index e295949ca2b..0d11f67be6c 100644
--- a/packages/model-runtime/src/types/chat.ts
+++ b/packages/model-runtime/src/types/chat.ts
@@ -4,6 +4,7 @@ import type {
ModelTokensUsage,
ModelUsage,
} from '@lobechat/types';
+import type OpenAI from 'openai';
import type { ModelPricingContext } from './pricing';
import type { ModelRuntimeDiagnostics } from './providerDiagnostics';
@@ -73,6 +74,10 @@ export interface OpenAIChatMessage {
provider?: string;
reasoning?: ModelReasoning;
reasoning_content?: string;
+ /** Native tool output parts, including images and files, for Responses replay. */
+ responsesOutput?: OpenAI.Responses.ResponseCustomToolCallOutput['output'];
+ /** Tools introduced at this position in a Responses conversation. */
+ responsesTools?: OpenAI.Responses.Tool[];
role: LLMRoleType;
tool_call_id?: string;
tool_calls?: MessageToolCall[];
@@ -155,6 +160,8 @@ export interface ChatStreamPayload {
reasoning_effort?: 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';
response_format?: ChatResponseFormat;
responseMode?: 'stream' | 'json';
+ /** Native Responses tools, including namespaces and free-form custom tools. */
+ responsesTools?: OpenAI.Responses.Tool[];
/**
* @title Whether to enable streaming requests
* @default true
diff --git a/packages/model-runtime/src/types/toolsCalling.ts b/packages/model-runtime/src/types/toolsCalling.ts
index 9198f7b62bf..a9b48cbabfa 100644
--- a/packages/model-runtime/src/types/toolsCalling.ts
+++ b/packages/model-runtime/src/types/toolsCalling.ts
@@ -30,9 +30,10 @@ export interface MessageToolCall {
*/
id: string;
+ namespace?: string;
thoughtSignature?: string;
/**
- * The type of the tool. Currently, only `function` is supported.
+ * For custom tools, function.arguments carries the raw input instead of JSON.
*/
type: 'function' | string;
}
@@ -43,6 +44,7 @@ export const MessageToolCallSchema = z.object({
name: z.string(),
}),
id: z.string(),
+ namespace: z.string().optional(),
thoughtSignature: z.string().optional(),
type: z.string(),
});
diff --git a/packages/model-runtime/src/utils/anthropicToolSchema.test.ts b/packages/model-runtime/src/utils/anthropicToolSchema.test.ts
new file mode 100644
index 00000000000..e74ea155ff4
--- /dev/null
+++ b/packages/model-runtime/src/utils/anthropicToolSchema.test.ts
@@ -0,0 +1,129 @@
+/* eslint-disable unicorn/no-thenable -- then is a JSON Schema keyword, not a promise method. */
+import Ajv from 'ajv';
+import Ajv2020 from 'ajv/dist/2020';
+import { describe, expect, it } from 'vitest';
+
+import { buildAnthropicTools } from '../core/contextBuilders/anthropic';
+import { normalizeAnthropicToolSchema } from './anthropicToolSchema';
+
+const ajv = new Ajv({ strict: false });
+
+describe('normalizeAnthropicToolSchema', () => {
+ it('preserves mutually exclusive argument branches, intersections, root not and nested schemas', () => {
+ const schema = {
+ type: 'object',
+ properties: {
+ name: { type: 'string' },
+ arguments: { type: 'object' },
+ id: { type: 'integer' },
+ },
+ additionalProperties: false,
+ oneOf: [{ required: ['name', 'arguments'] }, { required: ['id'] }],
+ anyOf: [{ properties: { name: { enum: ['read', 'write'] } } }, { required: ['id'] }],
+ allOf: [{ not: { required: ['forbidden'] } }],
+ not: { properties: { id: { const: -1 } }, required: ['id'] },
+ };
+ const original = structuredClone(schema);
+ const normalized = normalizeAnthropicToolSchema(schema)!;
+ expect(normalized).not.toHaveProperty('oneOf');
+ expect(normalized).not.toHaveProperty('anyOf');
+ expect(normalized).not.toHaveProperty('allOf');
+ expect(normalized.properties).toEqual(schema.properties);
+ const before = ajv.compile(schema);
+ const after = ajv.compile(normalized);
+ for (const input of [
+ {},
+ { name: 'read' },
+ { name: 'read', arguments: {} },
+ { id: 1 },
+ { id: -1 },
+ { id: 1, name: 'read', arguments: {} },
+ { name: 'other', arguments: {} },
+ { id: 2, extra: true },
+ { id: '1' },
+ ]) {
+ expect(after(input), JSON.stringify(input)).toBe(before(input));
+ }
+ expect(schema).toEqual(original);
+ expect(normalizeAnthropicToolSchema(normalized)).toBe(normalized);
+ });
+
+ it('keeps references to moved constraints and unmoved definitions valid', () => {
+ const schema = {
+ type: 'object',
+ definitions: { text: { type: 'string' } },
+ properties: {
+ name: { $ref: '#/definitions/text' },
+ copy: { $ref: '#/oneOf/0/properties/name' },
+ },
+ oneOf: [
+ { required: ['name'], properties: { name: { enum: ['read'] } } },
+ { required: ['id'] },
+ ],
+ };
+ const normalized = normalizeAnthropicToolSchema(schema)!;
+ const before = ajv.compile(schema);
+ const after = ajv.compile(normalized);
+ for (const value of [
+ { name: 'read', copy: 'read' },
+ { name: 'read', copy: 'write' },
+ { id: 1 },
+ {},
+ ])
+ expect(after(value)).toBe(before(value));
+ expect(normalized.properties).toMatchObject({
+ copy: { $ref: '#/if/oneOf/0/properties/name' },
+ });
+ });
+
+ it('retains evaluated-property annotations and an existing conditional', () => {
+ const schema = {
+ type: 'object',
+ allOf: [{ properties: { path: { type: 'string' } } }],
+ if: { required: ['path'] },
+ then: { properties: { mode: { const: 'read' } } },
+ else: { required: ['missing'] },
+ unevaluatedProperties: false,
+ };
+ const validator = new Ajv2020({ strict: false });
+ const before = validator.compile(schema);
+ const after = validator.compile(normalizeAnthropicToolSchema(schema)!);
+ for (const input of [
+ { path: 'file.txt' },
+ { path: 'file.txt', mode: 'read' },
+ { path: 'file.txt', mode: 'write' },
+ { path: 'file.txt', extra: true },
+ {},
+ ])
+ expect(after(input)).toBe(before(input));
+ });
+
+ it('does not rewrite literal data that happens to contain reference-shaped keys', () => {
+ const value = { $ref: '#/allOf/0' };
+ const schema = {
+ type: 'object',
+ properties: { data: { const: value, default: value, examples: [value] } },
+ allOf: [{ required: ['data'] }],
+ };
+ const normalized = normalizeAnthropicToolSchema(schema)!;
+ expect(normalized.properties).toEqual(schema.properties);
+ expect(ajv.compile(normalized)({ data: value })).toBe(true);
+ });
+
+ it('applies to native Anthropic tools without changing ordinary schemas', () => {
+ const schema = { type: 'object', properties: { path: { type: 'string' } } };
+ expect(normalizeAnthropicToolSchema(schema)).toBe(schema);
+ const tools = buildAnthropicTools([
+ {
+ type: 'function',
+ function: { name: 'use_tool', parameters: { ...schema, oneOf: [{ required: ['path'] }] } },
+ },
+ ]);
+ expect(tools?.[0].input_schema).not.toHaveProperty('oneOf');
+ expect(tools?.[0].input_schema).toMatchObject({
+ if: { oneOf: [{ required: ['path'] }] },
+ then: true,
+ else: false,
+ });
+ });
+});
diff --git a/packages/model-runtime/src/utils/anthropicToolSchema.ts b/packages/model-runtime/src/utils/anthropicToolSchema.ts
new file mode 100644
index 00000000000..40cd873f156
--- /dev/null
+++ b/packages/model-runtime/src/utils/anthropicToolSchema.ts
@@ -0,0 +1,78 @@
+/* eslint-disable unicorn/no-thenable -- then is a JSON Schema keyword, not a promise method. */
+const schemaMaps = new Set([
+ '$defs',
+ 'definitions',
+ 'properties',
+ 'patternProperties',
+ 'dependentSchemas',
+ 'dependencies',
+]);
+const schemaChildren = new Set([
+ 'allOf',
+ 'anyOf',
+ 'oneOf',
+ 'prefixItems',
+ 'items',
+ 'additionalItems',
+ 'additionalProperties',
+ 'unevaluatedProperties',
+ 'unevaluatedItems',
+ 'contains',
+ 'propertyNames',
+ 'not',
+ 'if',
+ 'then',
+ 'else',
+]);
+
+/**
+ * Claude rejects root union/intersection keywords. An equivalent conditional
+ * keeps their validation AND evaluated-property annotations (unlike double not),
+ * without changing the arguments or hiding the root property declarations.
+ */
+export const normalizeAnthropicToolSchema = (
+ schema: Record<string, unknown> | undefined,
+): Record<string, unknown> | undefined => {
+ if (!schema || !['oneOf', 'anyOf', 'allOf'].some((key) => key in schema)) return schema;
+
+ const movedKeys = ['oneOf', 'anyOf', 'allOf', 'if', 'then', 'else'].filter(
+ (key) => key in schema,
+ );
+ const constraints = Object.fromEntries(movedKeys.map((key) => [key, schema[key]]));
+ const root = Object.fromEntries(
+ Object.entries(schema).filter(([key]) => !movedKeys.includes(key)),
+ );
+
+ // Relocate local JSON-pointer references, visiting schema positions only:
+ // values inside const/enum/default/examples are data, even if they contain $ref.
+ const relocateReferences = (value: unknown, isRoot = false): unknown => {
+ if (Array.isArray(value)) return value.map((item) => relocateReferences(item));
+ if (!value || typeof value !== 'object') return value;
+ const record = value as Record<string, unknown>;
+ if (!isRoot && typeof record.$id === 'string') return value;
+ return Object.fromEntries(
+ Object.entries(record).map(([key, child]) => {
+ if ((key === '$ref' || key === '$dynamicRef') && typeof child === 'string') {
+ const target = movedKeys.find(
+ (moved) => child === `#/${moved}` || child.startsWith(`#/${moved}/`),
+ );
+ if (target) return [key, child.replace('#/', '#/if/')];
+ }
+ if (schemaMaps.has(key) && child && typeof child === 'object' && !Array.isArray(child)) {
+ return [
+ key,
+ Object.fromEntries(
+ Object.entries(child).map(([name, nested]) => [name, relocateReferences(nested)]),
+ ),
+ ];
+ }
+ return [key, schemaChildren.has(key) ? relocateReferences(child) : child];
+ }),
+ );
+ };
+
+ return relocateReferences({ ...root, if: constraints, then: true, else: false }, true) as Record<
+ string,
+ unknown
+ >;
+};
diff --git a/packages/openapi/src/services/heterogeneous-direct.request.ts b/packages/openapi/src/services/heterogeneous-direct.request.ts
new file mode 100644
index 00000000000..04b9a069842
--- /dev/null
+++ b/packages/openapi/src/services/heterogeneous-direct.request.ts
@@ -0,0 +1,326 @@
+import type {
+ ChatStreamPayload,
+ OpenAIChatMessage,
+ UserMessageContentPart,
+} from '@lobechat/model-runtime';
+import { isRecord } from '@lobechat/utils/object';
+import type OpenAI from 'openai';
+
+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) => {
+ 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) => {
+ if (!isRecord(part) || !['image', 'input_image'].includes(String(part.type))) return [];
+ if (typeof part.image_url === 'string') {
+ return [{ image_url: { url: part.image_url }, type: 'image_url' as const }];
+ }
+ const source = part.source;
+ if (!isRecord(source)) return [];
+ const url =
+ source.type === 'base64' && typeof source.data === 'string'
+ ? `data:${String(source.media_type || 'image/png')};base64,${source.data}`
+ : typeof source.url === 'string'
+ ? source.url
+ : undefined;
+ return url ? [{ image_url: { url }, type: 'image_url' as const }] : [];
+ });
+};
+
+const contentWithImages = (
+ content: unknown,
+ transform = (text: string) => text,
+): OpenAIChatMessage['content'] => {
+ const images = imageParts(content);
+ const text = transform(textFromParts(content));
+ return images.length > 0 ? [...(text ? [{ text, type: 'text' as const }] : []), ...images] : text;
+};
+
+const anthropicThinkingParts = (content: unknown): UserMessageContentPart[] => {
+ if (!Array.isArray(content)) return [];
+ return content.flatMap<UserMessageContentPart>((part) => {
+ if (!isRecord(part)) return [];
+ if (
+ part.type === 'thinking' &&
+ typeof part.thinking === 'string' &&
+ typeof part.signature === 'string'
+ ) {
+ return [{ signature: part.signature, thinking: part.thinking, type: 'thinking' as const }];
+ }
+ if (part.type === 'redacted_thinking' && typeof part.data === 'string') {
+ return [{ data: part.data, type: 'redacted_thinking' as const }];
+ }
+ return [];
+ });
+};
+
+const contentWithAnthropicThinking = (content: unknown): OpenAIChatMessage['content'] => {
+ const thinking = anthropicThinkingParts(content);
+ if (thinking.length === 0) return contentWithImages(content);
+ const visible = contentWithImages(content);
+ return [
+ ...thinking,
+ ...(typeof visible === 'string'
+ ? visible
+ ? [{ text: visible, type: 'text' as const }]
+ : []
+ : visible),
+ ];
+};
+
+interface NormalizeAnthropicRequestOptions {
+ unwrapSystemReminders?: boolean;
+}
+
+export const normalizeAnthropicRequest = (
+ request: Record<string, unknown>,
+ model: string,
+ options?: NormalizeAnthropicRequestOptions,
+) => {
+ const messages: OpenAIChatMessage[] = [];
+ 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;
+ const content = rawMessage.content;
+ const role = rawMessage.role as 'assistant' | 'user';
+ const toolCalls = Array.isArray(content)
+ ? content.flatMap((part) =>
+ isRecord(part) &&
+ part.type === 'tool_use' &&
+ typeof part.id === 'string' &&
+ typeof part.name === 'string'
+ ? [
+ {
+ function: { arguments: JSON.stringify(part.input ?? {}), name: part.name },
+ id: part.id,
+ type: 'function' as const,
+ },
+ ]
+ : [],
+ )
+ : [];
+ const toolResults = Array.isArray(content)
+ ? content.filter((part) => isRecord(part) && part.type === 'tool_result')
+ : [];
+ if (toolResults.length > 0) {
+ for (const result of toolResults) {
+ messages.push({
+ content: contentWithImages(result.content),
+ role: 'tool',
+ tool_call_id: String(result.tool_use_id),
+ });
+ }
+ 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, transformUserText);
+ const hasAnthropicThinking =
+ Array.isArray(normalizedContent) &&
+ normalizedContent.some(
+ (part) => part.type === 'thinking' || part.type === 'redacted_thinking',
+ );
+ messages.push({
+ content: normalizedContent,
+ ...(hasAnthropicThinking ? { provider: 'anthropic' } : {}),
+ role,
+ ...(toolCalls.length ? { tool_calls: toolCalls } : {}),
+ });
+ }
+
+ const tools = Array.isArray(request.tools)
+ ? request.tools.flatMap((tool) =>
+ isRecord(tool) && typeof tool.name === 'string'
+ ? [
+ {
+ function: {
+ description: typeof tool.description === 'string' ? tool.description : undefined,
+ name: tool.name,
+ parameters: isRecord(tool.input_schema) ? tool.input_schema : {},
+ },
+ type: 'function' as const,
+ },
+ ]
+ : [],
+ )
+ : undefined;
+ const thinking = isRecord(request.thinking) ? request.thinking : undefined;
+ return {
+ max_tokens: typeof request.max_tokens === 'number' ? request.max_tokens : undefined,
+ messages,
+ model,
+ stream: true,
+ temperature: typeof request.temperature === 'number' ? request.temperature : undefined,
+ thinking: thinking as ChatStreamPayload['thinking'],
+ tools,
+ top_p: typeof request.top_p === 'number' ? request.top_p : undefined,
+ } satisfies ChatStreamPayload;
+};
+
+export const normalizeResponsesRequest = (request: Record<string, unknown>, model: string) => {
+ const messages: OpenAIChatMessage[] = [];
+ let pendingReasoningItems: NonNullable<OpenAIChatMessage['reasoning']>['responseItems'] = [];
+ const takePendingReasoning = () => {
+ if (!pendingReasoningItems?.length) return {};
+ const reasoning = { reasoning: { responseItems: pendingReasoningItems } };
+ pendingReasoningItems = [];
+ return reasoning;
+ };
+ if (typeof request.instructions === 'string') {
+ messages.push({ content: request.instructions, role: 'system' });
+ }
+ if (typeof request.input === 'string') {
+ messages.push({ content: request.input, role: 'user' });
+ } else if (Array.isArray(request.input)) {
+ for (const item of request.input) {
+ if (!isRecord(item)) continue;
+ if (item.type === 'additional_tools' && Array.isArray(item.tools)) {
+ messages.push({
+ content: '',
+ role: 'system',
+ responsesTools: item.tools as OpenAI.Responses.Tool[],
+ });
+ } else if (
+ item.type === 'reasoning' &&
+ typeof item.id === 'string' &&
+ Array.isArray(item.summary)
+ ) {
+ pendingReasoningItems?.push(
+ item as unknown as NonNullable<
+ NonNullable<OpenAIChatMessage['reasoning']>['responseItems']
+ >[number],
+ );
+ } else if (
+ ['function_call', 'custom_tool_call'].includes(String(item.type)) &&
+ typeof item.call_id === 'string'
+ ) {
+ const toolCall = {
+ function: {
+ arguments: String(
+ (item.type === 'custom_tool_call' ? item.input : item.arguments) ?? '',
+ ),
+ name: String(item.name || ''),
+ },
+ id: item.call_id,
+ ...(typeof item.namespace === 'string' ? { namespace: item.namespace } : {}),
+ type: item.type === 'custom_tool_call' ? 'custom' : 'function',
+ };
+ const previousMessage = messages.at(-1);
+
+ // Responses history records every parallel call before their outputs.
+ // Chat Completions requires those calls in one assistant message, followed
+ // by the contiguous batch of tool-result messages.
+ if (
+ !pendingReasoningItems?.length &&
+ previousMessage?.role === 'assistant' &&
+ previousMessage.tool_calls?.length
+ ) {
+ previousMessage.tool_calls.push(toolCall);
+ } else {
+ messages.push({
+ content: '',
+ role: 'assistant',
+ ...takePendingReasoning(),
+ tool_calls: [toolCall],
+ });
+ }
+ } else if (
+ ['function_call_output', 'custom_tool_call_output'].includes(String(item.type)) &&
+ typeof item.call_id === 'string'
+ ) {
+ messages.push({
+ content: contentWithImages(item.output),
+ ...(Array.isArray(item.output)
+ ? {
+ responsesOutput:
+ item.output as OpenAI.Responses.ResponseCustomToolCallOutput['output'],
+ }
+ : {}),
+ role: 'tool',
+ tool_call_id: item.call_id,
+ });
+ } else if (
+ (item.type === undefined || item.type === 'message') &&
+ ['assistant', 'developer', 'system', 'user'].includes(String(item.role))
+ ) {
+ messages.push({
+ content: contentWithImages(item.content),
+ role: item.role === 'developer' ? 'system' : (item.role as OpenAIChatMessage['role']),
+ ...(item.role === 'assistant' ? takePendingReasoning() : {}),
+ });
+ }
+ }
+ }
+ if (pendingReasoningItems?.length) {
+ messages.push({ content: '', role: 'assistant', ...takePendingReasoning() });
+ }
+ const tools = Array.isArray(request.tools)
+ ? request.tools.flatMap((tool) =>
+ isRecord(tool) && tool.type === 'function' && typeof tool.name === 'string'
+ ? [
+ {
+ function: {
+ description: typeof tool.description === 'string' ? tool.description : undefined,
+ name: tool.name,
+ parameters: isRecord(tool.parameters) ? tool.parameters : {},
+ },
+ type: 'function' as const,
+ },
+ ]
+ : [],
+ )
+ : undefined;
+ return {
+ max_tokens:
+ typeof request.max_output_tokens === 'number' ? request.max_output_tokens : undefined,
+ messages,
+ model,
+ reasoning: isRecord(request.reasoning) ? request.reasoning : undefined,
+ responsesTools:
+ Array.isArray(request.tools) &&
+ request.tools.some(
+ (tool) => isRecord(tool) && ['custom', 'namespace'].includes(String(tool.type)),
+ )
+ ? (request.tools as OpenAI.Responses.Tool[])
+ : undefined,
+ stream: true,
+ temperature: typeof request.temperature === 'number' ? request.temperature : undefined,
+ tools,
+ top_p: typeof request.top_p === 'number' ? request.top_p : undefined,
+ } satisfies ChatStreamPayload;
+};
diff --git a/packages/openapi/src/services/heterogeneous-direct.responses.ts b/packages/openapi/src/services/heterogeneous-direct.responses.ts
new file mode 100644
index 00000000000..b455e2f2a06
--- /dev/null
+++ b/packages/openapi/src/services/heterogeneous-direct.responses.ts
@@ -0,0 +1,384 @@
+import { randomUUID } from 'node:crypto';
+
+import { isRecord } from '@lobechat/utils/object';
+
+import type { BaseStreamEvent, ResponseUsage } from '../types/responses.type';
+import {
+ nonNegativeNumber,
+ parseProtocolStream,
+ type ProtocolEvent,
+ sse,
+} from './heterogeneous-direct.stream';
+
+export const encodeResponsesStream = (source: ReadableStream<Uint8Array>, model: string) => {
+ const responseId = `resp_${randomUUID().replaceAll('-', '')}`;
+ let finalized = false;
+ let nextOutputIndex = 0;
+ const outputItems: unknown[] = [];
+ let reasoningItemId: string | undefined;
+ let reasoningOutputIndex: number | undefined;
+ let reasoningText = '';
+ let sequenceNumber = 0;
+ let stopReason: unknown;
+ let textOutputIndex: number | undefined;
+ let outputText = '';
+ let usage: ResponseUsage | undefined;
+ const toolItems = new Map<
+ number,
+ {
+ arguments: string;
+ callId: string;
+ id: string;
+ name: string;
+ namespace?: string;
+ outputIndex: number;
+ type: 'custom' | 'function';
+ }
+ >();
+ const response = {
+ created_at: Math.floor(Date.now() / 1000),
+ error: null,
+ id: responseId,
+ incomplete_details: null,
+ instructions: null,
+ model,
+ object: 'response',
+ output: [],
+ status: 'in_progress',
+ };
+ const responseSse = (
+ event: BaseStreamEvent['type'],
+ data: Omit<BaseStreamEvent, 'sequence_number'> & Record<string, unknown>,
+ ) => {
+ const sequencedData = {
+ ...data,
+ sequence_number: sequenceNumber++,
+ } satisfies BaseStreamEvent;
+ return sse(event, sequencedData);
+ };
+ const completeReasoning = (
+ controller: TransformStreamDefaultController<string>,
+ responseItem?: unknown,
+ ) => {
+ if (reasoningOutputIndex === undefined) {
+ if (responseItem === undefined) return;
+ const outputIndex = nextOutputIndex++;
+ const item = isRecord(responseItem) ? { ...responseItem, status: 'completed' } : responseItem;
+ outputItems[outputIndex] = item;
+ controller.enqueue(
+ responseSse('response.output_item.added', {
+ item: isRecord(responseItem) ? { ...responseItem, status: 'in_progress' } : responseItem,
+ output_index: outputIndex,
+ type: 'response.output_item.added',
+ }),
+ );
+ controller.enqueue(
+ responseSse('response.output_item.done', {
+ item,
+ output_index: outputIndex,
+ type: 'response.output_item.done',
+ }),
+ );
+ return;
+ }
+
+ const outputIndex = reasoningOutputIndex;
+ const itemId =
+ isRecord(responseItem) && typeof responseItem.id === 'string'
+ ? responseItem.id
+ : reasoningItemId || `rs_${responseId}`;
+ const item = isRecord(responseItem)
+ ? { ...responseItem, status: 'completed' }
+ : {
+ id: itemId,
+ status: 'completed',
+ summary: [{ text: reasoningText, type: 'summary_text' }],
+ type: 'reasoning',
+ };
+ outputItems[outputIndex] = item;
+ controller.enqueue(
+ responseSse('response.reasoning_summary_text.done', {
+ item_id: itemId,
+ output_index: outputIndex,
+ summary_index: 0,
+ text: reasoningText,
+ type: 'response.reasoning_summary_text.done',
+ }),
+ );
+ controller.enqueue(
+ responseSse('response.output_item.done', {
+ item,
+ output_index: outputIndex,
+ type: 'response.output_item.done',
+ }),
+ );
+ reasoningItemId = undefined;
+ reasoningOutputIndex = undefined;
+ reasoningText = '';
+ };
+ const finalize = (controller: TransformStreamDefaultController<string>) => {
+ if (finalized) return;
+ finalized = true;
+ completeReasoning(controller);
+ if (textOutputIndex !== undefined) {
+ const item = {
+ content: [{ annotations: [], text: outputText, type: 'output_text' }],
+ id: `msg_${responseId}`,
+ role: 'assistant',
+ status: 'completed',
+ type: 'message',
+ };
+ outputItems[textOutputIndex] = item;
+ controller.enqueue(
+ responseSse('response.output_text.done', {
+ content_index: 0,
+ item_id: `msg_${responseId}`,
+ output_index: textOutputIndex,
+ text: outputText,
+ type: 'response.output_text.done',
+ }),
+ );
+ controller.enqueue(
+ responseSse('response.content_part.done', {
+ content_index: 0,
+ item_id: `msg_${responseId}`,
+ output_index: textOutputIndex,
+ part: { annotations: [], text: outputText, type: 'output_text' },
+ type: 'response.content_part.done',
+ }),
+ );
+ controller.enqueue(
+ responseSse('response.output_item.done', {
+ item,
+ output_index: textOutputIndex,
+ type: 'response.output_item.done',
+ }),
+ );
+ }
+ for (const tool of toolItems.values()) {
+ const item = {
+ ...(tool.type === 'custom' ? { input: tool.arguments } : { arguments: tool.arguments }),
+ ...(tool.namespace ? { namespace: tool.namespace } : {}),
+ call_id: tool.callId,
+ id: tool.id,
+ name: tool.name,
+ status: 'completed',
+ type: tool.type === 'custom' ? 'custom_tool_call' : 'function_call',
+ };
+ outputItems[tool.outputIndex] = item;
+ const doneType =
+ tool.type === 'custom'
+ ? 'response.custom_tool_call_input.done'
+ : 'response.function_call_arguments.done';
+ controller.enqueue(
+ responseSse(doneType, {
+ ...(tool.type === 'custom' ? { input: tool.arguments } : { arguments: tool.arguments }),
+ item_id: tool.id,
+ output_index: tool.outputIndex,
+ type: doneType,
+ }),
+ );
+ controller.enqueue(
+ responseSse('response.output_item.done', {
+ item,
+ output_index: tool.outputIndex,
+ type: 'response.output_item.done',
+ }),
+ );
+ }
+ const incomplete = stopReason === 'max_tokens';
+ const type = incomplete ? 'response.incomplete' : 'response.completed';
+ controller.enqueue(
+ responseSse(type, {
+ response: {
+ ...response,
+ incomplete_details: incomplete ? { reason: 'max_output_tokens' } : null,
+ output: outputItems.filter(Boolean),
+ status: incomplete ? 'incomplete' : 'completed',
+ usage,
+ },
+ type,
+ }),
+ );
+ controller.enqueue('data: [DONE]\n\n');
+ };
+ return parseProtocolStream(source)
+ .pipeThrough(
+ new TransformStream<ProtocolEvent, string>({
+ start(controller) {
+ controller.enqueue(
+ responseSse('response.created', { response, type: 'response.created' }),
+ );
+ },
+ transform(event, controller) {
+ if (finalized) return;
+ const part =
+ (event.type === 'content_part' || event.type === 'reasoning_part') &&
+ isRecord(event.data) &&
+ event.data.partType === 'text'
+ ? event.data
+ : undefined;
+ const content =
+ event.type === 'text' || event.type === 'reasoning'
+ ? typeof event.data === 'string'
+ ? event.data
+ : undefined
+ : typeof part?.content === 'string'
+ ? part.content
+ : undefined;
+ const isReasoning = event.type === 'reasoning' || event.type === 'reasoning_part';
+ if (content && !isReasoning) {
+ outputText += content;
+ if (textOutputIndex === undefined) {
+ textOutputIndex = nextOutputIndex++;
+ controller.enqueue(
+ responseSse('response.output_item.added', {
+ item: {
+ content: [],
+ id: `msg_${responseId}`,
+ role: 'assistant',
+ status: 'in_progress',
+ type: 'message',
+ },
+ output_index: textOutputIndex,
+ type: 'response.output_item.added',
+ }),
+ );
+ controller.enqueue(
+ responseSse('response.content_part.added', {
+ content_index: 0,
+ item_id: `msg_${responseId}`,
+ output_index: textOutputIndex,
+ part: { annotations: [], text: '', type: 'output_text' },
+ type: 'response.content_part.added',
+ }),
+ );
+ }
+ controller.enqueue(
+ responseSse('response.output_text.delta', {
+ content_index: 0,
+ delta: content,
+ item_id: `msg_${responseId}`,
+ output_index: textOutputIndex,
+ type: 'response.output_text.delta',
+ }),
+ );
+ } else if (content && isReasoning) {
+ reasoningText += content;
+ if (reasoningOutputIndex === undefined) {
+ reasoningItemId = event.id || `rs_${responseId}`;
+ reasoningOutputIndex = nextOutputIndex++;
+ controller.enqueue(
+ responseSse('response.output_item.added', {
+ item: {
+ id: reasoningItemId,
+ status: 'in_progress',
+ summary: [],
+ type: 'reasoning',
+ },
+ output_index: reasoningOutputIndex,
+ type: 'response.output_item.added',
+ }),
+ );
+ }
+ controller.enqueue(
+ responseSse('response.reasoning_summary_text.delta', {
+ delta: content,
+ item_id: reasoningItemId,
+ output_index: reasoningOutputIndex,
+ summary_index: 0,
+ type: 'response.reasoning_summary_text.delta',
+ }),
+ );
+ } else if (event.type === 'reasoning_response_item') {
+ completeReasoning(controller, event.data);
+ } else if (event.type === 'tool_calls' && Array.isArray(event.data)) {
+ for (const chunk of event.data) {
+ if (!isRecord(chunk) || typeof chunk.index !== 'number') continue;
+ const fn = isRecord(chunk.function) ? chunk.function : {};
+ let tool = toolItems.get(chunk.index);
+ if (!tool) {
+ tool = {
+ arguments: '',
+ callId: String(chunk.id || `call_${randomUUID()}`),
+ id: `fc_${randomUUID()}`,
+ name: String(fn.name || ''),
+ namespace: typeof chunk.namespace === 'string' ? chunk.namespace : undefined,
+ outputIndex: nextOutputIndex++,
+ type: chunk.type === 'custom' ? 'custom' : 'function',
+ };
+ toolItems.set(chunk.index, tool);
+ controller.enqueue(
+ responseSse('response.output_item.added', {
+ item: {
+ ...(tool.type === 'custom' ? { input: '' } : { arguments: '' }),
+ ...(tool.namespace ? { namespace: tool.namespace } : {}),
+ call_id: tool.callId,
+ id: tool.id,
+ name: tool.name,
+ status: 'in_progress',
+ type: tool.type === 'custom' ? 'custom_tool_call' : 'function_call',
+ },
+ output_index: tool.outputIndex,
+ type: 'response.output_item.added',
+ }),
+ );
+ }
+ if (typeof fn.arguments === 'string') {
+ tool.arguments += fn.arguments;
+ const deltaType =
+ tool.type === 'custom'
+ ? 'response.custom_tool_call_input.delta'
+ : 'response.function_call_arguments.delta';
+ controller.enqueue(
+ responseSse(deltaType, {
+ delta: fn.arguments,
+ item_id: tool.id,
+ output_index: tool.outputIndex,
+ type: deltaType,
+ }),
+ );
+ }
+ }
+ } else if (event.type === 'usage' && isRecord(event.data)) {
+ const inputTokens = nonNegativeNumber(event.data.totalInputTokens) ?? 0;
+ const outputTokens = nonNegativeNumber(event.data.totalOutputTokens) ?? 0;
+ usage = {
+ input_tokens: inputTokens,
+ input_tokens_details: {
+ cached_tokens: nonNegativeNumber(event.data.inputCachedTokens) ?? 0,
+ },
+ output_tokens: outputTokens,
+ output_tokens_details: {
+ reasoning_tokens: nonNegativeNumber(event.data.outputReasoningTokens) ?? 0,
+ },
+ total_tokens: inputTokens + outputTokens,
+ };
+ } else if (event.type === 'stop') {
+ if (stopReason === undefined && event.data) stopReason = event.data;
+ } else if (event.type === 'error') {
+ const message = isRecord(event.data)
+ ? String(event.data.message || 'Model request failed')
+ : String(event.data);
+ finalized = true;
+ controller.enqueue(
+ responseSse('response.failed', {
+ response: {
+ ...response,
+ error: { code: 'server_error', message },
+ output: outputItems.filter(Boolean),
+ status: 'failed',
+ },
+ type: 'response.failed',
+ }),
+ );
+ controller.enqueue('data: [DONE]\n\n');
+ }
+ },
+ flush(controller) {
+ finalize(controller);
+ },
+ }),
+ )
+ .pipeThrough(new TextEncoderStream());
+};
diff --git a/packages/openapi/src/services/heterogeneous-direct.service.tools.test.ts b/packages/openapi/src/services/heterogeneous-direct.service.tools.test.ts
new file mode 100644
index 00000000000..df2b6d2fee4
--- /dev/null
+++ b/packages/openapi/src/services/heterogeneous-direct.service.tools.test.ts
@@ -0,0 +1,192 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ initModelRuntimeFromServerConfig,
+ resolveServerDefaultHeterogeneousModel,
+} from '@/server/modules/ModelRuntime';
+
+import {
+ encodeResponsesStream,
+ invokeServerDefaultModel,
+ normalizeResponsesRequest,
+} from './heterogeneous-direct.service';
+
+vi.mock('@/server/modules/ModelRuntime', () => ({
+ initModelRuntimeFromServerConfig: vi.fn(),
+ resolveServerDefaultHeterogeneousModel: vi.fn(),
+}));
+
+const protocolStream = (events: Array<{ data: unknown; id?: string; type: string }>) => {
+ const encoder = new TextEncoder();
+ return new ReadableStream<Uint8Array>({
+ start(controller) {
+ for (const event of events) {
+ controller.enqueue(
+ encoder.encode(
+ `${event.id ? `id: ${event.id}\n` : ''}event: ${event.type}\ndata: ${JSON.stringify(event.data)}\n\n`,
+ ),
+ );
+ }
+ controller.close();
+ },
+ });
+};
+
+const RESPONSES_STREAM_MODEL = 'lobehub/gpt-5.4';
+
+const readText = async (stream: ReadableStream<Uint8Array>) => new Response(stream).text();
+
+const responsesSse = (source: ReadableStream<Uint8Array>) =>
+ encodeResponsesStream(source, RESPONSES_STREAM_MODEL);
+
+const parseSseEvents = (output: string) =>
+ output
+ .split('\n\n')
+ .filter(Boolean)
+ .map((block) => {
+ const lines = block.split('\n');
+ const data = lines.find((line) => line.startsWith('data: '))?.slice(6);
+ const type = lines.find((line) => line.startsWith('event: '))?.slice(7);
+ return { data: data === '[DONE]' ? data : JSON.parse(data || 'null'), type };
+ });
+
+describe('heterogeneous direct tool protocols', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+ it('retains dynamic namespaced tools and custom tool history for Responses', () => {
+ const tool = { name: 'exec', type: 'custom', format: { type: 'text' } };
+ const tools = [{ name: 'functions', description: '', type: 'namespace', tools: [tool] }];
+ const payload = normalizeResponsesRequest(
+ {
+ input: [
+ { type: 'additional_tools', role: 'developer', tools },
+ {
+ type: 'custom_tool_call',
+ call_id: 'call-read',
+ name: 'exec',
+ namespace: 'functions',
+ input: 'read("probe.txt")',
+ },
+ { type: 'custom_tool_call_output', call_id: 'call-read', output: 'fixture contents' },
+ { type: 'message', role: 'user', content: 'Repeat the contents.' },
+ ],
+ tools,
+ },
+ 'gpt-5.6-sol',
+ );
+
+ expect(payload.responsesTools).toEqual(tools);
+ expect(payload.messages[0].responsesTools).toEqual(tools);
+ expect(payload.messages[1].tool_calls).toEqual([
+ {
+ id: 'call-read',
+ type: 'custom',
+ namespace: 'functions',
+ function: { name: 'exec', arguments: 'read("probe.txt")' },
+ },
+ ]);
+ expect(payload.messages[2]).toMatchObject({
+ role: 'tool',
+ tool_call_id: 'call-read',
+ content: 'fixture contents',
+ });
+ });
+
+ it('retains text-block tool outputs instead of stringifying the array', () => {
+ const payload = normalizeResponsesRequest(
+ {
+ input: [
+ {
+ type: 'custom_tool_call_output',
+ call_id: 'custom-1',
+ output: [
+ { type: 'input_text', text: 'Tool output:\n' },
+ { type: 'input_text', text: 'file contents' },
+ ],
+ },
+ {
+ type: 'function_call_output',
+ call_id: 'function-1',
+ output: [{ type: 'input_text', text: 'function contents' }],
+ },
+ ],
+ },
+ 'gpt-5.6-sol',
+ );
+ expect(payload.messages.map((message) => message.content)).toEqual([
+ 'Tool output:\nfile contents',
+ 'function contents',
+ ]);
+ });
+
+ it('encodes custom tools with raw input, namespace and stable call IDs', async () => {
+ const output = parseSseEvents(
+ await readText(
+ responsesSse(
+ protocolStream([
+ {
+ type: 'tool_calls',
+ data: [
+ {
+ index: 0,
+ id: 'call-read',
+ type: 'custom',
+ namespace: 'functions',
+ function: { name: 'exec', arguments: 'read(' },
+ },
+ ],
+ },
+ {
+ type: 'tool_calls',
+ data: [{ index: 0, type: 'custom', function: { arguments: '"probe.txt")' } }],
+ },
+ { type: 'stop', data: 'stop' },
+ ]),
+ ),
+ ),
+ );
+ expect(output.find((e) => e.type === 'response.custom_tool_call_input.done')?.data.input).toBe(
+ 'read("probe.txt")',
+ );
+ expect(output.find((e) => e.type === 'response.completed')?.data.response.output).toEqual([
+ expect.objectContaining({
+ type: 'custom_tool_call',
+ namespace: 'functions',
+ name: 'exec',
+ call_id: 'call-read',
+ input: 'read("probe.txt")',
+ }),
+ ]);
+ });
+
+ it('adapts root tool combinators before invoking a Claude deployment', async () => {
+ const chat = vi.fn().mockResolvedValue(new Response('stream'));
+ vi.mocked(resolveServerDefaultHeterogeneousModel).mockResolvedValue({
+ model: 'claude-sonnet-4-6',
+ provider: 'lobehub',
+ supportsAdaptiveThinking: false,
+ });
+ vi.mocked(initModelRuntimeFromServerConfig).mockResolvedValue({ chat } as any);
+ const schema = {
+ type: 'object',
+ properties: { path: { type: 'string' }, text: { type: 'string' } },
+ oneOf: [{ required: ['path'] }, { required: ['text'] }],
+ };
+ const payload = normalizeResponsesRequest(
+ { input: 'Read the file.', tools: [{ type: 'function', name: 'read', parameters: schema }] },
+ 'lobehub-default',
+ );
+ await invokeServerDefaultModel({
+ agentType: 'grok-build',
+ model: 'claude-sonnet-4-6',
+ payload,
+ signal: new AbortController().signal,
+ userId: 'user-1',
+ });
+ const parameters = chat.mock.calls[0][0].tools[0].function.parameters;
+ expect(parameters).not.toHaveProperty('oneOf');
+ expect(parameters.if.oneOf).toEqual(schema.oneOf);
+ expect(payload.tools?.[0].function.parameters).toEqual(schema);
+ });
+});
diff --git a/packages/openapi/src/services/heterogeneous-direct.service.ts b/packages/openapi/src/services/heterogeneous-direct.service.ts
index f90131cad0a..5fbde49d228 100644
--- a/packages/openapi/src/services/heterogeneous-direct.service.ts
+++ b/packages/openapi/src/services/heterogeneous-direct.service.ts
@@ -1,16 +1,12 @@
-import { randomUUID } from 'node:crypto';
-
-import type {
- ChatStreamPayload,
- OpenAIChatMessage,
- UserMessageContentPart,
-} from '@lobechat/model-runtime';
+import type { ChatStreamPayload } from '@lobechat/model-runtime';
import {
collectStatusCodes,
getErrorCodeSpec,
refineErrorCode,
} from '@lobechat/model-runtime/errors';
+import { parseClaudeModelId } from '@lobechat/model-runtime/providers/anthropic/modelId';
import { isResponsesAPIModel } from '@lobechat/model-runtime/providers/openai/modelId';
+import { normalizeAnthropicToolSchema } from '@lobechat/model-runtime/utils/anthropicToolSchema';
import type { CodexReasoningEffort } from '@lobechat/types';
import {
AgentRuntimeErrorType,
@@ -27,915 +23,14 @@ import {
resolveServerDefaultHeterogeneousModel,
} from '@/server/modules/ModelRuntime';
-import type { BaseStreamEvent, ResponseUsage } from '../types/responses.type';
-
export const SERVER_DEFAULT_MODEL_ALIAS = SERVER_DEFAULT_HETEROGENEOUS_MODEL_ALIAS;
-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) => {
- 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) => {
- if (!isRecord(part) || !['image', 'input_image'].includes(String(part.type))) return [];
- if (typeof part.image_url === 'string') {
- return [{ image_url: { url: part.image_url }, type: 'image_url' as const }];
- }
- const source = part.source;
- if (!isRecord(source)) return [];
- const url =
- source.type === 'base64' && typeof source.data === 'string'
- ? `data:${String(source.media_type || 'image/png')};base64,${source.data}`
- : typeof source.url === 'string'
- ? source.url
- : undefined;
- return url ? [{ image_url: { url }, type: 'image_url' as const }] : [];
- });
-};
-
-const contentWithImages = (
- content: unknown,
- transform = (text: string) => text,
-): OpenAIChatMessage['content'] => {
- const images = imageParts(content);
- const text = transform(textFromParts(content));
- return images.length > 0 ? [...(text ? [{ text, type: 'text' as const }] : []), ...images] : text;
-};
-
-const anthropicThinkingParts = (content: unknown): UserMessageContentPart[] => {
- if (!Array.isArray(content)) return [];
- return content.flatMap<UserMessageContentPart>((part) => {
- if (!isRecord(part)) return [];
- if (
- part.type === 'thinking' &&
- typeof part.thinking === 'string' &&
- typeof part.signature === 'string'
- ) {
- return [{ signature: part.signature, thinking: part.thinking, type: 'thinking' as const }];
- }
- if (part.type === 'redacted_thinking' && typeof part.data === 'string') {
- return [{ data: part.data, type: 'redacted_thinking' as const }];
- }
- return [];
- });
-};
-
-const contentWithAnthropicThinking = (content: unknown): OpenAIChatMessage['content'] => {
- const thinking = anthropicThinkingParts(content);
- if (thinking.length === 0) return contentWithImages(content);
- const visible = contentWithImages(content);
- return [
- ...thinking,
- ...(typeof visible === 'string'
- ? visible
- ? [{ text: visible, type: 'text' as const }]
- : []
- : visible),
- ];
-};
-
-interface NormalizeAnthropicRequestOptions {
- unwrapSystemReminders?: boolean;
-}
-
-export const normalizeAnthropicRequest = (
- request: Record<string, unknown>,
- model: string,
- options?: NormalizeAnthropicRequestOptions,
-) => {
- const messages: OpenAIChatMessage[] = [];
- 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;
- const content = rawMessage.content;
- const role = rawMessage.role as 'assistant' | 'user';
- const toolCalls = Array.isArray(content)
- ? content.flatMap((part) =>
- isRecord(part) &&
- part.type === 'tool_use' &&
- typeof part.id === 'string' &&
- typeof part.name === 'string'
- ? [
- {
- function: { arguments: JSON.stringify(part.input ?? {}), name: part.name },
- id: part.id,
- type: 'function' as const,
- },
- ]
- : [],
- )
- : [];
- const toolResults = Array.isArray(content)
- ? content.filter((part) => isRecord(part) && part.type === 'tool_result')
- : [];
- if (toolResults.length > 0) {
- for (const result of toolResults) {
- messages.push({
- content: contentWithImages(result.content),
- role: 'tool',
- tool_call_id: String(result.tool_use_id),
- });
- }
- 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, transformUserText);
- const hasAnthropicThinking =
- Array.isArray(normalizedContent) &&
- normalizedContent.some(
- (part) => part.type === 'thinking' || part.type === 'redacted_thinking',
- );
- messages.push({
- content: normalizedContent,
- ...(hasAnthropicThinking ? { provider: 'anthropic' } : {}),
- role,
- ...(toolCalls.length ? { tool_calls: toolCalls } : {}),
- });
- }
-
- const tools = Array.isArray(request.tools)
- ? request.tools.flatMap((tool) =>
- isRecord(tool) && typeof tool.name === 'string'
- ? [
- {
- function: {
- description: typeof tool.description === 'string' ? tool.description : undefined,
- name: tool.name,
- parameters: isRecord(tool.input_schema) ? tool.input_schema : {},
- },
- type: 'function' as const,
- },
- ]
- : [],
- )
- : undefined;
- const thinking = isRecord(request.thinking) ? request.thinking : undefined;
- return {
- max_tokens: typeof request.max_tokens === 'number' ? request.max_tokens : undefined,
- messages,
- model,
- stream: true,
- temperature: typeof request.temperature === 'number' ? request.temperature : undefined,
- thinking: thinking as ChatStreamPayload['thinking'],
- tools,
- top_p: typeof request.top_p === 'number' ? request.top_p : undefined,
- } satisfies ChatStreamPayload;
-};
-
-export const normalizeResponsesRequest = (request: Record<string, unknown>, model: string) => {
- const messages: OpenAIChatMessage[] = [];
- let pendingReasoningItems: NonNullable<OpenAIChatMessage['reasoning']>['responseItems'] = [];
- const takePendingReasoning = () => {
- if (!pendingReasoningItems?.length) return {};
- const reasoning = { reasoning: { responseItems: pendingReasoningItems } };
- pendingReasoningItems = [];
- return reasoning;
- };
- if (typeof request.instructions === 'string') {
- messages.push({ content: request.instructions, role: 'system' });
- }
- if (typeof request.input === 'string') {
- messages.push({ content: request.input, role: 'user' });
- } else if (Array.isArray(request.input)) {
- for (const item of request.input) {
- if (!isRecord(item)) continue;
- if (item.type === 'reasoning' && typeof item.id === 'string' && Array.isArray(item.summary)) {
- pendingReasoningItems?.push(
- item as unknown as NonNullable<
- NonNullable<OpenAIChatMessage['reasoning']>['responseItems']
- >[number],
- );
- } else if (item.type === 'function_call' && typeof item.call_id === 'string') {
- const toolCall = {
- function: { arguments: String(item.arguments || ''), name: String(item.name || '') },
- id: item.call_id,
- type: 'function' as const,
- };
- const previousMessage = messages.at(-1);
-
- // Responses history records every parallel call before their outputs.
- // Chat Completions requires those calls in one assistant message, followed
- // by the contiguous batch of tool-result messages.
- if (
- !pendingReasoningItems?.length &&
- previousMessage?.role === 'assistant' &&
- previousMessage.tool_calls?.length
- ) {
- previousMessage.tool_calls.push(toolCall);
- } else {
- messages.push({
- content: '',
- role: 'assistant',
- ...takePendingReasoning(),
- tool_calls: [toolCall],
- });
- }
- } else if (item.type === 'function_call_output' && typeof item.call_id === 'string') {
- messages.push({
- content: String(item.output || ''),
- role: 'tool',
- tool_call_id: item.call_id,
- });
- } else if (
- (item.type === undefined || item.type === 'message') &&
- ['assistant', 'developer', 'system', 'user'].includes(String(item.role))
- ) {
- messages.push({
- content: contentWithImages(item.content),
- role: item.role === 'developer' ? 'system' : (item.role as OpenAIChatMessage['role']),
- ...(item.role === 'assistant' ? takePendingReasoning() : {}),
- });
- }
- }
- }
- if (pendingReasoningItems?.length) {
- messages.push({ content: '', role: 'assistant', ...takePendingReasoning() });
- }
- const tools = Array.isArray(request.tools)
- ? request.tools.flatMap((tool) =>
- isRecord(tool) && tool.type === 'function' && typeof tool.name === 'string'
- ? [
- {
- function: {
- description: typeof tool.description === 'string' ? tool.description : undefined,
- name: tool.name,
- parameters: isRecord(tool.parameters) ? tool.parameters : {},
- },
- type: 'function' as const,
- },
- ]
- : [],
- )
- : undefined;
- return {
- max_tokens:
- typeof request.max_output_tokens === 'number' ? request.max_output_tokens : undefined,
- messages,
- model,
- reasoning: isRecord(request.reasoning) ? request.reasoning : undefined,
- stream: true,
- temperature: typeof request.temperature === 'number' ? request.temperature : undefined,
- tools,
- top_p: typeof request.top_p === 'number' ? request.top_p : undefined,
- } satisfies ChatStreamPayload;
-};
-
-interface ProtocolEvent {
- data: unknown;
- id?: string;
- type: string;
-}
-
-const parseProtocolStream = (stream: ReadableStream<Uint8Array>) => {
- let buffer = '';
- let eventId = '';
- let eventType = '';
- const decoder = new TextDecoder();
- const processLine = (
- line: string,
- controller: TransformStreamDefaultController<ProtocolEvent>,
- ) => {
- if (line.startsWith('id:')) eventId = line.slice(3).trim();
- if (line.startsWith('event:')) eventType = line.slice(6).trim();
- if (line.startsWith('data:')) {
- controller.enqueue({
- data: JSON.parse(line.slice(5).trim()),
- ...(eventId ? { id: eventId } : {}),
- type: eventType,
- });
- eventId = '';
- eventType = '';
- }
- };
- return stream
- .pipeThrough(
- new TransformStream<Uint8Array, string>({
- flush(controller) {
- const tail = decoder.decode();
- if (tail) controller.enqueue(tail);
- },
- transform(chunk, controller) {
- controller.enqueue(decoder.decode(chunk, { stream: true }));
- },
- }),
- )
- .pipeThrough(
- new TransformStream<string, ProtocolEvent>({
- flush(controller) {
- if (buffer.trim()) processLine(buffer, controller);
- },
- transform(chunk, controller) {
- buffer += chunk;
- const lines = buffer.split('\n');
- buffer = lines.pop() ?? '';
- for (const line of lines) {
- processLine(line, controller);
- }
- },
- }),
- );
-};
-
-const sse = (event: string, data: unknown) => `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
-
-const nonNegativeNumber = (value: unknown): number | undefined => {
- if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) return undefined;
- return value;
-};
-
-interface AnthropicStreamUsage {
- cache_creation_input_tokens?: number;
- cache_read_input_tokens?: number;
- input_tokens: number;
- output_tokens: number;
-}
-
-/**
- * Map a LobeHub protocol `usage` event onto Anthropic `message_delta.usage`.
- * `message_start` is emitted before upstream usage exists, so Claude Code treats
- * this snapshot as the final turn total (input + cache + output).
- */
-const toAnthropicStreamUsage = (data: Record<string, unknown>): AnthropicStreamUsage => {
- const cached = nonNegativeNumber(data.inputCachedTokens);
- const written = nonNegativeNumber(data.inputWriteCacheTokens);
- const totalInput = nonNegativeNumber(data.totalInputTokens) ?? 0;
- const miss = nonNegativeNumber(data.inputCacheMissTokens);
- const hasCache = (cached ?? 0) > 0 || (written ?? 0) > 0;
-
- return {
- ...(written ? { cache_creation_input_tokens: written } : {}),
- ...(cached ? { cache_read_input_tokens: cached } : {}),
- input_tokens: hasCache
- ? (miss ?? Math.max(0, totalInput - (cached ?? 0) - (written ?? 0)))
- : totalInput,
- output_tokens: nonNegativeNumber(data.totalOutputTokens) ?? 0,
- };
-};
-
-export const encodeAnthropicStream = (source: ReadableStream<Uint8Array>, model: string) => {
- const messageId = `msg_${randomUUID().replaceAll('-', '')}`;
- let finalized = false;
- let nextIndex = 0;
- let stopReason: string | undefined;
- let textIndex: number | undefined;
- let thinkingIndex: number | undefined;
- let usage: AnthropicStreamUsage = { input_tokens: 0, output_tokens: 0 };
- const tools = new Map<number, { blockIndex: number; id: string; name: string }>();
- const closeTextBlocks = (controller: TransformStreamDefaultController<string>) => {
- for (const index of [textIndex, thinkingIndex]) {
- if (index !== undefined)
- controller.enqueue(sse('content_block_stop', { index, type: 'content_block_stop' }));
- }
- textIndex = undefined;
- thinkingIndex = undefined;
- };
- const finalize = (controller: TransformStreamDefaultController<string>) => {
- if (finalized) return;
- finalized = true;
- closeTextBlocks(controller);
- for (const { blockIndex } of tools.values()) {
- controller.enqueue(
- sse('content_block_stop', { index: blockIndex, type: 'content_block_stop' }),
- );
- }
- controller.enqueue(
- sse('message_delta', {
- delta: {
- stop_reason: tools.size
- ? 'tool_use'
- : stopReason === 'max_tokens'
- ? 'max_tokens'
- : 'end_turn',
- stop_sequence: null,
- },
- type: 'message_delta',
- usage,
- }),
- );
- controller.enqueue(sse('message_stop', { type: 'message_stop' }));
- };
- return parseProtocolStream(source)
- .pipeThrough(
- new TransformStream<ProtocolEvent, string>({
- start(controller) {
- controller.enqueue(
- sse('message_start', {
- message: {
- content: [],
- id: messageId,
- model,
- role: 'assistant',
- stop_reason: null,
- type: 'message',
- usage: { input_tokens: 0, output_tokens: 0 },
- },
- type: 'message_start',
- }),
- );
- },
- transform(event, controller) {
- if (finalized) return;
- const part =
- (event.type === 'content_part' || event.type === 'reasoning_part') &&
- isRecord(event.data) &&
- event.data.partType === 'text'
- ? event.data
- : undefined;
- const content =
- event.type === 'text' || event.type === 'reasoning'
- ? typeof event.data === 'string'
- ? event.data
- : undefined
- : typeof part?.content === 'string'
- ? part.content
- : undefined;
- if (content !== undefined) {
- const isThinking = event.type === 'reasoning' || event.type === 'reasoning_part';
- let index = isThinking ? thinkingIndex : textIndex;
- if (index === undefined) {
- closeTextBlocks(controller);
- index = nextIndex++;
- controller.enqueue(
- sse('content_block_start', {
- content_block: isThinking
- ? { signature: '', thinking: '', type: 'thinking' }
- : { text: '', type: 'text' },
- index,
- type: 'content_block_start',
- }),
- );
- if (isThinking) thinkingIndex = index;
- else textIndex = index;
- }
- if (content) {
- controller.enqueue(
- sse('content_block_delta', {
- delta: isThinking
- ? { thinking: content, type: 'thinking_delta' }
- : { text: content, type: 'text_delta' },
- index,
- type: 'content_block_delta',
- }),
- );
- }
- } else if (
- event.type === 'reasoning_signature' &&
- thinkingIndex !== undefined &&
- typeof event.data === 'string' &&
- event.data
- ) {
- controller.enqueue(
- sse('content_block_delta', {
- delta: { signature: event.data, type: 'signature_delta' },
- index: thinkingIndex,
- type: 'content_block_delta',
- }),
- );
- } else if (event.type === 'tool_calls' && Array.isArray(event.data)) {
- closeTextBlocks(controller);
- for (const chunk of event.data) {
- if (!isRecord(chunk) || typeof chunk.index !== 'number') continue;
- const fn = isRecord(chunk.function) ? chunk.function : {};
- let tool = tools.get(chunk.index);
- if (!tool) {
- tool = {
- blockIndex: nextIndex++,
- id: String(chunk.id || `tool_${randomUUID()}`),
- name: String(fn.name || ''),
- };
- tools.set(chunk.index, tool);
- controller.enqueue(
- sse('content_block_start', {
- content_block: { id: tool.id, input: {}, name: tool.name, type: 'tool_use' },
- index: tool.blockIndex,
- type: 'content_block_start',
- }),
- );
- }
- if (typeof fn.arguments === 'string' && fn.arguments)
- controller.enqueue(
- sse('content_block_delta', {
- delta: { partial_json: fn.arguments, type: 'input_json_delta' },
- index: tool.blockIndex,
- type: 'content_block_delta',
- }),
- );
- }
- } else if (event.type === 'usage' && isRecord(event.data)) {
- usage = toAnthropicStreamUsage(event.data);
- } else if (event.type === 'stop') {
- const reason = typeof event.data === 'string' ? event.data : undefined;
- if (!stopReason && reason && reason !== 'message_stop') stopReason = reason;
- } else if (event.type === 'error') {
- finalized = true;
- controller.enqueue(
- sse('error', {
- error: {
- message: isRecord(event.data)
- ? String(event.data.message || 'Model request failed')
- : String(event.data),
- type: 'api_error',
- },
- type: 'error',
- }),
- );
- }
- },
- flush(controller) {
- finalize(controller);
- },
- }),
- )
- .pipeThrough(new TextEncoderStream());
-};
-
-export const encodeResponsesStream = (source: ReadableStream<Uint8Array>, model: string) => {
- const responseId = `resp_${randomUUID().replaceAll('-', '')}`;
- let finalized = false;
- let nextOutputIndex = 0;
- const outputItems: unknown[] = [];
- let reasoningItemId: string | undefined;
- let reasoningOutputIndex: number | undefined;
- let reasoningText = '';
- let sequenceNumber = 0;
- let stopReason: unknown;
- let textOutputIndex: number | undefined;
- let outputText = '';
- let usage: ResponseUsage | undefined;
- const toolItems = new Map<
- number,
- { arguments: string; callId: string; id: string; name: string; outputIndex: number }
- >();
- const response = {
- created_at: Math.floor(Date.now() / 1000),
- error: null,
- id: responseId,
- incomplete_details: null,
- instructions: null,
- model,
- object: 'response',
- output: [],
- status: 'in_progress',
- };
- const responseSse = (
- event: BaseStreamEvent['type'],
- data: Omit<BaseStreamEvent, 'sequence_number'> & Record<string, unknown>,
- ) => {
- const sequencedData = {
- ...data,
- sequence_number: sequenceNumber++,
- } satisfies BaseStreamEvent;
- return sse(event, sequencedData);
- };
- const completeReasoning = (
- controller: TransformStreamDefaultController<string>,
- responseItem?: unknown,
- ) => {
- if (reasoningOutputIndex === undefined) {
- if (responseItem === undefined) return;
- const outputIndex = nextOutputIndex++;
- const item = isRecord(responseItem) ? { ...responseItem, status: 'completed' } : responseItem;
- outputItems[outputIndex] = item;
- controller.enqueue(
- responseSse('response.output_item.added', {
- item: isRecord(responseItem) ? { ...responseItem, status: 'in_progress' } : responseItem,
- output_index: outputIndex,
- type: 'response.output_item.added',
- }),
- );
- controller.enqueue(
- responseSse('response.output_item.done', {
- item,
- output_index: outputIndex,
- type: 'response.output_item.done',
- }),
- );
- return;
- }
-
- const outputIndex = reasoningOutputIndex;
- const itemId =
- isRecord(responseItem) && typeof responseItem.id === 'string'
- ? responseItem.id
- : reasoningItemId || `rs_${responseId}`;
- const item = isRecord(responseItem)
- ? { ...responseItem, status: 'completed' }
- : {
- id: itemId,
- status: 'completed',
- summary: [{ text: reasoningText, type: 'summary_text' }],
- type: 'reasoning',
- };
- outputItems[outputIndex] = item;
- controller.enqueue(
- responseSse('response.reasoning_summary_text.done', {
- item_id: itemId,
- output_index: outputIndex,
- summary_index: 0,
- text: reasoningText,
- type: 'response.reasoning_summary_text.done',
- }),
- );
- controller.enqueue(
- responseSse('response.output_item.done', {
- item,
- output_index: outputIndex,
- type: 'response.output_item.done',
- }),
- );
- reasoningItemId = undefined;
- reasoningOutputIndex = undefined;
- reasoningText = '';
- };
- const finalize = (controller: TransformStreamDefaultController<string>) => {
- if (finalized) return;
- finalized = true;
- completeReasoning(controller);
- if (textOutputIndex !== undefined) {
- const item = {
- content: [{ annotations: [], text: outputText, type: 'output_text' }],
- id: `msg_${responseId}`,
- role: 'assistant',
- status: 'completed',
- type: 'message',
- };
- outputItems[textOutputIndex] = item;
- controller.enqueue(
- responseSse('response.output_text.done', {
- content_index: 0,
- item_id: `msg_${responseId}`,
- output_index: textOutputIndex,
- text: outputText,
- type: 'response.output_text.done',
- }),
- );
- controller.enqueue(
- responseSse('response.content_part.done', {
- content_index: 0,
- item_id: `msg_${responseId}`,
- output_index: textOutputIndex,
- part: { annotations: [], text: outputText, type: 'output_text' },
- type: 'response.content_part.done',
- }),
- );
- controller.enqueue(
- responseSse('response.output_item.done', {
- item,
- output_index: textOutputIndex,
- type: 'response.output_item.done',
- }),
- );
- }
- for (const tool of toolItems.values()) {
- const item = {
- arguments: tool.arguments,
- call_id: tool.callId,
- id: tool.id,
- name: tool.name,
- status: 'completed',
- type: 'function_call',
- };
- outputItems[tool.outputIndex] = item;
- controller.enqueue(
- responseSse('response.function_call_arguments.done', {
- arguments: tool.arguments,
- item_id: tool.id,
- output_index: tool.outputIndex,
- type: 'response.function_call_arguments.done',
- }),
- );
- controller.enqueue(
- responseSse('response.output_item.done', {
- item,
- output_index: tool.outputIndex,
- type: 'response.output_item.done',
- }),
- );
- }
- const incomplete = stopReason === 'max_tokens';
- const type = incomplete ? 'response.incomplete' : 'response.completed';
- controller.enqueue(
- responseSse(type, {
- response: {
- ...response,
- incomplete_details: incomplete ? { reason: 'max_output_tokens' } : null,
- output: outputItems.filter(Boolean),
- status: incomplete ? 'incomplete' : 'completed',
- usage,
- },
- type,
- }),
- );
- controller.enqueue('data: [DONE]\n\n');
- };
- return parseProtocolStream(source)
- .pipeThrough(
- new TransformStream<ProtocolEvent, string>({
- start(controller) {
- controller.enqueue(
- responseSse('response.created', { response, type: 'response.created' }),
- );
- },
- transform(event, controller) {
- if (finalized) return;
- const part =
- (event.type === 'content_part' || event.type === 'reasoning_part') &&
- isRecord(event.data) &&
- event.data.partType === 'text'
- ? event.data
- : undefined;
- const content =
- event.type === 'text' || event.type === 'reasoning'
- ? typeof event.data === 'string'
- ? event.data
- : undefined
- : typeof part?.content === 'string'
- ? part.content
- : undefined;
- const isReasoning = event.type === 'reasoning' || event.type === 'reasoning_part';
- if (content && !isReasoning) {
- outputText += content;
- if (textOutputIndex === undefined) {
- textOutputIndex = nextOutputIndex++;
- controller.enqueue(
- responseSse('response.output_item.added', {
- item: {
- content: [],
- id: `msg_${responseId}`,
- role: 'assistant',
- status: 'in_progress',
- type: 'message',
- },
- output_index: textOutputIndex,
- type: 'response.output_item.added',
- }),
- );
- controller.enqueue(
- responseSse('response.content_part.added', {
- content_index: 0,
- item_id: `msg_${responseId}`,
- output_index: textOutputIndex,
- part: { annotations: [], text: '', type: 'output_text' },
- type: 'response.content_part.added',
- }),
- );
- }
- controller.enqueue(
- responseSse('response.output_text.delta', {
- content_index: 0,
- delta: content,
- item_id: `msg_${responseId}`,
- output_index: textOutputIndex,
- type: 'response.output_text.delta',
- }),
- );
- } else if (content && isReasoning) {
- reasoningText += content;
- if (reasoningOutputIndex === undefined) {
- reasoningItemId = event.id || `rs_${responseId}`;
- reasoningOutputIndex = nextOutputIndex++;
- controller.enqueue(
- responseSse('response.output_item.added', {
- item: {
- id: reasoningItemId,
- status: 'in_progress',
- summary: [],
- type: 'reasoning',
- },
- output_index: reasoningOutputIndex,
- type: 'response.output_item.added',
- }),
- );
- }
- controller.enqueue(
- responseSse('response.reasoning_summary_text.delta', {
- delta: content,
- item_id: reasoningItemId,
- output_index: reasoningOutputIndex,
- summary_index: 0,
- type: 'response.reasoning_summary_text.delta',
- }),
- );
- } else if (event.type === 'reasoning_response_item') {
- completeReasoning(controller, event.data);
- } else if (event.type === 'tool_calls' && Array.isArray(event.data)) {
- for (const chunk of event.data) {
- if (!isRecord(chunk) || typeof chunk.index !== 'number') continue;
- const fn = isRecord(chunk.function) ? chunk.function : {};
- let tool = toolItems.get(chunk.index);
- if (!tool) {
- tool = {
- arguments: '',
- callId: String(chunk.id || `call_${randomUUID()}`),
- id: `fc_${randomUUID()}`,
- name: String(fn.name || ''),
- outputIndex: nextOutputIndex++,
- };
- toolItems.set(chunk.index, tool);
- controller.enqueue(
- responseSse('response.output_item.added', {
- item: {
- arguments: '',
- call_id: tool.callId,
- id: tool.id,
- name: tool.name,
- status: 'in_progress',
- type: 'function_call',
- },
- output_index: tool.outputIndex,
- type: 'response.output_item.added',
- }),
- );
- }
- if (typeof fn.arguments === 'string') {
- tool.arguments += fn.arguments;
- controller.enqueue(
- responseSse('response.function_call_arguments.delta', {
- delta: fn.arguments,
- item_id: tool.id,
- output_index: tool.outputIndex,
- type: 'response.function_call_arguments.delta',
- }),
- );
- }
- }
- } else if (event.type === 'usage' && isRecord(event.data)) {
- const inputTokens = nonNegativeNumber(event.data.totalInputTokens) ?? 0;
- const outputTokens = nonNegativeNumber(event.data.totalOutputTokens) ?? 0;
- usage = {
- input_tokens: inputTokens,
- input_tokens_details: {
- cached_tokens: nonNegativeNumber(event.data.inputCachedTokens) ?? 0,
- },
- output_tokens: outputTokens,
- output_tokens_details: {
- reasoning_tokens: nonNegativeNumber(event.data.outputReasoningTokens) ?? 0,
- },
- total_tokens: inputTokens + outputTokens,
- };
- } else if (event.type === 'stop') {
- if (stopReason === undefined && event.data) stopReason = event.data;
- } else if (event.type === 'error') {
- const message = isRecord(event.data)
- ? String(event.data.message || 'Model request failed')
- : String(event.data);
- finalized = true;
- controller.enqueue(
- responseSse('response.failed', {
- response: {
- ...response,
- error: { code: 'server_error', message },
- output: outputItems.filter(Boolean),
- status: 'failed',
- },
- type: 'response.failed',
- }),
- );
- controller.enqueue('data: [DONE]\n\n');
- }
- },
- flush(controller) {
- finalize(controller);
- },
- }),
- )
- .pipeThrough(new TextEncoderStream());
-};
+export {
+ normalizeAnthropicRequest,
+ normalizeResponsesRequest,
+} from './heterogeneous-direct.request';
+export { encodeResponsesStream } from './heterogeneous-direct.responses';
+export { encodeAnthropicStream } from './heterogeneous-direct.stream';
export const invokeServerDefaultModel = async (params: {
agentType: ServerDefaultHeterogeneousAgentType;
@@ -956,6 +51,17 @@ export const invokeServerDefaultModel = async (params: {
workspaceId: params.workspaceId,
});
const normalizedPayload = { ...params.payload };
+ // OpenAI-compatible routers can also select Claude. Normalize before routing,
+ // using the logical model rather than an opaque provider deployment alias.
+ if (parseClaudeModelId(resolvedModel.model) || parseClaudeModelId(params.model)) {
+ normalizedPayload.tools = normalizedPayload.tools?.map((tool) => ({
+ ...tool,
+ function: {
+ ...tool.function,
+ parameters: normalizeAnthropicToolSchema(tool.function.parameters),
+ },
+ }));
+ }
// Kimi can use its context window as the output budget for an unknown model.
// Bound that budget by the selected deployment model, including for older clients.
if (params.agentType === 'kimi-code' && maxOutput !== undefined && maxOutput > 0) {
diff --git a/packages/openapi/src/services/heterogeneous-direct.stream.ts b/packages/openapi/src/services/heterogeneous-direct.stream.ts
new file mode 100644
index 00000000000..75dad4aee50
--- /dev/null
+++ b/packages/openapi/src/services/heterogeneous-direct.stream.ts
@@ -0,0 +1,273 @@
+import { randomUUID } from 'node:crypto';
+
+import { isRecord } from '@lobechat/utils/object';
+
+export interface ProtocolEvent {
+ data: unknown;
+ id?: string;
+ type: string;
+}
+
+export const parseProtocolStream = (stream: ReadableStream<Uint8Array>) => {
+ let buffer = '';
+ let eventId = '';
+ let eventType = '';
+ const decoder = new TextDecoder();
+ const processLine = (
+ line: string,
+ controller: TransformStreamDefaultController<ProtocolEvent>,
+ ) => {
+ if (line.startsWith('id:')) eventId = line.slice(3).trim();
+ if (line.startsWith('event:')) eventType = line.slice(6).trim();
+ if (line.startsWith('data:')) {
+ controller.enqueue({
+ data: JSON.parse(line.slice(5).trim()),
+ ...(eventId ? { id: eventId } : {}),
+ type: eventType,
+ });
+ eventId = '';
+ eventType = '';
+ }
+ };
+ return stream
+ .pipeThrough(
+ new TransformStream<Uint8Array, string>({
+ flush(controller) {
+ const tail = decoder.decode();
+ if (tail) controller.enqueue(tail);
+ },
+ transform(chunk, controller) {
+ controller.enqueue(decoder.decode(chunk, { stream: true }));
+ },
+ }),
+ )
+ .pipeThrough(
+ new TransformStream<string, ProtocolEvent>({
+ flush(controller) {
+ if (buffer.trim()) processLine(buffer, controller);
+ },
+ transform(chunk, controller) {
+ buffer += chunk;
+ const lines = buffer.split('\n');
+ buffer = lines.pop() ?? '';
+ for (const line of lines) {
+ processLine(line, controller);
+ }
+ },
+ }),
+ );
+};
+
+export const sse = (event: string, data: unknown) =>
+ `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
+
+export const nonNegativeNumber = (value: unknown): number | undefined => {
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) return undefined;
+ return value;
+};
+
+interface AnthropicStreamUsage {
+ cache_creation_input_tokens?: number;
+ cache_read_input_tokens?: number;
+ input_tokens: number;
+ output_tokens: number;
+}
+
+/**
+ * Map a LobeHub protocol `usage` event onto Anthropic `message_delta.usage`.
+ * `message_start` is emitted before upstream usage exists, so Claude Code treats
+ * this snapshot as the final turn total (input + cache + output).
+ */
+const toAnthropicStreamUsage = (data: Record<string, unknown>): AnthropicStreamUsage => {
+ const cached = nonNegativeNumber(data.inputCachedTokens);
+ const written = nonNegativeNumber(data.inputWriteCacheTokens);
+ const totalInput = nonNegativeNumber(data.totalInputTokens) ?? 0;
+ const miss = nonNegativeNumber(data.inputCacheMissTokens);
+ const hasCache = (cached ?? 0) > 0 || (written ?? 0) > 0;
+
+ return {
+ ...(written ? { cache_creation_input_tokens: written } : {}),
+ ...(cached ? { cache_read_input_tokens: cached } : {}),
+ input_tokens: hasCache
+ ? (miss ?? Math.max(0, totalInput - (cached ?? 0) - (written ?? 0)))
+ : totalInput,
+ output_tokens: nonNegativeNumber(data.totalOutputTokens) ?? 0,
+ };
+};
+
+export const encodeAnthropicStream = (source: ReadableStream<Uint8Array>, model: string) => {
+ const messageId = `msg_${randomUUID().replaceAll('-', '')}`;
+ let finalized = false;
+ let nextIndex = 0;
+ let stopReason: string | undefined;
+ let textIndex: number | undefined;
+ let thinkingIndex: number | undefined;
+ let usage: AnthropicStreamUsage = { input_tokens: 0, output_tokens: 0 };
+ const tools = new Map<number, { blockIndex: number; id: string; name: string }>();
+ const closeTextBlocks = (controller: TransformStreamDefaultController<string>) => {
+ for (const index of [textIndex, thinkingIndex]) {
+ if (index !== undefined)
+ controller.enqueue(sse('content_block_stop', { index, type: 'content_block_stop' }));
+ }
+ textIndex = undefined;
+ thinkingIndex = undefined;
+ };
+ const finalize = (controller: TransformStreamDefaultController<string>) => {
+ if (finalized) return;
+ finalized = true;
+ closeTextBlocks(controller);
+ for (const { blockIndex } of tools.values()) {
+ controller.enqueue(
+ sse('content_block_stop', { index: blockIndex, type: 'content_block_stop' }),
+ );
+ }
+ controller.enqueue(
+ sse('message_delta', {
+ delta: {
+ stop_reason: tools.size
+ ? 'tool_use'
+ : stopReason === 'max_tokens'
+ ? 'max_tokens'
+ : 'end_turn',
+ stop_sequence: null,
+ },
+ type: 'message_delta',
+ usage,
+ }),
+ );
+ controller.enqueue(sse('message_stop', { type: 'message_stop' }));
+ };
+ return parseProtocolStream(source)
+ .pipeThrough(
+ new TransformStream<ProtocolEvent, string>({
+ start(controller) {
+ controller.enqueue(
+ sse('message_start', {
+ message: {
+ content: [],
+ id: messageId,
+ model,
+ role: 'assistant',
+ stop_reason: null,
+ type: 'message',
+ usage: { input_tokens: 0, output_tokens: 0 },
+ },
+ type: 'message_start',
+ }),
+ );
+ },
+ transform(event, controller) {
+ if (finalized) return;
+ const part =
+ (event.type === 'content_part' || event.type === 'reasoning_part') &&
+ isRecord(event.data) &&
+ event.data.partType === 'text'
+ ? event.data
+ : undefined;
+ const content =
+ event.type === 'text' || event.type === 'reasoning'
+ ? typeof event.data === 'string'
+ ? event.data
+ : undefined
+ : typeof part?.content === 'string'
+ ? part.content
+ : undefined;
+ if (content !== undefined) {
+ const isThinking = event.type === 'reasoning' || event.type === 'reasoning_part';
+ let index = isThinking ? thinkingIndex : textIndex;
+ if (index === undefined) {
+ closeTextBlocks(controller);
+ index = nextIndex++;
+ controller.enqueue(
+ sse('content_block_start', {
+ content_block: isThinking
+ ? { signature: '', thinking: '', type: 'thinking' }
+ : { text: '', type: 'text' },
+ index,
+ type: 'content_block_start',
+ }),
+ );
+ if (isThinking) thinkingIndex = index;
+ else textIndex = index;
+ }
+ if (content) {
+ controller.enqueue(
+ sse('content_block_delta', {
+ delta: isThinking
+ ? { thinking: content, type: 'thinking_delta' }
+ : { text: content, type: 'text_delta' },
+ index,
+ type: 'content_block_delta',
+ }),
+ );
+ }
+ } else if (
+ event.type === 'reasoning_signature' &&
+ thinkingIndex !== undefined &&
+ typeof event.data === 'string' &&
+ event.data
+ ) {
+ controller.enqueue(
+ sse('content_block_delta', {
+ delta: { signature: event.data, type: 'signature_delta' },
+ index: thinkingIndex,
+ type: 'content_block_delta',
+ }),
+ );
+ } else if (event.type === 'tool_calls' && Array.isArray(event.data)) {
+ closeTextBlocks(controller);
+ for (const chunk of event.data) {
+ if (!isRecord(chunk) || typeof chunk.index !== 'number') continue;
+ const fn = isRecord(chunk.function) ? chunk.function : {};
+ let tool = tools.get(chunk.index);
+ if (!tool) {
+ tool = {
+ blockIndex: nextIndex++,
+ id: String(chunk.id || `tool_${randomUUID()}`),
+ name: String(fn.name || ''),
+ };
+ tools.set(chunk.index, tool);
+ controller.enqueue(
+ sse('content_block_start', {
+ content_block: { id: tool.id, input: {}, name: tool.name, type: 'tool_use' },
+ index: tool.blockIndex,
+ type: 'content_block_start',
+ }),
+ );
+ }
+ if (typeof fn.arguments === 'string' && fn.arguments)
+ controller.enqueue(
+ sse('content_block_delta', {
+ delta: { partial_json: fn.arguments, type: 'input_json_delta' },
+ index: tool.blockIndex,
+ type: 'content_block_delta',
+ }),
+ );
+ }
+ } else if (event.type === 'usage' && isRecord(event.data)) {
+ usage = toAnthropicStreamUsage(event.data);
+ } else if (event.type === 'stop') {
+ const reason = typeof event.data === 'string' ? event.data : undefined;
+ if (!stopReason && reason && reason !== 'message_stop') stopReason = reason;
+ } else if (event.type === 'error') {
+ finalized = true;
+ controller.enqueue(
+ sse('error', {
+ error: {
+ message: isRecord(event.data)
+ ? String(event.data.message || 'Model request failed')
+ : String(event.data),
+ type: 'api_error',
+ },
+ type: 'error',
+ }),
+ );
+ }
+ },
+ flush(controller) {
+ finalize(controller);
+ },
+ }),
+ )
+ .pipeThrough(new TextEncoderStream());
+};
diff --git a/packages/openapi/src/types/responses.type.ts b/packages/openapi/src/types/responses.type.ts
index 5be19e4924c..06f754c6f8b 100644
--- a/packages/openapi/src/types/responses.type.ts
+++ b/packages/openapi/src/types/responses.type.ts
@@ -139,11 +139,7 @@ export interface ResponseUsage {
// ==================== Error Types ====================
export type ResponseErrorCode =
- | 'server_error'
- | 'invalid_request_error'
- | 'not_found'
- | 'model_error'
- | 'rate_limit_error';
+ 'server_error' | 'invalid_request_error' | 'not_found' | 'model_error' | 'rate_limit_error';
export interface ResponseError {
code: ResponseErrorCode;
@@ -251,6 +247,8 @@ export type ResponseStreamEventType =
// Function call events
| 'response.function_call_arguments.delta'
| 'response.function_call_arguments.done'
+ | 'response.custom_tool_call_input.delta'
+ | 'response.custom_tool_call_input.done'
// Reasoning events
| 'response.reasoning_summary_text.delta'
| 'response.reasoning_summary_text.done';