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(model-runtime): report usage callbacks for JSON response mode (#22064)

YuTengjingf53a51d3e39e
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.jsonMode.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.jsonMode.test.ts
new file mode 100644
index 00000000000..4c8389f8ae4
--- /dev/null
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.jsonMode.test.ts
@@ -0,0 +1,80 @@
+// @vitest-environment node
+import type OpenAI from 'openai';
+import { describe, expect, it, vi } from 'vitest';
+
+import { createOpenAICompatibleRuntime } from '../openaiCompatibleFactory';
+import { createRouterRuntime } from './createRuntime';
+
+vi.mock('@lobechat/business-model-bank/model-config', () => ({
+ loadModels: vi.fn().mockResolvedValue([]),
+}));
+
+const completion = {
+ choices: [
+ {
+ finish_reason: 'stop',
+ index: 0,
+ logprobs: null,
+ message: { content: 'answer', refusal: null, role: 'assistant' },
+ },
+ ],
+ created: 1,
+ id: 'chatcmpl-json',
+ model: 'gpt-4',
+ object: 'chat.completion',
+ usage: { completion_tokens: 7, prompt_tokens: 11, total_tokens: 18 },
+} as OpenAI.ChatCompletion;
+
+const ProviderRuntime = createOpenAICompatibleRuntime({
+ customClient: {
+ createClient: () =>
+ ({
+ chat: { completions: { create: vi.fn().mockResolvedValue(completion) } },
+ }) as unknown as OpenAI,
+ },
+ provider: 'test-provider',
+});
+
+describe('RouterRuntime JSON response mode', () => {
+ it.each([
+ ['stream fallback', true],
+ ['direct fallback', false],
+ ])(
+ 'records provider usage on the attempt and the final callback (%s)',
+ async (_label, fallbackChatAttempt) => {
+ const finished = vi.fn();
+ const onFinal = vi.fn();
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ onRouteAttemptFinished: finished,
+ routers: [
+ {
+ apiType: 'openai',
+ models: ['gpt-4'],
+ options: { apiKey: 'test' },
+ runtime: ProviderRuntime,
+ },
+ ],
+ ...(fallbackChatAttempt && { shouldFallbackChatAttempt: () => true }),
+ });
+
+ const response = await new Runtime().chat(
+ { messages: [], model: 'gpt-4', responseMode: 'json', stream: false },
+ { callback: { onFinal } },
+ );
+
+ await expect(response.json()).resolves.toEqual(completion);
+ expect(finished).toHaveBeenCalledOnce();
+ expect(finished.mock.calls[0][0]).toMatchObject({
+ outcome: 'completed',
+ streaming: false,
+ usage: { totalInputTokens: 11, totalOutputTokens: 7 },
+ });
+ expect(onFinal).toHaveBeenCalledOnce();
+ expect(onFinal.mock.calls[0][0].usage).toMatchObject({
+ totalInputTokens: 11,
+ totalOutputTokens: 7,
+ });
+ },
+ );
+});
diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts
index dd1cee318ff..4567b59c76e 100644
--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts
+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts
@@ -335,6 +335,51 @@ describe('createAnthropicCompatibleRuntime', () => {
expect(createClient.mock.calls[0][0]).not.toHaveProperty('modelIdMapping');
});
+ it('reports usage through onFinal in JSON response mode and returns the raw message', async () => {
+ const message = {
+ content: [{ text: 'Hello', type: 'text' }],
+ id: 'msg_json',
+ model: 'test-model',
+ role: 'assistant',
+ stop_reason: 'end_turn',
+ stop_sequence: null,
+ type: 'message',
+ usage: { cache_read_input_tokens: 100, input_tokens: 11, output_tokens: 7 },
+ };
+ const Runtime = createAnthropicCompatibleRuntime({
+ chatCompletion: {
+ handlePayload: (payload) => ({ max_tokens: 1024, messages: [], model: payload.model }),
+ },
+ customClient: {
+ createClient: () =>
+ ({
+ baseURL: 'https://api.example.com/anthropic',
+ messages: { create: vi.fn().mockResolvedValue(message) },
+ }) as unknown as Anthropic,
+ },
+ provider: 'test-provider',
+ });
+ const onFinal = vi.fn();
+
+ const response = await new Runtime({ apiKey: 'test-key' }).chat(
+ {
+ messages: [{ content: 'hi', role: 'user' }],
+ model: 'test-model',
+ responseMode: 'json',
+ stream: false,
+ } as any,
+ { callback: { onFinal } },
+ );
+
+ expect(await response.json()).toEqual(message);
+ expect(onFinal).toHaveBeenCalledTimes(1);
+ expect(onFinal.mock.calls[0][0].usage).toMatchObject({
+ inputCachedTokens: 100,
+ totalInputTokens: 111,
+ totalOutputTokens: 7,
+ });
+ });
+
it('should classify provider balance errors without a custom error handler', async () => {
const messagesCreate = vi.fn().mockRejectedValue({
error: {
diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
index b8cffc992bf..cc5a48f32ec 100644
--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
@@ -21,6 +21,7 @@ import type {
} from '../../types';
import type { ILobeAgentRuntimeErrorType } from '../../types/error';
import { AgentRuntimeErrorType } from '../../types/error';
+import { respondJsonAfterStream } from '../../utils/consumeStream';
import { AgentRuntimeError } from '../../utils/createError';
import { debugPayload, debugStream } from '../../utils/debugStream';
import { desensitizeUrl } from '../../utils/desensitizeUrl';
@@ -699,10 +700,6 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =
options?.signal,
);
- if (payload.responseMode === 'json') {
- return Response.json(response);
- }
-
const stream = new ReadableStream<Anthropic.MessageStreamEvent>({
start(controller) {
const message = response as Anthropic.Message;
@@ -767,7 +764,7 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =
},
});
- return StreamingResponse(
+ const streamingResponse = StreamingResponse(
chatCompletion?.handleStream
? chatCompletion.handleStream(stream, {
callbacks: streamOptions.callbacks,
@@ -783,6 +780,10 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =
headers: options?.headers,
},
);
+
+ if (payload.responseMode === 'json')
+ return await respondJsonAfterStream(streamingResponse, response);
+ return streamingResponse;
} catch (error) {
throw this.handleError(error);
}
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
index 8d365b7a31f..57025680a5b 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
@@ -38,6 +38,7 @@ import type {
PollVideoStatusResult,
VideoGenerationCapabilities,
} from '../../types/video';
+import { respondJsonAfterStream } from '../../utils/consumeStream';
import { AgentRuntimeError } from '../../utils/createError';
import { debugPayload, debugResponse, debugStream } from '../../utils/debugStream';
import { desensitizeUrl } from '../../utils/desensitizeUrl';
@@ -749,17 +750,14 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
options?.signal,
);
- if (responseMode === 'json') {
- log('returning JSON response mode');
- return Response.json(response);
- }
-
log('transforming non-streaming response to stream');
+ // Snapshot first: provider transform handlers may rewrite the completion in place
+ const jsonBody = responseMode === 'json' ? structuredClone(response) : undefined;
const transformHandler =
chatCompletion?.handleTransformResponseToStream || transformResponseToStream;
const stream = transformHandler(response as unknown as OpenAI.ChatCompletion);
- return StreamingResponse(
+ const streamingResponse = StreamingResponse(
chatCompletion?.handleStream
? chatCompletion.handleStream(stream, {
callbacks: streamOptions.callbacks,
@@ -771,6 +769,8 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
headers: options?.headers,
},
);
+ if (jsonBody) return await respondJsonAfterStream(streamingResponse, jsonBody);
+ return streamingResponse;
} catch (error) {
throw this.handleError(error);
}
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/jsonResponseMode.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/jsonResponseMode.test.ts
new file mode 100644
index 00000000000..cccecc0db00
--- /dev/null
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/jsonResponseMode.test.ts
@@ -0,0 +1,87 @@
+// @vitest-environment node
+import type OpenAI from 'openai';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { OnFinishData } from '../streams/protocol';
+import { createOpenAICompatibleRuntime } from './index';
+import { transformResponseToStream } from './nonStreamToStream';
+
+vi.mock('@lobechat/business-model-bank/model-config', () => ({
+ loadModels: vi.fn().mockResolvedValue([]),
+}));
+
+const chatCompletion = {
+ choices: [
+ {
+ finish_reason: 'stop',
+ index: 0,
+ logprobs: null,
+ message: { content: 'Hello', refusal: null, role: 'assistant' },
+ },
+ ],
+ created: 1,
+ id: 'chatcmpl-json',
+ model: 'test-model',
+ object: 'chat.completion',
+ usage: { completion_tokens: 7, prompt_tokens: 11, total_tokens: 18 },
+} as OpenAI.ChatCompletion;
+
+/**
+ * JSON response mode returns the provider body verbatim, but usage callbacks must still fire:
+ * usage tracking and billing hooks only ever see usage through `onFinal`.
+ */
+describe('JSON response mode', () => {
+ it('reports chat completion usage through onFinal and returns the raw body', async () => {
+ const create = vi.fn().mockResolvedValue(chatCompletion);
+ const Runtime = createOpenAICompatibleRuntime({
+ customClient: {
+ createClient: () => ({ chat: { completions: { create } } }) as unknown as OpenAI,
+ },
+ provider: 'test',
+ });
+ const onFinal = vi.fn<(data: OnFinishData) => void>();
+
+ const response = await new Runtime({ apiKey: 'test' }).chat(
+ {
+ messages: [{ content: 'Hi', role: 'user' }],
+ model: 'test-model',
+ responseMode: 'json',
+ stream: false,
+ },
+ { callback: { onFinal } },
+ );
+
+ expect(response.headers.get('content-type')).toContain('application/json');
+ expect(await response.json()).toEqual(chatCompletion);
+ expect(onFinal).toHaveBeenCalledTimes(1);
+ expect(onFinal.mock.calls[0][0].usage).toMatchObject({
+ totalInputTokens: 11,
+ totalOutputTokens: 7,
+ });
+ });
+
+ it('returns the provider body untouched when a transform handler rewrites it', async () => {
+ const create = vi.fn().mockResolvedValue(structuredClone(chatCompletion));
+ const Runtime = createOpenAICompatibleRuntime({
+ chatCompletion: {
+ handleTransformResponseToStream: (data) => {
+ (data.choices[0].message as any).reasoning_content = 'rewritten';
+ return transformResponseToStream(data);
+ },
+ },
+ customClient: {
+ createClient: () => ({ chat: { completions: { create } } }) as unknown as OpenAI,
+ },
+ provider: 'test',
+ });
+
+ const response = await new Runtime({ apiKey: 'test' }).chat({
+ messages: [{ content: 'Hi', role: 'user' }],
+ model: 'test-model',
+ responseMode: 'json',
+ stream: false,
+ });
+
+ expect(await response.json()).toEqual(chatCompletion);
+ });
+});
diff --git a/packages/model-runtime/src/utils/consumeStream.ts b/packages/model-runtime/src/utils/consumeStream.ts
index 3ef356eb510..d6653d6b087 100644
--- a/packages/model-runtime/src/utils/consumeStream.ts
+++ b/packages/model-runtime/src/utils/consumeStream.ts
@@ -32,3 +32,16 @@ export async function consumeStreamUntilDone(response: Response): Promise<void>
reader.releaseLock();
}
}
+
+/**
+ * Answer a JSON-mode chat with the raw provider body. Usage callbacks only fire inside the
+ * stream transform, so drain it first; otherwise `onFinal` never reports usage and usage
+ * tracking (billing, tracing) silently sees nothing.
+ */
+export async function respondJsonAfterStream(
+ streamingResponse: Response,
+ body: unknown,
+): Promise<Response> {
+ await consumeStreamUntilDone(streamingResponse);
+ return Response.json(body);
+}