🤯 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): pass provider-reported cost to onFinal (#20980)
YuTengjinge8108d0fe296
diff --git a/packages/model-runtime/src/core/RouterRuntime/chatAttempt.test.ts b/packages/model-runtime/src/core/RouterRuntime/chatAttempt.test.tsindex 3be6e848444..6c1d1e3f20b 100644--- a/packages/model-runtime/src/core/RouterRuntime/chatAttempt.test.ts+++ b/packages/model-runtime/src/core/RouterRuntime/chatAttempt.test.ts@@ -9,10 +9,12 @@ describe('observeChatAttempt', () => {const attempt = {apiType: 'openai',attemptId: 'attempt-1',+ channelId: 'channel-1',model: 'model',optionIndex: 0,providerId: 'test',requestId: 'request-1',+ routerId: 'router-1',startedAt: 1000,};@@ -48,7 +50,12 @@ describe('observeChatAttempt', () => {await response.text();expect(completion.mock.calls[0][0]).toEqual(final.mock.calls[0][0]);expect(final.mock.calls[0][0]).toMatchObject({- routeAttempt: { attemptId: 'attempt-1', requestId: 'request-1' },+ routeAttempt: {+ attemptId: 'attempt-1',+ channelId: 'channel-1',+ requestId: 'request-1',+ routerId: 'router-1',+ },speed: { ttft: 200, duration: 1000, latency: 1300, tps: 100 },});expect(finished).toHaveBeenCalledTimes(1);@@ -265,8 +272,10 @@ describe('observeChatAttempt', () => {expect(finished.mock.calls[0][0].speed.tps).toBeUndefined();expect(final.mock.calls[0][0].routeAttempt).toEqual({attemptId: 'attempt-1',+ channelId: 'channel-1',outcome: 'completed',requestId: 'request-1',+ routerId: 'router-1',});});diff --git a/packages/model-runtime/src/core/RouterRuntime/chatAttempt.ts b/packages/model-runtime/src/core/RouterRuntime/chatAttempt.tsindex c307c7bd9eb..178bafab904 100644--- a/packages/model-runtime/src/core/RouterRuntime/chatAttempt.ts+++ b/packages/model-runtime/src/core/RouterRuntime/chatAttempt.ts@@ -147,8 +147,10 @@ export const observeChatAttempt = async (...terminal.data,routeAttempt: {attemptId: attempt.attemptId,+ channelId: attempt.channelId,outcome: finalResult.outcome,requestId: attempt.requestId,+ routerId: attempt.routerId,},speed: finalResult.speed ? { ...finalResult.speed } : undefined,});diff --git a/packages/model-runtime/src/core/streams/anthropic.ts b/packages/model-runtime/src/core/streams/anthropic.tsindex 1844cd216b7..f3408f2f121 100644--- a/packages/model-runtime/src/core/streams/anthropic.ts+++ b/packages/model-runtime/src/core/streams/anthropic.ts@@ -20,6 +20,7 @@ import {createTokenSpeedCalculator,FIRST_CHUNK_ERROR_KEY,} from './protocol';+import { recordProviderReportedCost } from './providerReportedCost';export const transformAnthropicStream = (chunk: Anthropic.MessageStreamEvent,@@ -316,15 +317,17 @@ export const AnthropicStream = (stream: Stream<Anthropic.MessageStreamEvent> | ReadableStream,{ callbacks, inputStartAt, enableStreaming = true, payload }: AnthropicStreamOptions = {},) => {- const streamStack: StreamContext = { id: '' };+ const streamStack: StreamContext = { id: '', pricingOptions: payload?.pricingOptions };const readableStream =stream instanceof ReadableStream? stream: convertIterableToStream(stream, { model: payload?.model, provider: payload?.provider });- const transformWithPayload: typeof transformAnthropicStream = (chunk, ctx) =>- transformAnthropicStream(chunk, ctx, payload);+ const transformWithPayload: typeof transformAnthropicStream = (chunk, ctx) => {+ recordProviderReportedCost(streamStack, chunk);+ return transformAnthropicStream(chunk, ctx, payload);+ };return readableStream.pipeThrough(createFirstErrorHandleTransformer(undefined, payload?.provider))diff --git a/packages/model-runtime/src/core/streams/bedrock/claude.ts b/packages/model-runtime/src/core/streams/bedrock/claude.tsindex 4efd3113d6c..b86fd2dd976 100644--- a/packages/model-runtime/src/core/streams/bedrock/claude.ts+++ b/packages/model-runtime/src/core/streams/bedrock/claude.ts@@ -19,7 +19,10 @@ export const AWSBedrockClaudeStream = (payload?: Parameters<typeof transformAnthropicStream>[2];},): ReadableStream<Uint8Array> => {- const streamStack: StreamContext = { id: 'chat_' + nanoid() };+ const streamStack: StreamContext = {+ id: 'chat_' + nanoid(),+ pricingOptions: options?.payload?.pricingOptions,+ };const stream = res instanceof ReadableStream ? res : createBedrockStream(res);@@ -37,5 +40,5 @@ export const AWSBedrockClaudeStream = (// Same Messages event contract as `AnthropicStream`: closing without a terminal event is a truncation.createSSEProtocolTransformer((c) => c, streamStack, { requireTerminalEvent: true }),)- .pipeThrough(createCallbacksTransformer(options?.callbacks));+ .pipeThrough(createCallbacksTransformer(options?.callbacks, { streamStack }));};diff --git a/packages/model-runtime/src/core/streams/index.ts b/packages/model-runtime/src/core/streams/index.tsindex c95e5c9af47..4449b227dc2 100644--- a/packages/model-runtime/src/core/streams/index.ts+++ b/packages/model-runtime/src/core/streams/index.ts@@ -5,5 +5,7 @@ export * from './model';export * from './ollama';export * from './openai';export * from './protocol';+export * from './providerReportedCost';export * from './qwen';export * from './spark';+export * from './usageMissingDiagnostics';diff --git a/packages/model-runtime/src/core/streams/openai/openai.ts b/packages/model-runtime/src/core/streams/openai/openai.tsindex 66d80fdcd81..94d60d96fc6 100644--- a/packages/model-runtime/src/core/streams/openai/openai.ts+++ b/packages/model-runtime/src/core/streams/openai/openai.ts@@ -24,6 +24,7 @@ import {FIRST_CHUNK_ERROR_KEY,generateToolCallId,} from '../protocol';+import { recordProviderReportedCost } from '../providerReportedCost';/*** Extended type for OpenAI tool calls that includes provider-specific extensions@@ -730,8 +731,13 @@ export const OpenAIStream = (id: '',};- const transformWithProvider = (chunk: OpenAI.ChatCompletionChunk, streamContext: StreamContext) =>- transformOpenAIStream(chunk, streamContext, payload);+ const transformWithProvider = (+ chunk: OpenAI.ChatCompletionChunk,+ streamContext: StreamContext,+ ) => {+ recordProviderReportedCost(streamStack, chunk);+ return transformOpenAIStream(chunk, streamContext, payload);+ };const readableStream =stream instanceof ReadableStreamdiff --git a/packages/model-runtime/src/core/streams/openai/responsesStream.ts b/packages/model-runtime/src/core/streams/openai/responsesStream.tsindex e2c0ac74edf..610f9cf3488 100644--- a/packages/model-runtime/src/core/streams/openai/responsesStream.ts+++ b/packages/model-runtime/src/core/streams/openai/responsesStream.ts@@ -20,6 +20,7 @@ import {createTokenSpeedCalculator,FIRST_CHUNK_ERROR_KEY,} from '../protocol';+import { recordProviderReportedCost } from '../providerReportedCost';import type { OpenAIStreamOptions } from './openai';const toResponsesError = (error: { code?: string | null; message?: string | null }) =>@@ -351,8 +352,10 @@ export const OpenAIResponsesStream = (: convertIterableToStream(stream, { model: payload?.model, provider: payload?.provider });// use closure to pass payload to transformOpenAIStream- const transformWithPayload: typeof transformOpenAIStream = (chunk, streamContext) =>- transformOpenAIStream(chunk, streamContext, payload);+ const transformWithPayload: typeof transformOpenAIStream = (chunk, streamContext) => {+ recordProviderReportedCost(streamStack, chunk);+ return transformOpenAIStream(chunk, streamContext, payload);+ };return (readableStreamdiff --git a/packages/model-runtime/src/core/streams/protocol.ts b/packages/model-runtime/src/core/streams/protocol.tsindex e9b288b9963..50125ebc0c8 100644--- a/packages/model-runtime/src/core/streams/protocol.ts+++ b/packages/model-runtime/src/core/streams/protocol.ts@@ -31,6 +31,10 @@ export type ChatPayloadForTransformStream = {export interface StreamContext {chunkIndex?: number;id: string;+ /** Options used to price `usage.cost`, forwarded so hooks can reprice the same usage. */+ pricingOptions?: ComputeChatCostOptions;+ /** Latest USD charge the upstream provider reported in a chunk. Server-side only. */+ providerReportedCost?: number;/*** As pplx citations is in every chunk, but we only need to return it once* this flag is used to check if the pplx citation is returned,and then not return it again.@@ -79,31 +83,6 @@ export interface StreamContext {usageMissingDiagnostics?: UsageMissingDiagnostics;}-export const setOpenAIChatCompletionUsageMissingDiagnostics = (- streamContext: StreamContext,- payload: ChatPayloadForTransformStream | undefined,- {- finishReason,- responseId,- }: {- finishReason?: string | null;- responseId?: string;- },-) => {- streamContext.usageMissingDiagnostics = {- apiMode: 'chat_completions',- chunkIndex: streamContext.chunkIndex,- finishReason,- hasUsageMetadata: false,- includeUsageRequested: payload?.includeUsageRequested,- model: payload?.model,- provider: payload?.provider,- responseId,- source: 'openai_chat_completions',- terminalEventType: 'chat.completion.chunk',- };-};-export interface StreamProtocolChunk {data: any;id?: string;@@ -496,6 +475,9 @@ export function createCallbacksTransformer(? undefined: options?.streamStack?.usageMissingDiagnostics;if (usageMissingDiagnostics) data.usageMissingDiagnostics = usageMissingDiagnostics;+ const { pricingOptions, providerReportedCost } = options?.streamStack ?? {};+ if (providerReportedCost !== undefined) data.providerReportedCost = providerReportedCost;+ if (pricingOptions) data.pricingOptions = pricingOptions;if (callbacks.onCompletion) {await callbacks.onCompletion(data);diff --git a/packages/model-runtime/src/core/streams/providerReportedCost.test.ts b/packages/model-runtime/src/core/streams/providerReportedCost.test.tsnew file mode 100644index 00000000000..710eaed19ba--- /dev/null+++ b/packages/model-runtime/src/core/streams/providerReportedCost.test.ts@@ -0,0 +1,173 @@+import { describe, expect, it, vi } from 'vitest';++import { AnthropicStream } from './anthropic';+import { AWSBedrockClaudeStream } from './bedrock/claude';+import { OpenAIStream } from './openai/openai';+import { OpenAIResponsesStream } from './openai/responsesStream';+import { readProviderReportedCost } from './providerReportedCost';++const createStream = (chunks: unknown[]) =>+ new ReadableStream({+ start(controller) {+ for (const chunk of chunks) controller.enqueue(chunk);+ controller.close();+ },+ });++const readAll = async (stream: ReadableStream<Uint8Array>) => {+ const decoder = new TextDecoder();+ let output = '';+ // @ts-ignore+ for await (const chunk of stream) output += decoder.decode(chunk, { stream: true });+ return output;+};++describe('readProviderReportedCost', () => {+ it('reads OpenRouter usage.cost', () => {+ expect(readProviderReportedCost({ usage: { cost: 0.000_150_48 } })).toBe(0.000_150_48);+ });++ it('reads the Vercel gateway cost decimal string', () => {+ expect(readProviderReportedCost({ provider_metadata: { gateway: { cost: '0.000076' } } })).toBe(+ 0.000_076,+ );+ });++ it('reads costs nested in Anthropic message and Responses response objects', () => {+ expect(readProviderReportedCost({ message: { usage: { cost: 0.2 } } })).toBe(0.2);+ expect(+ readProviderReportedCost({ response: { provider_metadata: { gateway: { cost: '0.3' } } } }),+ ).toBe(0.3);+ });++ it('ignores missing, empty, negative and non-numeric values', () => {+ expect(readProviderReportedCost(undefined)).toBeUndefined();+ expect(readProviderReportedCost({ usage: { prompt_tokens: 1 } })).toBeUndefined();+ expect(+ readProviderReportedCost({ provider_metadata: { gateway: { cost: '' } } }),+ ).toBeUndefined();+ expect(readProviderReportedCost({ usage: { cost: -1 } })).toBeUndefined();+ expect(readProviderReportedCost({ usage: { cost: 'n/a' } })).toBeUndefined();+ });+});++describe('provider-reported cost in stream callbacks', () => {+ it('passes OpenAI Chat Completions usage.cost to onFinal without streaming it', async () => {+ const onFinal = vi.fn();+ const output = await readAll(+ OpenAIStream(+ createStream([+ { choices: [{ delta: { content: 'hi' }, index: 0 }], id: 'c1' },+ { choices: [{ delta: {}, finish_reason: 'stop', index: 0 }], id: 'c1' },+ {+ choices: [],+ id: 'c1',+ usage: { completion_tokens: 6, cost: 0.000_088_11, prompt_tokens: 8, total_tokens: 14 },+ },+ ]),+ { callbacks: { onFinal } },+ ),+ );++ expect(onFinal).toHaveBeenCalledWith(+ expect.objectContaining({ providerReportedCost: 0.000_088_11 }),+ );+ expect(output).not.toContain('0.00008811');+ });++ it('passes the Vercel gateway cost on Responses completion to onFinal', async () => {+ const onFinal = vi.fn();+ const output = await readAll(+ OpenAIResponsesStream(+ createStream([+ { response: { id: 'r1', status: 'in_progress' }, type: 'response.created' },+ {+ response: {+ id: 'r1',+ provider_metadata: { gateway: { cost: '0.000076' } },+ status: 'completed',+ usage: { input_tokens: 8, output_tokens: 6, total_tokens: 14 },+ },+ type: 'response.completed',+ },+ ]),+ { callbacks: { onFinal } },+ ),+ );++ expect(onFinal).toHaveBeenCalledWith(+ expect.objectContaining({ providerReportedCost: 0.000_076 }),+ );+ expect(output).not.toContain('0.000076');+ });++ it('passes the final Anthropic message_delta cost and pricing options to onFinal', async () => {+ const onFinal = vi.fn();+ const pricingOptions = { lookupParams: { ttl: '1h' } };+ await readAll(+ AnthropicStream(+ createStream([+ {+ message: { id: 'm1', usage: { input_tokens: 8, output_tokens: 1 } },+ type: 'message_start',+ },+ { delta: { text: 'hi', type: 'text_delta' }, index: 0, type: 'content_block_delta' },+ {+ delta: { stop_reason: 'end_turn' },+ provider_metadata: { gateway: { cost: '0.00012' } },+ type: 'message_delta',+ usage: { output_tokens: 6 },+ },+ { type: 'message_stop' },+ ]),+ { callbacks: { onFinal }, payload: { model: 'claude', pricingOptions, provider: 'x' } },+ ),+ );++ expect(onFinal).toHaveBeenCalledWith(+ expect.objectContaining({ pricingOptions, providerReportedCost: 0.000_12 }),+ );+ });++ it('passes Bedrock Claude pricing options to onFinal', async () => {+ const onFinal = vi.fn();+ const pricingOptions = { lookupParams: { ttl: '1h' } };+ await readAll(+ AWSBedrockClaudeStream(+ createStream([+ {+ message: { id: 'm1', usage: { input_tokens: 8, output_tokens: 1 } },+ type: 'message_start',+ },+ { delta: { text: 'hi', type: 'text_delta' }, index: 0, type: 'content_block_delta' },+ {+ delta: { stop_reason: 'end_turn' },+ type: 'message_delta',+ usage: { output_tokens: 6 },+ },+ { type: 'message_stop' },+ ]),+ {+ callbacks: { onFinal },+ payload: { model: 'claude', pricingOptions, provider: 'bedrock' },+ },+ ),+ );++ expect(onFinal).toHaveBeenCalledWith(expect.objectContaining({ pricingOptions }));+ });++ it('omits providerReportedCost when the provider reports none', async () => {+ const onFinal = vi.fn();+ await readAll(+ OpenAIStream(+ createStream([+ { choices: [{ delta: { content: 'hi' }, finish_reason: 'stop', index: 0 }], id: 'c1' },+ ]),+ { callbacks: { onFinal } },+ ),+ );++ expect(onFinal.mock.calls[0][0]).not.toHaveProperty('providerReportedCost');+ });+});diff --git a/packages/model-runtime/src/core/streams/providerReportedCost.ts b/packages/model-runtime/src/core/streams/providerReportedCost.tsnew file mode 100644index 00000000000..822d5d1e3d9--- /dev/null+++ b/packages/model-runtime/src/core/streams/providerReportedCost.ts@@ -0,0 +1,35 @@+import type { StreamContext } from './protocol';++const toReportedCost = (value: unknown): number | undefined => {+ const cost = typeof value === 'string' && value.trim() !== '' ? Number(value) : value;+ return typeof cost === 'number' && Number.isFinite(cost) && cost >= 0 ? cost : undefined;+};++/**+ * Reads the USD charge an aggregator reports for a call. OpenRouter sends `usage.cost` on every+ * API; Vercel AI Gateway sends `usage.cost` on Chat Completions and a decimal string in+ * `provider_metadata.gateway.cost` on Messages and Responses. The value can sit on the chunk+ * itself, on Anthropic `message_start.message`, or on Responses `response.completed.response`.+ */+export const readProviderReportedCost = (chunk: unknown): number | undefined => {+ if (!chunk || typeof chunk !== 'object') return undefined;+ const record = chunk as Record<string, any>;++ for (const source of [record, record.message, record.response]) {+ if (!source || typeof source !== 'object') continue;+ const cost =+ toReportedCost(source.usage?.cost) ?? toReportedCost(source.provider_metadata?.gateway?.cost);+ if (cost !== undefined) return cost;+ }++ return undefined;+};++/**+ * Keeps the provider-reported charge out of `usage`, which is streamed to clients and persisted+ * on messages, and hands it to `onFinal` through the server-side stream context instead.+ */+export const recordProviderReportedCost = (streamContext: StreamContext, chunk: unknown) => {+ const cost = readProviderReportedCost(chunk);+ if (cost !== undefined) streamContext.providerReportedCost = cost;+};diff --git a/packages/model-runtime/src/core/streams/qwen.ts b/packages/model-runtime/src/core/streams/qwen.tsindex 0eae94f2350..7e49a27aa41 100644--- a/packages/model-runtime/src/core/streams/qwen.ts+++ b/packages/model-runtime/src/core/streams/qwen.ts@@ -20,8 +20,8 @@ import {createSSEProtocolTransformer,createTokenSpeedCalculator,generateToolCallId,- setOpenAIChatCompletionUsageMissingDiagnostics,} from './protocol';+import { setOpenAIChatCompletionUsageMissingDiagnostics } from './usageMissingDiagnostics';export const transformQwenStream = (chunk: OpenAI.ChatCompletionChunk,diff --git a/packages/model-runtime/src/core/streams/spark.ts b/packages/model-runtime/src/core/streams/spark.tsindex f778d79081d..ca8465c92f5 100644--- a/packages/model-runtime/src/core/streams/spark.ts+++ b/packages/model-runtime/src/core/streams/spark.ts@@ -14,8 +14,8 @@ import {createCallbacksTransformer,createSSEProtocolTransformer,generateToolCallId,- setOpenAIChatCompletionUsageMissingDiagnostics,} from './protocol';+import { setOpenAIChatCompletionUsageMissingDiagnostics } from './usageMissingDiagnostics';export function transformSparkResponseToStream(data: OpenAI.ChatCompletion) {return new ReadableStream({diff --git a/packages/model-runtime/src/core/streams/usageMissingDiagnostics.ts b/packages/model-runtime/src/core/streams/usageMissingDiagnostics.tsnew file mode 100644index 00000000000..f843c59cb12--- /dev/null+++ b/packages/model-runtime/src/core/streams/usageMissingDiagnostics.ts@@ -0,0 +1,26 @@+import type { ChatPayloadForTransformStream, StreamContext } from './protocol';++export const setOpenAIChatCompletionUsageMissingDiagnostics = (+ streamContext: StreamContext,+ payload: ChatPayloadForTransformStream | undefined,+ {+ finishReason,+ responseId,+ }: {+ finishReason?: string | null;+ responseId?: string;+ },+) => {+ streamContext.usageMissingDiagnostics = {+ apiMode: 'chat_completions',+ chunkIndex: streamContext.chunkIndex,+ finishReason,+ hasUsageMetadata: false,+ includeUsageRequested: payload?.includeUsageRequested,+ model: payload?.model,+ provider: payload?.provider,+ responseId,+ source: 'openai_chat_completions',+ terminalEventType: 'chat.completion.chunk',+ };+};diff --git a/packages/model-runtime/src/types/chat.ts b/packages/model-runtime/src/types/chat.tsindex 0d11f67be6c..4d0c12ff8ab 100644--- a/packages/model-runtime/src/types/chat.ts+++ b/packages/model-runtime/src/types/chat.ts@@ -6,6 +6,7 @@ import type {} from '@lobechat/types';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 { MessageToolCall, MessageToolCallChunk } from './toolsCalling';@@ -280,12 +281,22 @@ export interface OnFinishData {*/finishReason?: string;grounding?: any;+ /** Options used to price `usage.cost` (e.g. cache TTL lookups), so hooks can reprice the same usage. */+ pricingOptions?: ComputeChatCostOptions;+ /**+ * USD charge reported by the upstream provider (OpenRouter, Vercel AI Gateway). Server-side+ * only: unlike `usage`, it is never streamed to clients or persisted on messages.+ */+ 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;outcome?: 'completed' | 'empty' | 'interrupted' | 'cancelled' | 'failed';requestId: string;+ routerId?: string;};speed?: ModelPerformance;text: string;