🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(model-runtime): attribute non-chat usage to its route attempt (#22158)
YuTengjingee1f0d806cf9
diff --git a/apps/server/src/router-hono/webhooks/handlers/video.ts b/apps/server/src/router-hono/webhooks/handlers/video.tsindex 5c5735bca3c..91c56096d50 100644--- a/apps/server/src/router-hono/webhooks/handlers/video.ts+++ b/apps/server/src/router-hono/webhooks/handlers/video.ts@@ -352,6 +352,7 @@ export const videoWebhook = async (c: Context<BlankEnv, '/video/:provider'>) =>model: resolvedModelId,prechargeResult: metadata?.precharge as any,provider,+ route: metadata?.route,usage: result.usage ?? measureVideoOutputUsage(resolvedModelId, processResult),userId: asyncTask.userId,workspaceId: asyncTask.workspaceId ?? undefined,diff --git a/apps/server/src/routers/async/image.ts b/apps/server/src/routers/async/image.tsindex 1395eb2d20c..3bfb46b87d0 100644--- a/apps/server/src/routers/async/image.ts+++ b/apps/server/src/routers/async/image.ts@@ -4,7 +4,7 @@ import {buildMappedBusinessModelFields,resolveBusinessModelMapping,} from '@lobechat/business-model-runtime';-import { type CreateImageMethodOptions } from '@lobechat/model-runtime';+import { type CreateImageMethodOptions, readRouteAttemptIdentity } from '@lobechat/model-runtime';import { AsyncTaskError, AsyncTaskStatus, RequestTrigger, type SpendOrigin } from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';@@ -301,6 +301,7 @@ export const imageRouter = router({// into the outer catch and be reconciled as a generation failure.try {await chargeAfterGenerate({+ computePriceParams: params,metrics: { latency: duration },metadata: {...spendOrigin,@@ -317,6 +318,7 @@ export const imageRouter = router({prechargeResult,pricingContext: runtimeOptions.pricingContext,provider,+ routeAttempt: readRouteAttemptIdentity(runtimeOptions.metadata),userId: ctx.userId,workspaceId,});diff --git a/apps/server/src/routers/lambda/video/index.ts b/apps/server/src/routers/lambda/video/index.tsindex 42b96b81137..a61821c628d 100644--- a/apps/server/src/routers/lambda/video/index.ts+++ b/apps/server/src/routers/lambda/video/index.ts@@ -59,14 +59,13 @@ const getVideoGenerationRoute = (value: unknown): VideoGenerationRoute | undefinreturn {apiType: value.apiType,+ ...(typeof value.attemptId === 'string' ? { attemptId: value.attemptId } : {}),...(typeof value.channelId === 'string' ? { channelId: value.channelId } : {}),...(typeof value.routerId === 'string' ? { routerId: value.routerId } : {}),};};-type ChargeErrorBatch = NonNullable<- Awaited<ReturnType<typeof chargeBeforeGenerate>>['errorBatch']->;+type ChargeErrorBatch = NonNullable<Awaited<ReturnType<typeof chargeBeforeGenerate>>['errorBatch']>;/*** An error batch (insufficient budget, frozen workspace, …) links each generation todiff --git a/apps/server/src/services/generation/videoBackgroundPolling.ts b/apps/server/src/services/generation/videoBackgroundPolling.tsindex d3bddf2988d..bd527c62892 100644--- a/apps/server/src/services/generation/videoBackgroundPolling.ts+++ b/apps/server/src/services/generation/videoBackgroundPolling.ts@@ -178,6 +178,7 @@ export async function processBackgroundVideoPolling(model: resolvedModelId,prechargeResult,provider,+ route,usage: pollResult.usage ?? measureVideoOutputUsage(resolvedModelId, processResult),userId,workspaceId,diff --git a/packages/business-server/src/image-generation/chargeAfterGenerate.ts b/packages/business-server/src/image-generation/chargeAfterGenerate.tsindex e8a2fd326ff..74c2237e5ee 100644--- a/packages/business-server/src/image-generation/chargeAfterGenerate.ts+++ b/packages/business-server/src/image-generation/chargeAfterGenerate.ts@@ -1,9 +1,9 @@-import { type ModelPricingContext } from '@lobechat/model-runtime';-import { type SpendOrigin } from '@lobechat/types';--import { type ModelPerformance, type ModelUsage } from '@/types/index';+import { type ModelPricingContext, type RouteAttemptIdentity } from '@lobechat/model-runtime';+import { type ModelPerformance, type ModelUsage, type SpendOrigin } from '@lobechat/types';interface ChargeParams {+ /** Generation params, to price fixed per-image models. */+ computePriceParams?: Record<string, unknown>;isError?: boolean;metadata: SpendOrigin & {asyncTaskId: string;@@ -17,6 +17,8 @@ interface ChargeParams {prechargeResult?: unknown;pricingContext?: ModelPricingContext;provider: string;+ /** Router attempt that generated the image; attributes the charge to its channel. */+ routeAttempt?: RouteAttemptIdentity;userId: string;workspaceId?: string;}diff --git a/packages/business-server/src/video-generation/chargeAfterGenerate.ts b/packages/business-server/src/video-generation/chargeAfterGenerate.tsindex 7ef2bded756..bd002fa70ea 100644--- a/packages/business-server/src/video-generation/chargeAfterGenerate.ts+++ b/packages/business-server/src/video-generation/chargeAfterGenerate.ts@@ -1,4 +1,4 @@-import { type SpendOrigin } from '@lobechat/types';+import { type SpendOrigin, type VideoGenerationRoute } from '@lobechat/types';interface ChargeParams {computePriceParams?: { duration?: number; generateAudio?: boolean; resolution?: string };@@ -14,6 +14,8 @@ interface ChargeParams {model: string;prechargeResult?: Record<string, unknown>;provider: string;+ /** Route that created the video; attributes the completion charge to its channel. */+ route?: VideoGenerationRoute;usage?: { completionTokens: number; totalTokens: number };userId: string;workspaceId?: string;diff --git a/packages/model-runtime/src/core/ModelRuntime.test.ts b/packages/model-runtime/src/core/ModelRuntime.test.tsindex eaed77fab88..e879482820b 100644--- a/packages/model-runtime/src/core/ModelRuntime.test.ts+++ b/packages/model-runtime/src/core/ModelRuntime.test.ts@@ -705,7 +705,7 @@ describe('ModelRuntime', () => {await runtime.generateObject(genObjPayload, { onUsage: existingOnUsage });- expect(existingOnUsage).toHaveBeenCalledWith(usage);+ expect(existingOnUsage).toHaveBeenCalledWith(usage, undefined);expect(onGenerateObjectFinal).toHaveBeenCalled();expect(callOrder).toEqual(['existing', 'hook']);});@@ -745,6 +745,26 @@ describe('ModelRuntime', () => {}});+ it('onGenerateObjectFinal receives the route attempt that reported the usage', async () => {+ const onGenerateObjectFinal = vi.fn();+ const existingOnUsage = vi.fn();+ const { runtime, mockRuntimeAI } = createMockRuntime({ onGenerateObjectFinal });+ const usage = { totalTokens: 10 };+ const routeAttempt = { attemptId: 'att-1', channelId: 'ch-1', requestId: 'req-1' };+ mockRuntimeAI.generateObject.mockImplementation(async (_p: any, opts: any) => {+ await opts?.onUsage?.(usage, { routeAttempt });+ return { result: 'ok' };+ });++ await runtime.generateObject(genObjPayload, { onUsage: existingOnUsage });++ expect(existingOnUsage).toHaveBeenCalledWith(usage, { routeAttempt });+ expect(onGenerateObjectFinal).toHaveBeenCalledWith(+ expect.objectContaining({ routeAttempt, usage }),+ expect.anything(),+ );+ });+it('onGenerateObjectError is called when generateObject throws, error is re-thrown', async () => {const genError = { errorType: 'ProviderBizError', error: new Error('fail') };const onGenerateObjectError = vi.fn();@@ -885,6 +905,43 @@ describe('ModelRuntime', () => {});});+ describe('route attempt attribution', () => {+ const routeAttempt = { attemptId: 'att-1', channelId: 'ch-1', requestId: 'req-1' };+ const usage = { cost: 0.001, totalTokens: 10 };++ it('passes the route attempt to onEmbeddingsFinal', async () => {+ const onEmbeddingsFinal = vi.fn();+ const { runtime, mockRuntimeAI } = createMockRuntime({ onEmbeddingsFinal });+ mockRuntimeAI.embeddings.mockImplementation(async (_p: any, opts: any) => {+ await opts?.onUsage?.(usage, { routeAttempt });+ return [[0.1]];+ });++ await runtime.embeddings({ input: 'hi', model: 'emb' });++ expect(onEmbeddingsFinal).toHaveBeenCalledWith(+ { latencyMs: expect.any(Number), routeAttempt, usage },+ expect.anything(),+ );+ });++ it('passes the route attempt to onTranscribeFinal', async () => {+ const onTranscribeFinal = vi.fn();+ const { runtime, mockRuntimeAI } = createMockRuntime({ onTranscribeFinal });+ mockRuntimeAI.transcribe.mockImplementation(async (_p: any, opts: any) => {+ await opts.onUsage(usage, { routeAttempt });+ return { text: 'hello' };+ });++ await runtime.transcribe({ file: new Blob([new Uint8Array([1])]), model: 'asr' });++ expect(onTranscribeFinal).toHaveBeenCalledWith(+ { latencyMs: expect.any(Number), routeAttempt, usage },+ expect.anything(),+ );+ });+ });+describe('transcribe hooks', () => {const transcribePayload = {file: new Blob([new Uint8Array([1, 2, 3])]),diff --git a/packages/model-runtime/src/core/ModelRuntime.textToSpeech.test.ts b/packages/model-runtime/src/core/ModelRuntime.textToSpeech.test.tsindex 9b77a258889..df77c0938f5 100644--- a/packages/model-runtime/src/core/ModelRuntime.textToSpeech.test.ts+++ b/packages/model-runtime/src/core/ModelRuntime.textToSpeech.test.ts@@ -69,7 +69,7 @@ describe('ModelRuntime textToSpeech', () => {mockRuntimeAI.textToSpeech.mock.invocationCallOrder[0],);// The caller's own onUsage still fires alongside the hook's capture.- expect(callerOnUsage).toHaveBeenCalledWith(usage);+ expect(callerOnUsage).toHaveBeenCalledWith(usage, undefined);expect(onTextToSpeechFinal).toHaveBeenCalledWith({ latencyMs: expect.any(Number), usage },{ options, payload: ttsPayload },diff --git a/packages/model-runtime/src/core/ModelRuntime.ts b/packages/model-runtime/src/core/ModelRuntime.tsindex 42a4bf16d7d..d304ccceeeb 100644--- a/packages/model-runtime/src/core/ModelRuntime.ts+++ b/packages/model-runtime/src/core/ModelRuntime.ts@@ -22,8 +22,10 @@ import type {ModelRequestOptions,OnFinishData,PullModelParams,+ RouteAttemptIdentity,TextToSpeechOptions,TextToSpeechPayload,+ UsageReportContext,} from '../types';import { AgentRuntimeErrorType } from '../types/error';import type {@@ -189,7 +191,7 @@ export interface ModelRuntimeHooks {) => void | Promise<void>;onEmbeddingsFinal?: (- data: { latencyMs?: number; usage?: ModelUsage },+ data: { latencyMs?: number; routeAttempt?: RouteAttemptIdentity; usage?: ModelUsage },context: { options?: EmbeddingsOptions; payload: EmbeddingsPayload },) => void | Promise<void>;@@ -218,7 +220,7 @@ export interface ModelRuntimeHooks {) => void | Promise<void>;onGenerateObjectFinal?: (- data: { speed?: ModelPerformance; usage?: ModelUsage },+ data: { routeAttempt?: RouteAttemptIdentity; speed?: ModelPerformance; usage?: ModelUsage },context: { options?: GenerateObjectOptions; payload: GenerateObjectPayload },) => void | Promise<void>;@@ -233,7 +235,7 @@ export interface ModelRuntimeHooks {* `beforeTextToSpeech`.*/onTextToSpeechFinal?: (- data: { latencyMs: number; usage?: ModelUsage },+ data: { latencyMs: number; routeAttempt?: RouteAttemptIdentity; usage?: ModelUsage },context: { options?: TextToSpeechOptions; payload: TextToSpeechPayload },) => void | Promise<void>;@@ -248,7 +250,7 @@ export interface ModelRuntimeHooks {* settle or release anything taken in `beforeTranscribe`.*/onTranscribeFinal?: (- data: { latencyMs: number; usage?: ModelUsage },+ data: { latencyMs: number; routeAttempt?: RouteAttemptIdentity; usage?: ModelUsage },context: { options?: ASROptions; payload: ASRPayload },) => void | Promise<void>;}@@ -497,12 +499,15 @@ export class ModelRuntime {const finalOptions = needsUsageCapture? {...hookOptions,- onUsage: async (usage: ModelUsage) => {+ onUsage: async (usage: ModelUsage, context?: UsageReportContext) => {usageCapture = usage;const speed = buildGenerateObjectSpeed(runtimeStartedAt, usage);- await hookOptions?.onUsage?.(usage);+ await hookOptions?.onUsage?.(usage, context);try {- await this._hooks?.onGenerateObjectFinal?.({ speed, usage }, { options, payload });+ await this._hooks?.onGenerateObjectFinal?.(+ { routeAttempt: context?.routeAttempt, speed, usage },+ { options, payload },+ );} catch (e) {// Hook failures (billing, tracing) must not interfere with response completionconsole.error('[ModelRuntime] onGenerateObjectFinal hook error:', e);@@ -577,11 +582,14 @@ export class ModelRuntime {const finalOptions = this._hooks?.onEmbeddingsFinal? {...hookOptions,- onUsage: async (usage: ModelUsage) => {- await hookOptions?.onUsage?.(usage);+ onUsage: async (usage: ModelUsage, context?: UsageReportContext) => {+ await hookOptions?.onUsage?.(usage, context);try {const latencyMs = Date.now() - startTime;- await this._hooks!.onEmbeddingsFinal!({ latencyMs, usage }, { options, payload });+ await this._hooks!.onEmbeddingsFinal!(+ { latencyMs, routeAttempt: context?.routeAttempt, usage },+ { options, payload },+ );} catch (e) {console.error('[ModelRuntime] onEmbeddingsFinal hook error:', e);}@@ -607,12 +615,14 @@ export class ModelRuntime {const startTime = Date.now();let usage: ModelUsage | undefined;+ let routeAttempt: RouteAttemptIdentity | undefined;const finalOptions = this._hooks?.onTextToSpeechFinal? {...hookOptions,- onUsage: async (reported: ModelUsage) => {+ onUsage: async (reported: ModelUsage, context?: UsageReportContext) => {usage = reported;- await hookOptions?.onUsage?.(reported);+ routeAttempt = context?.routeAttempt;+ await hookOptions?.onUsage?.(reported, context);},}: hookOptions;@@ -622,7 +632,7 @@ export class ModelRuntime {if (this._hooks?.onTextToSpeechFinal) {try {await this._hooks.onTextToSpeechFinal(- { latencyMs: Date.now() - startTime, usage },+ { latencyMs: Date.now() - startTime, routeAttempt, usage },{ options, payload },);} catch (e) {@@ -649,12 +659,14 @@ export class ModelRuntime {const startTime = Date.now();let usage: ModelUsage | undefined;+ let routeAttempt: RouteAttemptIdentity | undefined;const finalOptions = this._hooks?.onTranscribeFinal? {...hookOptions,- onUsage: async (reported: ModelUsage) => {+ onUsage: async (reported: ModelUsage, context?: UsageReportContext) => {usage = reported;- await hookOptions?.onUsage?.(reported);+ routeAttempt = context?.routeAttempt;+ await hookOptions?.onUsage?.(reported, context);},}: hookOptions;@@ -664,7 +676,7 @@ export class ModelRuntime {if (this._hooks?.onTranscribeFinal) {try {await this._hooks.onTranscribeFinal(- { latencyMs: Date.now() - startTime, usage },+ { latencyMs: Date.now() - startTime, routeAttempt, usage },{ options, payload },);} catch (e) {diff --git a/packages/model-runtime/src/core/RouterRuntime/attemptIdentity.ts b/packages/model-runtime/src/core/RouterRuntime/attemptIdentity.tsnew file mode 100644index 00000000000..493c3246359--- /dev/null+++ b/packages/model-runtime/src/core/RouterRuntime/attemptIdentity.ts@@ -0,0 +1,44 @@+import type { OnUsageCallback, RouteAttemptIdentity } from '../../types';+import type { RouteAttemptStart } from './routeAttempt';++/**+ * Written to `options.metadata.routeAttempt` once an attempt succeeds; read back with+ * `readRouteAttemptIdentity` by callers that bill after the method returns.+ */+export interface RouteAttemptMetadata {+ apiType: string;+ attemptId: string;+ channelId?: string;+ completionPending?: boolean;+ durationMs: number;+ optionIndex: number;+ providerId: string;+ requestId: string;+ routerId?: string;+ success: boolean;+ totalOptions: number;+}++/**+ * Tags the usage an attempt reports with that attempt's identity, so billing hooks know which+ * channel served it. Per attempt, because a failed attempt's usage must not inherit the identity+ * of the attempt that eventually succeeds.+ */+export const withAttemptUsage = <T extends { onUsage?: OnUsageCallback }>(+ options: T | undefined,+ attempt: RouteAttemptStart,+): T | undefined => {+ const onUsage = options?.onUsage;+ if (!onUsage) return options;++ const routeAttempt: RouteAttemptIdentity = {+ attemptId: attempt.attemptId,+ channelId: attempt.channelId,+ requestId: attempt.requestId,+ routerId: attempt.routerId,+ };+ return {+ ...options,+ onUsage: (usage, context) => onUsage(usage, { ...context, routeAttempt }),+ };+};diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.textToSpeech.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.textToSpeech.test.tsindex 8a738ea4a8d..3f64373f475 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.textToSpeech.test.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.textToSpeech.test.ts@@ -40,8 +40,13 @@ describe('createRouterRuntime textToSpeech', () => {const options = { metadata: { trigger: RequestTrigger.Tts }, onUsage };const result = await new Runtime().textToSpeech(payload, options);- expect(textToSpeech).toHaveBeenCalledWith(payload, options);+ expect(textToSpeech).toHaveBeenCalledWith(+ payload,+ expect.objectContaining({ metadata: options.metadata }),+ );expect(result).toMatchObject({ format: 'wav', usage });- expect(onUsage).toHaveBeenCalledWith(usage);+ expect(onUsage).toHaveBeenCalledWith(usage, {+ routeAttempt: expect.objectContaining({ attemptId: expect.any(String) }),+ });});});diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.tsindex fbd303d8b6f..ed08b806622 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts@@ -38,6 +38,7 @@ import { createTimingHelpers, getDurationMs } from '../../utils/timing';import { createVideoWithCompletionMode } from '../../utils/videoCompletionMode';import type { LobeRuntimeAI } from '../BaseAI';import type { ApiType } from './apiTypes';+import { type RouteAttemptMetadata, withAttemptUsage } from './attemptIdentity';import { getChatAttemptObservation, observeChatAttempt } from './chatAttempt';import { createChatAttemptFallbackCheck, resolveHoldReasoning } from './chatFallbackHooks';import type { ChatStreamFallbackAttempt } from './chatStreamFallback';@@ -65,18 +66,6 @@ export type {const log = debug('lobe-model-runtime:router-runtime');const { logger: timing } = createTimingHelpers('lobe-server:chat:lobehub:timing');-interface RouteAttemptMetadata {- apiType: string;- channelId?: string;- completionPending?: boolean;- durationMs: number;- optionIndex: number;- providerId: string;- routerId?: string;- success: boolean;- totalOptions: number;-}-interface RouteAttemptContext {allowedApiTypes?: ReadonlySet<ApiType>;metadata?: Record<string, unknown>;@@ -596,11 +585,13 @@ export const createRouterRuntime = ({});this.attachRouteAttemptMetadata(metadata, {apiType: resolvedApiType,+ attemptId: attempt.attemptId,channelId,completionPending: true,durationMs,optionIndex,providerId: id,+ requestId,routerId: matchedRouter.id,success: true,totalOptions: routerOptions.length,@@ -857,10 +848,12 @@ export const createRouterRuntime = ({this.attachRouteAttemptMetadata(metadata, {apiType: resolvedApiType,+ attemptId: attemptContext.attemptId,channelId,durationMs: Date.now() - attemptContext.startedAt,optionIndex: index,providerId: id,+ requestId,routerId: matchedRouter.id,success: true,totalOptions,@@ -1170,7 +1163,7 @@ export const createRouterRuntime = ({async generateObject(payload: GenerateObjectPayload, options?: GenerateObjectOptions) {return this.runWithFallback(payload.model,- (runtime) => runtime.generateObject!(payload, options),+ (runtime, attempt) => runtime.generateObject!(payload, withAttemptUsage(options, attempt)),{metadata: options?.metadata,method: 'generateObject',@@ -1184,7 +1177,7 @@ export const createRouterRuntime = ({async embeddings(payload: EmbeddingsPayload, options?: EmbeddingsOptions) {return this.runWithFallback(payload.model,- (runtime) => runtime.embeddings!(payload, options),+ (runtime, attempt) => runtime.embeddings!(payload, withAttemptUsage(options, attempt)),{metadata: options?.metadata,method: 'embeddings',@@ -1197,7 +1190,7 @@ export const createRouterRuntime = ({async textToSpeech(payload: TextToSpeechPayload, options?: TextToSpeechOptions) {return this.runWithFallback(payload.model,- (runtime) => runtime.textToSpeech!(payload, options),+ (runtime, attempt) => runtime.textToSpeech!(payload, withAttemptUsage(options, attempt)),{metadata: options?.metadata,method: 'textToSpeech',@@ -1210,7 +1203,7 @@ export const createRouterRuntime = ({async transcribe(payload: ASRPayload, options?: ASROptions) {return this.runWithFallback(payload.model,- (runtime) => runtime.transcribe!(payload, options),+ (runtime, attempt) => runtime.transcribe!(payload, withAttemptUsage(options, attempt)),{ metadata: options?.metadata, method: 'transcribe', user: options?.user },);}diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.usageAttribution.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.usageAttribution.test.tsnew file mode 100644index 00000000000..c81b70e9adc--- /dev/null+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.usageAttribution.test.ts@@ -0,0 +1,127 @@+import type { ModelUsage } from '@lobechat/types';+import { afterEach, describe, expect, it, vi } from 'vitest';++import type {+ CreateImagePayload,+ EmbeddingsOptions,+ EmbeddingsPayload,+ GenerateObjectOptions,+ GenerateObjectPayload,+} from '../../types';+import { readRouteAttemptIdentity } from '../../types';+import type { LobeRuntimeAI } from '../BaseAI';+import { createRouterRuntime } from './createRuntime';++const usage: ModelUsage = { cost: 0.001, totalInputTokens: 10, totalOutputTokens: 5 };++/** Channel `channel-a` fails after reporting usage; `channel-b` serves the request. */+const createFallbackRuntime = (method: 'embeddings' | 'generateObject') => {+ const calls = { count: 0 };+ class MockRuntime implements LobeRuntimeAI {+ async embeddings(_payload: EmbeddingsPayload, options?: EmbeddingsOptions) {+ return this.respond(options, [[0.1]]);+ }++ async generateObject(_payload: GenerateObjectPayload, options?: GenerateObjectOptions) {+ return this.respond(options, { ok: true });+ }++ private async respond<T>(+ options: { onUsage?: EmbeddingsOptions['onUsage'] } | undefined,+ result: T,+ ) {+ calls.count += 1;+ await options?.onUsage?.(usage);+ if (calls.count === 1) throw new Error('first channel failed');+ return result;+ }+ }++ const Runtime = createRouterRuntime({+ id: 'lobehub',+ routers: [+ {+ apiType: 'openai',+ id: 'router-1',+ models: ['model-x'],+ options: [{ id: 'channel-a' }, { id: 'channel-b' }],+ runtime: MockRuntime as any,+ },+ ],+ });++ return { method, runtime: new Runtime({ userId: 'user-1' }) };+};++describe('createRouterRuntime usage attribution', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it.each(['generateObject', 'embeddings'] as const)(+ 'tags %s usage with the identity of the attempt that reported it',+ async (method) => {+ const { runtime } = createFallbackRuntime(method);+ const onUsage = vi.fn();+ const metadata: Record<string, unknown> = { traceId: 'trace-1', trigger: 'chat' };+ const options = { metadata, onUsage };++ if (method === 'generateObject') {+ await runtime.generateObject({ messages: [], model: 'model-x' }, options);+ } else {+ await runtime.embeddings({ input: 'hi', model: 'model-x' }, options);+ }++ expect(onUsage).toHaveBeenCalledTimes(2);+ const [first, second] = onUsage.mock.calls.map(([, context]) => context.routeAttempt);+ expect(first).toMatchObject({ channelId: 'channel-a', routerId: 'router-1' });+ expect(second).toMatchObject({ channelId: 'channel-b', routerId: 'router-1' });+ expect(first.attemptId).not.toBe(second.attemptId);+ // Both attempts belong to one request.+ expect(first.requestId).toBe(second.requestId);+ // The metadata identity points at the attempt that served the request.+ expect(readRouteAttemptIdentity(metadata)).toEqual(second);+ },+ );++ it('exposes the serving attempt identity to callers billing after createImage returns', async () => {+ class MockRuntime implements LobeRuntimeAI {+ createImage = vi.fn(async (_payload: CreateImagePayload) => ({ imageUrl: 'https://img' }));+ }+ const Runtime = createRouterRuntime({+ id: 'lobehub',+ routers: [+ {+ apiType: 'openai',+ id: 'router-1',+ models: ['image-x'],+ options: { id: 'channel-1' },+ runtime: MockRuntime as any,+ },+ ],+ });+ const metadata: Record<string, unknown> = { traceId: 'trace-1', trigger: 'image' };++ await new Runtime({ userId: 'user-1' }).createImage(+ { model: 'image-x', params: { prompt: 'cat' } as any },+ { metadata },+ );++ expect(readRouteAttemptIdentity(metadata)).toEqual({+ attemptId: expect.any(String),+ channelId: 'channel-1',+ requestId: expect.any(String),+ routerId: 'router-1',+ });+ });+});++describe('readRouteAttemptIdentity', () => {+ it('ignores metadata without a complete identity', () => {+ expect(readRouteAttemptIdentity(undefined)).toBeUndefined();+ expect(readRouteAttemptIdentity({ routeAttempt: { channelId: 'c' } })).toBeUndefined();+ expect(+ readRouteAttemptIdentity({ routeAttempt: { attemptId: 'a', channelId: 1, requestId: 'r' } }),+ ).toEqual({ attemptId: 'a', requestId: 'r' });+ });+});diff --git a/packages/model-runtime/src/types/asr.ts b/packages/model-runtime/src/types/asr.tsindex 65ba63cb6c1..70be0f1e172 100644--- a/packages/model-runtime/src/types/asr.ts+++ b/packages/model-runtime/src/types/asr.ts@@ -1,6 +1,5 @@-import type { ModelUsage } from '@lobechat/types';-import type { ModelPricingContext } from './pricing';+import type { OnUsageCallback } from './routeAttempt';export interface ASRPayload {/**@@ -42,7 +41,7 @@ export interface ASROptions {* Receives the provider-reported token usage (with `cost` when the model has* pricing) after a successful transcription.*/- onUsage?: (usage: ModelUsage) => void | Promise<void>;+ onUsage?: OnUsageCallback;pricingContext?: ModelPricingContext;signal?: AbortSignal;/**diff --git a/packages/model-runtime/src/types/chat.ts b/packages/model-runtime/src/types/chat.tsindex 4d0c12ff8ab..355f5fc3d7c 100644--- a/packages/model-runtime/src/types/chat.ts+++ b/packages/model-runtime/src/types/chat.ts@@ -9,6 +9,7 @@ import type OpenAI from 'openai';import type { ComputeChatCostOptions } from '../core/usageConverters/utils/computeChatCost';import type { ModelPricingContext } from './pricing';import type { ModelRuntimeDiagnostics } from './providerDiagnostics';+import type { RouteAttemptIdentity } from './routeAttempt';import type { MessageToolCall, MessageToolCallChunk } from './toolsCalling';export type LLMRoleType = 'user' | 'system' | 'assistant' | 'function' | 'tool';@@ -290,13 +291,8 @@ export interface OnFinishData {providerReportedCost?: number;reasoning?: ModelReasoning;/** Stable identities and terminal outcome for the provider attempt producing this result. */- routeAttempt?: {- attemptId: string;- /** Router channel that served the attempt. */- channelId?: string;+ routeAttempt?: RouteAttemptIdentity & {outcome?: 'completed' | 'empty' | 'interrupted' | 'cancelled' | 'failed';- requestId: string;- routerId?: string;};speed?: ModelPerformance;text: string;diff --git a/packages/model-runtime/src/types/embeddings.ts b/packages/model-runtime/src/types/embeddings.tsindex b2d805ac467..e36e3cbc52f 100644--- a/packages/model-runtime/src/types/embeddings.ts+++ b/packages/model-runtime/src/types/embeddings.ts@@ -1,6 +1,5 @@-import type { ModelUsage } from '@lobechat/types';-import type { ModelPricingContext } from './pricing';+import type { OnUsageCallback } from './routeAttempt';export interface EmbeddingsPayload {/**@@ -24,7 +23,7 @@ export interface EmbeddingsOptions {headers?: Record<string, any>;/** Metadata passed to hooks (billing, tracing, etc.) */metadata?: Record<string, unknown>;- onUsage?: (usage: ModelUsage) => void | Promise<void>;+ onUsage?: OnUsageCallback;/** Request-scoped pricing context for model-bank pricing lookups. */pricingContext?: ModelPricingContext;signal?: AbortSignal;diff --git a/packages/model-runtime/src/types/index.ts b/packages/model-runtime/src/types/index.tsindex 3283ef4ab5f..f27e4d6b718 100644--- a/packages/model-runtime/src/types/index.ts+++ b/packages/model-runtime/src/types/index.ts@@ -7,6 +7,7 @@ export * from './image';export * from './model';export * from './pricing';export * from './providerDiagnostics';+export * from './routeAttempt';export * from './structureOutput';export * from './toolsCalling';export * from './tts';diff --git a/packages/model-runtime/src/types/routeAttempt.ts b/packages/model-runtime/src/types/routeAttempt.tsnew file mode 100644index 00000000000..b1f3cebdf35--- /dev/null+++ b/packages/model-runtime/src/types/routeAttempt.ts@@ -0,0 +1,44 @@+import type { ModelUsage } from '@lobechat/types';++/**+ * Stable identity of the router attempt that served a request, so billing can attribute the+ * usage to the channel that produced it.+ */+export interface RouteAttemptIdentity {+ attemptId: string;+ /** Router channel that served the attempt. */+ channelId?: string;+ requestId: string;+ routerId?: string;+}++/** Second `onUsage` argument, filled by RouterRuntime for the attempt that reported the usage. */+export interface UsageReportContext {+ routeAttempt?: RouteAttemptIdentity;+}++export type OnUsageCallback = (+ usage: ModelUsage,+ context?: UsageReportContext,+) => void | Promise<void>;++/**+ * Reads the identity RouterRuntime attaches to `options.metadata.routeAttempt` once an attempt+ * succeeds. Methods whose result is billed after they return (image, video) carry it this way.+ */+export const readRouteAttemptIdentity = (+ metadata: Record<string, unknown> | undefined,+): RouteAttemptIdentity | undefined => {+ const value = metadata?.routeAttempt;+ if (!value || typeof value !== 'object') return;++ const { attemptId, channelId, requestId, routerId } = value as Record<string, unknown>;+ if (typeof attemptId !== 'string' || typeof requestId !== 'string') return;++ return {+ attemptId,+ requestId,+ ...(typeof channelId === 'string' ? { channelId } : {}),+ ...(typeof routerId === 'string' ? { routerId } : {}),+ };+};diff --git a/packages/model-runtime/src/types/structureOutput.ts b/packages/model-runtime/src/types/structureOutput.tsindex a0f4504bc69..6f0ea55c538 100644--- a/packages/model-runtime/src/types/structureOutput.ts+++ b/packages/model-runtime/src/types/structureOutput.ts@@ -1,7 +1,6 @@-import type { ModelUsage } from '@lobechat/types';-import type { ChatCompletionTool, ChatStreamPayload } from './chat';import type { ModelPricingContext } from './pricing';+import type { OnUsageCallback } from './routeAttempt';interface GenerateObjectMessage {content: string;@@ -40,7 +39,7 @@ export interface GenerateObjectOptions {/** Free-form context passed to hooks (e.g. billing, routing). */metadata?: Record<string, unknown>;- onUsage?: (usage: ModelUsage) => void | Promise<void>;+ onUsage?: OnUsageCallback;/** Request-scoped pricing context for model-bank pricing lookups. */pricingContext?: ModelPricingContext;diff --git a/packages/model-runtime/src/types/tts.ts b/packages/model-runtime/src/types/tts.tsindex d1d0dd1df74..12f69edbcd9 100644--- a/packages/model-runtime/src/types/tts.ts+++ b/packages/model-runtime/src/types/tts.ts@@ -2,6 +2,7 @@ import type { ModelUsage } from '@lobechat/types';import type { RuntimeTTSParams, TTSAudioFormat } from 'model-bank';import type { ModelPricingContext } from './pricing';+import type { OnUsageCallback } from './routeAttempt';export interface TextToSpeechPayload {input: string;@@ -26,7 +27,7 @@ export interface TextToSpeechOptions {* Receives the synthesis usage (with `cost` when the model has pricing) after a* successful request.*/- onUsage?: (usage: ModelUsage) => void | Promise<void>;+ onUsage?: OnUsageCallback;pricingContext?: ModelPricingContext;signal?: AbortSignal;/**diff --git a/packages/types/src/asyncTask.ts b/packages/types/src/asyncTask.tsindex b8806d44244..22aca81010d 100644--- a/packages/types/src/asyncTask.ts+++ b/packages/types/src/asyncTask.ts@@ -226,6 +226,11 @@ export interface VideoGenerationTaskMetadata {export interface VideoGenerationRoute {apiType: string;+ /**+ * Router attempt that created the video, so the completion charge can be attributed to it.+ * Routing ignores it: only `routerId` and `channelId` pin later polls.+ */+ attemptId?: string;channelId?: string;routerId?: string;}