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.

✨ feat: add ModelRuntime hooks for billing lifecycle interception (#13013)

YuTengjingd2666b735b5e
diff --git a/packages/model-runtime/src/core/ModelRuntime.test.ts b/packages/model-runtime/src/core/ModelRuntime.test.ts
index bf3ecd80033..e638aedf02f 100644
--- a/packages/model-runtime/src/core/ModelRuntime.test.ts
+++ b/packages/model-runtime/src/core/ModelRuntime.test.ts
@@ -3,7 +3,7 @@ import type { ClientSecretPayload } from '@lobechat/types';
import { ModelProvider } from 'model-bank';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import type { ChatStreamCallbacks, ChatStreamPayload } from '../index';
+import type { ChatStreamCallbacks, ChatStreamPayload, ModelRuntimeHooks } from '../index';
import { LobeOpenAI, ModelRuntime } from '../index';
import { providerRuntimeMap } from '../runtimeMap';
import type { CreateImagePayload } from '../types/image';
@@ -222,7 +222,7 @@ describe('ModelRuntime', () => {
const result = await mockModelRuntime.generateObject(payload);
- expect(LobeOpenAI.prototype.generateObject).toHaveBeenCalledWith(payload);
+ expect(LobeOpenAI.prototype.generateObject).toHaveBeenCalledWith(payload, undefined);
expect(result).toBe(mockResponse);
});
});
@@ -474,4 +474,161 @@ describe('ModelRuntime', () => {
expect(result).toBeUndefined();
});
});
+
+ describe('hooks', () => {
+ const createMockRuntime = (hooks?: ModelRuntimeHooks) => {
+ const mockRuntimeAI = { chat: vi.fn(), generateObject: vi.fn() } as any;
+ return { runtime: new ModelRuntime(mockRuntimeAI, hooks), mockRuntimeAI };
+ };
+
+ const chatPayload: ChatStreamPayload = {
+ messages: [{ role: 'user', content: 'hi' }],
+ model: 'gpt-4',
+ temperature: 0,
+ };
+
+ const genObjPayload = {
+ messages: [{ role: 'user' as const, content: 'gen' }],
+ model: 'gpt-4',
+ schema: { name: 'test', schema: { type: 'object' as const, properties: {} } },
+ };
+
+ describe('chat hooks', () => {
+ it('beforeChat is called before runtime.chat', async () => {
+ const beforeChat = vi.fn();
+ const { runtime, mockRuntimeAI } = createMockRuntime({ beforeChat });
+ mockRuntimeAI.chat.mockResolvedValue(new Response(''));
+
+ await runtime.chat(chatPayload);
+
+ expect(beforeChat).toHaveBeenCalledWith(chatPayload, undefined);
+ expect(mockRuntimeAI.chat).toHaveBeenCalled();
+ });
+
+ it('beforeChat throwing aborts chat call', async () => {
+ const beforeChat = vi.fn().mockRejectedValue(new Error('budget exceeded'));
+ const { runtime, mockRuntimeAI } = createMockRuntime({ beforeChat });
+
+ await expect(runtime.chat(chatPayload)).rejects.toThrow('budget exceeded');
+ expect(mockRuntimeAI.chat).not.toHaveBeenCalled();
+ });
+
+ it('onChatFinal is injected into callback chain, existing onFinal called first', async () => {
+ const callOrder: string[] = [];
+ const existingOnFinal = vi.fn().mockImplementation(() => callOrder.push('existing'));
+ const onChatFinal = vi.fn().mockImplementation(() => callOrder.push('hook'));
+ const { runtime, mockRuntimeAI } = createMockRuntime({ onChatFinal });
+
+ mockRuntimeAI.chat.mockImplementation(async (_p: any, opts: any) => {
+ await opts?.callback?.onFinal?.({ id: 'msg-1', text: 'hello' });
+ return new Response('');
+ });
+
+ await runtime.chat(chatPayload, { callback: { onFinal: existingOnFinal } });
+
+ expect(existingOnFinal).toHaveBeenCalled();
+ expect(onChatFinal).toHaveBeenCalled();
+ expect(callOrder).toEqual(['existing', 'hook']);
+ });
+
+ it('onChatFinal receives data and context', async () => {
+ const onChatFinal = vi.fn();
+ const { runtime, mockRuntimeAI } = createMockRuntime({ onChatFinal });
+ const options = { callback: {} };
+ const finalData = { id: 'msg-1', text: 'hello' };
+
+ mockRuntimeAI.chat.mockImplementation(async (_p: any, opts: any) => {
+ await opts?.callback?.onFinal?.(finalData);
+ return new Response('');
+ });
+
+ await runtime.chat(chatPayload, options);
+
+ expect(onChatFinal).toHaveBeenCalledWith(finalData, {
+ options,
+ payload: chatPayload,
+ });
+ });
+
+ it('onChatError is called when chat throws, error is re-thrown', async () => {
+ const chatError = { errorType: 'ProviderBizError', error: new Error('fail') };
+ const onChatError = vi.fn();
+ const { runtime, mockRuntimeAI } = createMockRuntime({ onChatError });
+ mockRuntimeAI.chat.mockRejectedValue(chatError);
+
+ await expect(runtime.chat(chatPayload)).rejects.toBe(chatError);
+ expect(onChatError).toHaveBeenCalledWith(chatError, {
+ options: undefined,
+ payload: chatPayload,
+ });
+ });
+
+ it('works without hooks (undefined)', async () => {
+ const { runtime, mockRuntimeAI } = createMockRuntime(undefined);
+ mockRuntimeAI.chat.mockResolvedValue(new Response(''));
+
+ await expect(runtime.chat(chatPayload)).resolves.toBeInstanceOf(Response);
+ });
+ });
+
+ describe('generateObject hooks', () => {
+ it('beforeGenerateObject is called before runtime.generateObject', async () => {
+ const beforeGenerateObject = vi.fn();
+ const { runtime, mockRuntimeAI } = createMockRuntime({ beforeGenerateObject });
+ mockRuntimeAI.generateObject.mockResolvedValue({ result: 'ok' });
+
+ await runtime.generateObject(genObjPayload);
+
+ expect(beforeGenerateObject).toHaveBeenCalledWith(genObjPayload, undefined);
+ expect(mockRuntimeAI.generateObject).toHaveBeenCalled();
+ });
+
+ it('beforeGenerateObject throwing aborts generateObject call', async () => {
+ const beforeGenerateObject = vi.fn().mockRejectedValue(new Error('budget exceeded'));
+ const { runtime, mockRuntimeAI } = createMockRuntime({ beforeGenerateObject });
+
+ await expect(runtime.generateObject(genObjPayload)).rejects.toThrow('budget exceeded');
+ expect(mockRuntimeAI.generateObject).not.toHaveBeenCalled();
+ });
+
+ it('onGenerateObjectFinal wraps onUsage, existing onUsage called first', async () => {
+ const callOrder: string[] = [];
+ const existingOnUsage = vi.fn().mockImplementation(() => callOrder.push('existing'));
+ const onGenerateObjectFinal = vi.fn().mockImplementation(() => callOrder.push('hook'));
+ const { runtime, mockRuntimeAI } = createMockRuntime({ onGenerateObjectFinal });
+ const usage = { totalTokens: 100, promptTokens: 50, completionTokens: 50 };
+
+ mockRuntimeAI.generateObject.mockImplementation(async (_p: any, opts: any) => {
+ await opts?.onUsage?.(usage);
+ return { result: 'ok' };
+ });
+
+ await runtime.generateObject(genObjPayload, { onUsage: existingOnUsage });
+
+ expect(existingOnUsage).toHaveBeenCalledWith(usage);
+ expect(onGenerateObjectFinal).toHaveBeenCalled();
+ expect(callOrder).toEqual(['existing', 'hook']);
+ });
+
+ it('onGenerateObjectError is called when generateObject throws, error is re-thrown', async () => {
+ const genError = { errorType: 'ProviderBizError', error: new Error('fail') };
+ const onGenerateObjectError = vi.fn();
+ const { runtime, mockRuntimeAI } = createMockRuntime({ onGenerateObjectError });
+ mockRuntimeAI.generateObject.mockRejectedValue(genError);
+
+ await expect(runtime.generateObject(genObjPayload)).rejects.toBe(genError);
+ expect(onGenerateObjectError).toHaveBeenCalledWith(genError, {
+ options: undefined,
+ payload: genObjPayload,
+ });
+ });
+
+ it('works without hooks (undefined)', async () => {
+ const { runtime, mockRuntimeAI } = createMockRuntime(undefined);
+ mockRuntimeAI.generateObject.mockResolvedValue({ result: 'ok' });
+
+ await expect(runtime.generateObject(genObjPayload)).resolves.toEqual({ result: 'ok' });
+ });
+ });
+ });
});
diff --git a/packages/model-runtime/src/core/ModelRuntime.ts b/packages/model-runtime/src/core/ModelRuntime.ts
index 6311079021e..1e6cad62744 100644
--- a/packages/model-runtime/src/core/ModelRuntime.ts
+++ b/packages/model-runtime/src/core/ModelRuntime.ts
@@ -1,4 +1,4 @@
-import type { TracePayload } from '@lobechat/types';
+import type { ModelUsage, TracePayload } from '@lobechat/types';
import type { ClientOptions } from 'openai';
import type { LobeBedrockAIParams } from '../providers/bedrock';
@@ -6,12 +6,15 @@ import type { LobeCloudflareParams } from '../providers/cloudflare';
import { LobeOpenAI } from '../providers/openai';
import { providerRuntimeMap } from '../runtimeMap';
import type {
+ ChatCompletionErrorPayload,
ChatMethodOptions,
ChatStreamPayload,
EmbeddingsOptions,
EmbeddingsPayload,
+ GenerateObjectOptions,
GenerateObjectPayload,
ModelRequestOptions,
+ OnFinishData,
PullModelParams,
TextToSpeechPayload,
} from '../types';
@@ -27,11 +30,51 @@ export interface AgentChatOptions {
trace?: TracePayload;
}
+export interface ModelRuntimeHooks {
+ /**
+ * Runs before the LLM call. Throw to abort (e.g., budget exceeded).
+ */
+ beforeChat?: (payload: ChatStreamPayload, options?: ChatMethodOptions) => Promise<void>;
+ beforeGenerateObject?: (
+ payload: GenerateObjectPayload,
+ options?: GenerateObjectOptions,
+ ) => Promise<void>;
+ /**
+ * Called when chat() throws. Handle side effects (sanitize, log, DB record).
+ * The error is re-thrown after the hook completes — callers still handle response formatting.
+ */
+ onChatError?: (
+ error: ChatCompletionErrorPayload,
+ context: { options?: ChatMethodOptions; payload: ChatStreamPayload },
+ ) => void | Promise<void>;
+
+ /**
+ * Called after the stream completes. ModelRuntime handles merging into onFinal internally.
+ * Hook consumers only need to implement the callback — no need to deal with option merging.
+ */
+ onChatFinal?: (
+ data: OnFinishData,
+ context: { options?: ChatMethodOptions; payload: ChatStreamPayload },
+ ) => void | Promise<void>;
+
+ onGenerateObjectError?: (
+ error: ChatCompletionErrorPayload,
+ context: { options?: GenerateObjectOptions; payload: GenerateObjectPayload },
+ ) => void | Promise<void>;
+
+ onGenerateObjectFinal?: (
+ data: { usage?: ModelUsage },
+ context: { options?: GenerateObjectOptions; payload: GenerateObjectPayload },
+ ) => void | Promise<void>;
+}
+
export class ModelRuntime {
+ private _hooks?: ModelRuntimeHooks;
private _runtime: LobeRuntimeAI;
- constructor(runtime: LobeRuntimeAI) {
+ constructor(runtime: LobeRuntimeAI, hooks?: ModelRuntimeHooks) {
this._runtime = runtime;
+ this._hooks = hooks;
}
/**
@@ -72,11 +115,77 @@ export class ModelRuntime {
});
}
- return this._runtime.chat(payload, options);
+ const finalOptions = await this.applyHooks(payload, options);
+
+ try {
+ return await this._runtime.chat(payload, finalOptions);
+ } catch (error) {
+ if (this._hooks?.onChatError) {
+ await this._hooks.onChatError(error as ChatCompletionErrorPayload, { options, payload });
+ }
+ throw error;
+ }
}
- async generateObject(payload: GenerateObjectPayload) {
- return this._runtime.generateObject!(payload);
+ /**
+ * Apply lifecycle hooks: beforeChat (budget check) + onChatFinal (cost tracking callback injection).
+ */
+ private async applyHooks(
+ payload: ChatStreamPayload,
+ options?: ChatMethodOptions,
+ ): Promise<ChatMethodOptions | undefined> {
+ await this._hooks?.beforeChat?.(payload, options);
+
+ if (!this._hooks?.onChatFinal) return options;
+
+ const hookFn = this._hooks.onChatFinal;
+ const existingOnFinal = options?.callback?.onFinal;
+ return {
+ ...options,
+ callback: {
+ ...options?.callback,
+ async onFinal(data) {
+ await existingOnFinal?.(data);
+ try {
+ await hookFn(data, { options, payload });
+ } catch (e) {
+ // Hook failures (billing, tracing) must not interfere with response completion
+ console.error('[ModelRuntime] onChatFinal hook error:', e);
+ }
+ },
+ },
+ };
+ }
+
+ async generateObject(payload: GenerateObjectPayload, options?: GenerateObjectOptions) {
+ await this._hooks?.beforeGenerateObject?.(payload, options);
+
+ const finalOptions = this._hooks?.onGenerateObjectFinal
+ ? {
+ ...options,
+ onUsage: async (usage: ModelUsage) => {
+ await options?.onUsage?.(usage);
+ try {
+ await this._hooks!.onGenerateObjectFinal!({ usage }, { options, payload });
+ } catch (e) {
+ // Hook failures (billing, tracing) must not interfere with response completion
+ console.error('[ModelRuntime] onGenerateObjectFinal hook error:', e);
+ }
+ },
+ }
+ : options;
+
+ try {
+ return await this._runtime.generateObject!(payload, finalOptions);
+ } catch (error) {
+ if (this._hooks?.onGenerateObjectError) {
+ await this._hooks.onGenerateObjectError(error as ChatCompletionErrorPayload, {
+ options,
+ payload,
+ });
+ }
+ throw error;
+ }
}
async createImage(payload: CreateImagePayload) {
@@ -117,6 +226,7 @@ export class ModelRuntime {
* @description Initialize the runtime with the provider and the options
* @param provider choose a model provider
* @param params options of the choosed provider
+ * @param hooks optional hooks for lifecycle interception (billing, etc.)
* @returns the runtime instance
* Try to initialize the runtime with the provider and the options.
* @example
@@ -135,12 +245,13 @@ export class ModelRuntime {
LobeBedrockAIParams &
LobeCloudflareParams & { apiKey?: string; apiVersion?: string; baseURL?: string }
>,
+ hooks?: ModelRuntimeHooks,
) {
// @ts-expect-error runtime map not include vertex so it will be undefined
const providerAI = providerRuntimeMap[provider] ?? LobeOpenAI;
const runtimeModel: LobeRuntimeAI = new providerAI(params);
- return new ModelRuntime(runtimeModel);
+ return new ModelRuntime(runtimeModel, hooks);
}
}
diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.ts
index 2dafd9f77de..343811e2b3a 100644
--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.ts
+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.ts
@@ -228,6 +228,50 @@ describe('Anthropic generateObject', () => {
expect(result).toBeUndefined();
});
+ it('should call onUsage callback with usage data', async () => {
+ const mockClient = {
+ messages: {
+ create: vi.fn().mockResolvedValue({
+ content: [
+ {
+ input: { data: 'test' },
+ name: 'test_tool',
+ type: 'tool_use',
+ },
+ ],
+ usage: {
+ cache_creation_input_tokens: 0,
+ cache_read_input_tokens: 0,
+ input_tokens: 100,
+ output_tokens: 50,
+ },
+ }),
+ },
+ };
+
+ const payload = {
+ messages: [{ content: 'Generate data', role: 'user' as const }],
+ model: 'claude-3-5-sonnet-20241022',
+ schema: {
+ name: 'test_tool',
+ schema: { properties: { data: { type: 'string' } }, type: 'object' as const },
+ },
+ };
+
+ const onUsage = vi.fn();
+ const result = await createAnthropicGenerateObject(mockClient as any, payload, { onUsage });
+
+ expect(onUsage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ inputCacheMissTokens: 100,
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150,
+ }),
+ );
+ expect(result).toEqual({ data: 'test' });
+ });
+
it('should handle complex nested schemas', async () => {
const mockClient = {
messages: {
diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts
index e4738dd586d..348cc74c379 100644
--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts
+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts
@@ -1,8 +1,11 @@
import type Anthropic from '@anthropic-ai/sdk';
import debug from 'debug';
+import type { Pricing } from 'model-bank';
import type { GenerateObjectOptions, GenerateObjectPayload } from '../../types';
import { buildAnthropicMessages, buildAnthropicTools } from '../contextBuilders/anthropic';
+import { buildAnthropicInitialUsage } from '../usageConverters/anthropic';
+import { withUsageCost } from '../usageConverters/utils/withUsageCost';
const log = debug('lobe-model-runtime:anthropic:generate-object');
@@ -13,6 +16,7 @@ export const createAnthropicGenerateObject = async (
client: Anthropic,
payload: GenerateObjectPayload,
options?: GenerateObjectOptions,
+ pricing?: Pricing,
) => {
const { schema, messages, model, tools } = payload;
@@ -78,6 +82,11 @@ export const createAnthropicGenerateObject = async (
log('received response with %d content blocks', response.content.length);
log('response: %O', response);
+ const initialUsage = buildAnthropicInitialUsage(response.usage);
+ if (initialUsage) {
+ await options?.onUsage?.(withUsageCost(initialUsage, pricing));
+ }
+
// Extract the tool use result
if (tool_choice.type === 'tool') {
const toolUseBlock = response.content.find(
diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
index 225ef6efd54..b32c2b4251c 100644
--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
@@ -3,6 +3,7 @@ import type { Stream } from '@anthropic-ai/sdk/streaming';
import { CURRENT_VERSION } from '@lobechat/const';
import type { ChatModelCard } from '@lobechat/types';
import debug from 'debug';
+import type { Pricing } from 'model-bank';
import type {
ChatCompletionErrorPayload,
@@ -89,6 +90,7 @@ export interface AnthropicCompatibleFactoryOptions<T extends Record<string, any>
client: Anthropic,
payload: GenerateObjectPayload,
options?: GenerateObjectOptions,
+ pricing?: Pricing,
) => Promise<any>;
models?: (params: {
apiKey?: string;
@@ -616,7 +618,8 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =
}
try {
- return await generateObject(this.client, payload, options);
+ const pricing = await getModelPricing(payload.model, this.id);
+ return await generateObject(this.client, payload, options, pricing);
} 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 2fbf2fa473b..835e279422c 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
@@ -47,6 +47,8 @@ import { convertOpenAIMessages, convertOpenAIResponseInputs } from '../contextBu
import { resolveModelSamplingParameters } from '../parameterResolver';
import type { OpenAIStreamOptions } from '../streams';
import { OpenAIResponsesStream, OpenAIStream } from '../streams';
+import type { ChatPayloadForTransformStream } from '../streams/protocol';
+import { convertOpenAIResponseUsage, convertOpenAIUsage } from '../usageConverters/openai';
import { createOpenAICompatibleImage } from './createImage';
import { transformResponseAPIToStream, transformResponseToStream } from './nonStreamToStream';
@@ -661,9 +663,12 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
!!schema,
);
+ const pricing = await getModelPricing(model, this.id);
+ const usagePayload = { model, pricing, provider: this.id };
+
if (tools) {
log('using tools-based generation');
- return this.generateObjectWithTools(payload, options);
+ return this.generateObjectWithTools(payload, options, usagePayload);
}
if (!schema) throw new Error('tools or schema is required');
@@ -699,6 +704,10 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
{ headers: options?.headers, signal: options?.signal },
);
+ if (res.usage) {
+ await options?.onUsage?.(convertOpenAIUsage(res.usage, usagePayload));
+ }
+
const toolCalls = res.choices[0].message.tool_calls!;
try {
@@ -748,6 +757,10 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
{ headers: options?.headers, signal: options?.signal },
);
+ if (res.usage) {
+ await options?.onUsage?.(convertOpenAIResponseUsage(res.usage, usagePayload));
+ }
+
const text = res.output_text;
log('received structured output from Responses API, length: %d', text?.length || 0);
try {
@@ -771,6 +784,10 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
},
{ headers: options?.headers, signal: options?.signal },
);
+ if (res.usage) {
+ await options?.onUsage?.(convertOpenAIUsage(res.usage, usagePayload));
+ }
+
const text = res.choices[0].message.content!;
log('received structured output from Chat Completions API, length: %d', text?.length || 0);
@@ -1082,6 +1099,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
private async generateObjectWithTools(
payload: GenerateObjectPayload,
options?: GenerateObjectOptions,
+ usagePayload?: ChatPayloadForTransformStream,
) {
const { messages, model, tools, responseApi } = payload;
const log = debug(`${this.logPrefix}:generateObject`);
@@ -1129,6 +1147,10 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
{ headers: options?.headers, signal: options?.signal },
);
+ if (res.usage) {
+ await options?.onUsage?.(convertOpenAIResponseUsage(res.usage, usagePayload));
+ }
+
const functionCalls = res.output?.filter((item: any) => item.type === 'function_call');
log('received %d function calls from Responses API', functionCalls?.length || 0);
@@ -1165,6 +1187,10 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
{ headers: options?.headers, signal: options?.signal },
);
+ if (res.usage) {
+ await options?.onUsage?.(convertOpenAIUsage(res.usage, usagePayload));
+ }
+
const toolCalls = res.choices[0].message.tool_calls!;
log('received %d tool calls from Chat Completions API', toolCalls?.length || 0);
diff --git a/packages/model-runtime/src/core/usageConverters/anthropic.test.ts b/packages/model-runtime/src/core/usageConverters/anthropic.test.ts
index 89740206a5b..a56cc6e0ec1 100644
--- a/packages/model-runtime/src/core/usageConverters/anthropic.test.ts
+++ b/packages/model-runtime/src/core/usageConverters/anthropic.test.ts
@@ -26,6 +26,7 @@ describe('convertAnthropicUsage', () => {
inputWriteCacheTokens: 20,
totalInputTokens: 130,
totalOutputTokens: 5,
+ totalTokens: 135,
});
});
diff --git a/packages/model-runtime/src/core/usageConverters/anthropic.ts b/packages/model-runtime/src/core/usageConverters/anthropic.ts
index fd23a0f73f8..e68c6e7fb9a 100644
--- a/packages/model-runtime/src/core/usageConverters/anthropic.ts
+++ b/packages/model-runtime/src/core/usageConverters/anthropic.ts
@@ -4,7 +4,7 @@ import type { ModelUsage } from '@lobechat/types';
import type { ChatPayloadForTransformStream } from '../streams/protocol';
import { withUsageCost } from './utils/withUsageCost';
-const buildInitialUsage = (
+export const buildAnthropicInitialUsage = (
usage: Anthropic.Messages.Usage | null | undefined,
): ModelUsage | undefined => {
if (!usage) return undefined;
@@ -18,12 +18,15 @@ const buildInitialUsage = (
(usage.cache_read_input_tokens || 0);
}
+ const totalOutputTokens = usage.output_tokens;
+
return {
inputCacheMissTokens: usage.input_tokens,
inputCachedTokens: usage.cache_read_input_tokens || undefined,
inputWriteCacheTokens: usage.cache_creation_input_tokens || undefined,
totalInputTokens,
- totalOutputTokens: usage.output_tokens,
+ totalOutputTokens,
+ totalTokens: totalInputTokens + totalOutputTokens,
} satisfies ModelUsage;
};
@@ -59,7 +62,7 @@ export const convertAnthropicUsage = (
): ModelUsage | undefined => {
switch (messageEvent.type) {
case 'message_start': {
- return buildInitialUsage(messageEvent.message.usage);
+ return buildAnthropicInitialUsage(messageEvent.message.usage);
}
case 'message_delta': {
const usage = mergeDeltaUsage(streamContextUsage, messageEvent.usage);
diff --git a/packages/model-runtime/src/core/usageConverters/index.ts b/packages/model-runtime/src/core/usageConverters/index.ts
index 16a3d378b3b..853ddd19888 100644
--- a/packages/model-runtime/src/core/usageConverters/index.ts
+++ b/packages/model-runtime/src/core/usageConverters/index.ts
@@ -1,4 +1,4 @@
-export { convertAnthropicUsage } from './anthropic';
+export { buildAnthropicInitialUsage, convertAnthropicUsage } from './anthropic';
export { convertGoogleAIUsage } from './google-ai';
export { convertOpenAIResponseUsage, convertOpenAIUsage } from './openai';
export { computeImageCost } from './utils/computeImageCost';
diff --git a/packages/model-runtime/src/index.ts b/packages/model-runtime/src/index.ts
index ab51ef57a67..1542a82865a 100644
--- a/packages/model-runtime/src/index.ts
+++ b/packages/model-runtime/src/index.ts
@@ -1,6 +1,7 @@
export * from './const/models';
export * from './core/BaseAI';
export { pruneReasoningPayload } from './core/contextBuilders/openai';
+export type { ModelRuntimeHooks } from './core/ModelRuntime';
export { ModelRuntime } from './core/ModelRuntime';
export { createOpenAICompatibleRuntime } from './core/openaiCompatibleFactory';
export * from './core/RouterRuntime';
diff --git a/packages/model-runtime/src/providers/google/generateObject.test.ts b/packages/model-runtime/src/providers/google/generateObject.test.ts
index d6a3c7cf7f8..916b8c715ad 100644
--- a/packages/model-runtime/src/providers/google/generateObject.test.ts
+++ b/packages/model-runtime/src/providers/google/generateObject.test.ts
@@ -272,6 +272,46 @@ describe('Google generateObject', () => {
expect(result).toEqual({ status: 'success' });
});
+ it('should call onUsage callback with usage data', async () => {
+ const mockClient = {
+ models: {
+ generateContent: vi.fn().mockResolvedValue({
+ text: '{"result": "ok"}',
+ usageMetadata: {
+ candidatesTokenCount: 20,
+ promptTokenCount: 80,
+ totalTokenCount: 100,
+ },
+ }),
+ },
+ };
+
+ const contents = [{ parts: [{ text: 'Generate data' }], role: 'user' }];
+
+ const payload = {
+ contents,
+ model: 'gemini-2.5-flash',
+ schema: {
+ name: 'test',
+ schema: {
+ properties: { result: { type: 'string' } },
+ type: 'object' as const,
+ },
+ },
+ };
+
+ const onUsage = vi.fn();
+ const result = await createGoogleGenerateObject(mockClient as any, payload, { onUsage });
+
+ expect(onUsage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ totalInputTokens: 80,
+ totalOutputTokens: 20,
+ }),
+ );
+ expect(result).toEqual({ result: 'ok' });
+ });
+
it('should return undefined when JSON parsing fails', async () => {
const mockClient = {
models: {
@@ -504,6 +544,68 @@ describe('Google generateObject', () => {
]);
});
+ it('should call onUsage callback with usage data', async () => {
+ const mockClient = {
+ models: {
+ generateContent: vi.fn().mockResolvedValue({
+ candidates: [
+ {
+ content: {
+ parts: [
+ {
+ functionCall: {
+ args: { city: 'Tokyo' },
+ name: 'get_weather',
+ },
+ },
+ ],
+ },
+ },
+ ],
+ usageMetadata: {
+ candidatesTokenCount: 30,
+ promptTokenCount: 70,
+ totalTokenCount: 100,
+ },
+ }),
+ },
+ };
+
+ const contents = [{ parts: [{ text: 'What is the weather in Tokyo?' }], role: 'user' }];
+
+ const payload = {
+ contents,
+ model: 'gemini-2.5-flash',
+ tools: [
+ {
+ function: {
+ description: 'Get weather information',
+ name: 'get_weather',
+ parameters: {
+ properties: { city: { type: 'string' } },
+ required: ['city'],
+ type: 'object' as const,
+ },
+ },
+ type: 'function' as const,
+ },
+ ],
+ };
+
+ const onUsage = vi.fn();
+ const result = await createGoogleGenerateObjectWithTools(mockClient as any, payload, {
+ onUsage,
+ });
+
+ expect(onUsage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ totalInputTokens: 70,
+ totalOutputTokens: 30,
+ }),
+ );
+ expect(result).toEqual([{ arguments: { city: 'Tokyo' }, name: 'get_weather' }]);
+ });
+
it('should handle multiple function calls', async () => {
const mockClient = {
models: {
diff --git a/packages/model-runtime/src/providers/google/generateObject.ts b/packages/model-runtime/src/providers/google/generateObject.ts
index f9698625a7d..e9e4c04901e 100644
--- a/packages/model-runtime/src/providers/google/generateObject.ts
+++ b/packages/model-runtime/src/providers/google/generateObject.ts
@@ -1,8 +1,10 @@
import type { GenerateContentConfig, GoogleGenAI } from '@google/genai';
import { FunctionCallingConfigMode, Type as SchemaType } from '@google/genai';
import Debug from 'debug';
+import type { Pricing } from 'model-bank';
import { buildGoogleTool } from '../../core/contextBuilders/google';
+import { convertGoogleAIUsage } from '../../core/usageConverters/google-ai';
import type { ChatCompletionTool, GenerateObjectOptions, GenerateObjectSchema } from '../../types';
const debug = Debug('lobe-mode-runtime:google:generateObject');
@@ -109,6 +111,7 @@ export const createGoogleGenerateObject = async (
schema: GenerateObjectSchema;
},
options?: GenerateObjectOptions,
+ pricing?: Pricing,
) => {
const { schema, contents, model } = payload;
@@ -165,6 +168,10 @@ export const createGoogleGenerateObject = async (
debug('API response received', { hasText: !!response.text, textLength: response.text?.length });
+ if (response.usageMetadata) {
+ await options?.onUsage?.(convertGoogleAIUsage(response.usageMetadata, pricing));
+ }
+
const text = response.text;
try {
@@ -190,6 +197,7 @@ export const createGoogleGenerateObjectWithTools = async (
tools: ChatCompletionTool[];
},
options?: GenerateObjectOptions,
+ pricing?: Pricing,
) => {
const { tools, contents, model } = payload;
@@ -251,6 +259,10 @@ export const createGoogleGenerateObjectWithTools = async (
hasContent: !!response.candidates?.[0]?.content,
});
+ if (response.usageMetadata) {
+ await options?.onUsage?.(convertGoogleAIUsage(response.usageMetadata, pricing));
+ }
+
// Extract function calls from response
const candidate = response.candidates?.[0];
if (!candidate?.content?.parts) {
diff --git a/packages/model-runtime/src/providers/google/index.ts b/packages/model-runtime/src/providers/google/index.ts
index fe1b855e17b..18db79acf65 100644
--- a/packages/model-runtime/src/providers/google/index.ts
+++ b/packages/model-runtime/src/providers/google/index.ts
@@ -44,9 +44,7 @@ const modelsWithModalities = new Set([
'nano-banana-pro-preview',
]);
-const modelsWithImageSearch = new Set([
- 'gemini-3.1-flash-image-preview',
-]);
+const modelsWithImageSearch = new Set(['gemini-3.1-flash-image-preview']);
const modelsDisableInstuction = new Set([
'gemini-2.0-flash-exp',
@@ -281,6 +279,7 @@ export class LobeGoogleAI implements LobeRuntimeAI {
async generateObject(payload: GenerateObjectPayload, options?: GenerateObjectOptions) {
// Convert OpenAI messages to Google format
const contents = await buildGoogleMessages(payload.messages);
+ const pricing = await getModelPricing(payload.model, this.provider);
// Handle tools-based structured output
if (payload.tools && payload.tools.length > 0) {
@@ -288,6 +287,7 @@ export class LobeGoogleAI implements LobeRuntimeAI {
this.client,
{ contents, model: payload.model, tools: payload.tools },
options,
+ pricing,
);
}
@@ -297,6 +297,7 @@ export class LobeGoogleAI implements LobeRuntimeAI {
this.client,
{ contents, model: payload.model, schema: payload.schema },
options,
+ pricing,
);
}
diff --git a/packages/model-runtime/src/types/chat.ts b/packages/model-runtime/src/types/chat.ts
index ea8286d2231..6116ceff1f2 100644
--- a/packages/model-runtime/src/types/chat.ts
+++ b/packages/model-runtime/src/types/chat.ts
@@ -174,6 +174,8 @@ export interface ChatMethodOptions {
* response headers
*/
headers?: Record<string, any>;
+ /** Metadata passed to hooks (billing, tracing, etc.) */
+ metadata?: Record<string, unknown>;
/**
* send the request to the ai api endpoint
*/
diff --git a/packages/model-runtime/src/types/structureOutput.ts b/packages/model-runtime/src/types/structureOutput.ts
index a142d22b0eb..6de7ba397e3 100644
--- a/packages/model-runtime/src/types/structureOutput.ts
+++ b/packages/model-runtime/src/types/structureOutput.ts
@@ -1,3 +1,5 @@
+import type { ModelUsage } from '@lobechat/types';
+
import type { ChatCompletionTool } from './chat';
interface GenerateObjectMessage {
@@ -32,6 +34,8 @@ export interface GenerateObjectOptions {
*/
headers?: Record<string, any>;
+ onUsage?: (usage: ModelUsage) => void | Promise<void>;
+
signal?: AbortSignal;
/**
* userId for the GenerateObject
diff --git a/packages/openapi/src/services/chat.service.ts b/packages/openapi/src/services/chat.service.ts
index 470b69a1982..fecb1e48ed7 100644
--- a/packages/openapi/src/services/chat.service.ts
+++ b/packages/openapi/src/services/chat.service.ts
@@ -2,6 +2,7 @@ import type { ChatStreamPayload } from '@lobechat/model-runtime';
import type { LobeAgentChatConfig, LobeAgentConfig, UserSystemAgentConfig } from '@lobechat/types';
import { and, eq } from 'drizzle-orm';
+import { getBusinessModelRuntimeHooks } from '@/business/server/model-runtime';
import { DEFAULT_AGENT_CHAT_CONFIG, DEFAULT_SYSTEM_AGENT_CONFIG } from '@/const/settings';
import { UserModel } from '@/database/models/user';
import { agents, agentsToSessions, aiModels } from '@/database/schemas';
@@ -317,10 +318,13 @@ export class ChatService extends BaseService {
const { apiKey } = JSON.parse(await this.getApiKey(provider));
// 创建 AgentRuntime 实例
- const modelRuntime = await initModelRuntimeWithUserPayload(provider, {
- apiKey,
- userId: this.userId!,
- });
+ const hooks = getBusinessModelRuntimeHooks(this.userId!, provider);
+ const modelRuntime = await initModelRuntimeWithUserPayload(
+ provider,
+ { apiKey, userId: this.userId! },
+ {},
+ hooks,
+ );
// 构建 ChatStreamPayload
const chatPayload: ChatStreamPayload = {
diff --git a/src/business/server/model-runtime.ts b/src/business/server/model-runtime.ts
new file mode 100644
index 00000000000..b1ca38f8812
--- /dev/null
+++ b/src/business/server/model-runtime.ts
@@ -0,0 +1,8 @@
+import type { ModelRuntimeHooks } from '@lobechat/model-runtime';
+
+export function getBusinessModelRuntimeHooks(
+ _userId: string,
+ _provider: string,
+): ModelRuntimeHooks | undefined {
+ return undefined;
+}
diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.ts
index a90b11cd326..00b52045bf4 100644
--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts
+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts
@@ -402,6 +402,10 @@ export const createRuntimeExecutors = (
console.error(`[${operationLogId}][stream_error]`, errorData);
},
},
+ metadata: {
+ operationId,
+ topicId: state.metadata?.topicId,
+ },
user: ctx.userId,
});
diff --git a/src/server/modules/ModelRuntime/index.ts b/src/server/modules/ModelRuntime/index.ts
index f3fec3aaffe..6d40a94b1c0 100644
--- a/src/server/modules/ModelRuntime/index.ts
+++ b/src/server/modules/ModelRuntime/index.ts
@@ -1,5 +1,5 @@
import { type GoogleGenAIOptions } from '@google/genai';
-import { ModelRuntime } from '@lobechat/model-runtime';
+import { ModelRuntime, type ModelRuntimeHooks } from '@lobechat/model-runtime';
import { LobeVertexAI } from '@lobechat/model-runtime/vertexai';
import {
type AWSBedrockKeyVault,
@@ -14,6 +14,7 @@ import {
import { safeParseJSON } from '@lobechat/utils';
import { ModelProvider } from 'model-bank';
+import { getBusinessModelRuntimeHooks } from '@/business/server/model-runtime';
import { AiProviderModel } from '@/database/models/aiProvider';
import { type LobeChatDatabase } from '@/database/type';
import { getLLMConfig } from '@/envs/llm';
@@ -357,6 +358,7 @@ export const initModelRuntimeWithUserPayload = (
provider: string,
payload: ClientSecretPayload,
params: any = {},
+ hooks?: ModelRuntimeHooks,
) => {
const runtimeProvider = payload.runtimeProvider ?? provider;
@@ -364,13 +366,17 @@ export const initModelRuntimeWithUserPayload = (
const vertexOptions = buildVertexOptions(payload, params);
const runtime = LobeVertexAI.initFromVertexAI(vertexOptions);
- return new ModelRuntime(runtime);
+ return new ModelRuntime(runtime, hooks);
}
- return ModelRuntime.initializeWithProvider(runtimeProvider, {
- ...getParamsFromPayload(runtimeProvider, payload),
- ...params,
- });
+ return ModelRuntime.initializeWithProvider(
+ runtimeProvider,
+ {
+ ...getParamsFromPayload(runtimeProvider, payload),
+ ...params,
+ },
+ hooks,
+ );
};
/**
@@ -415,6 +421,9 @@ export const initModelRuntimeFromDB = async (
const keyVaults = (providerConfig?.keyVaults || {}) as ProviderKeyVaults;
const payload = buildPayloadFromKeyVaults(keyVaults, runtimeProvider);
- // 4. Initialize ModelRuntime with the payload
- return initModelRuntimeWithUserPayload(provider, payload);
+ // 4. Get business hooks (billing in cloud, undefined in OSS)
+ const hooks = getBusinessModelRuntimeHooks(userId, provider);
+
+ // 5. Initialize ModelRuntime with the payload and hooks
+ return initModelRuntimeWithUserPayload(provider, payload, {}, hooks);
};