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(asr): report transcription usage and fix Gemini transcripts (#20092)

YuTengjingd7918c166f1c
diff --git a/apps/server/src/routers/lambda/__tests__/asr.test.ts b/apps/server/src/routers/lambda/__tests__/asr.test.ts
index 16d090e4033..3b4ef793821 100644
--- a/apps/server/src/routers/lambda/__tests__/asr.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/asr.test.ts
@@ -56,6 +56,19 @@ describe('asrRouter.transcribe', () => {
expect(await payload.file.text()).toBe('audio-bytes');
});
+ it('tags the request with the ASR trigger for route attempts and hooks', async () => {
+ await caller.transcribe({
+ audioBase64: Buffer.from('audio-bytes').toString('base64'),
+ model: 'gemini-3.5-transcribe',
+ provider: 'lobehub',
+ });
+
+ expect(transcribeMock.mock.calls[0][1]).toEqual({
+ metadata: { trigger: 'asr' },
+ user: 'u1',
+ });
+ });
+
it('resolves a fileId by downloading the bytes from storage', async () => {
findByIdMock.mockResolvedValue({
fileType: 'audio/mp4',
diff --git a/apps/server/src/routers/lambda/asr.ts b/apps/server/src/routers/lambda/asr.ts
index 1e68148732e..3b13b52915c 100644
--- a/apps/server/src/routers/lambda/asr.ts
+++ b/apps/server/src/routers/lambda/asr.ts
@@ -1,4 +1,5 @@
import { hasApiKeyScope, isFullAccessApiKey } from '@lobechat/const/apiKeyScope';
+import { RequestTrigger } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
@@ -125,7 +126,7 @@ export const asrRouter = router({
prompt: input.prompt,
responseFormat: input.responseFormat,
},
- { user: ctx.userId },
+ { metadata: { trigger: RequestTrigger.Asr }, user: ctx.userId },
);
if (!result) {
diff --git a/locales/en-US/spend.json b/locales/en-US/spend.json
index 4fe873627df..026bdc66583 100644
--- a/locales/en-US/spend.json
+++ b/locales/en-US/spend.json
@@ -19,6 +19,7 @@
"table.columns.trigger.enums.agent_share": "Agent Share",
"table.columns.trigger.enums.agent_signal": "Agent Signal",
"table.columns.trigger.enums.api": "API Call",
+ "table.columns.trigger.enums.asr": "Voice Transcription",
"table.columns.trigger.enums.bot": "Bot Message",
"table.columns.trigger.enums.builder_suggestion": "Builder Suggestions",
"table.columns.trigger.enums.chat": "Chat Message",
diff --git a/locales/zh-CN/spend.json b/locales/zh-CN/spend.json
index a643cf20540..fc72a9cda19 100644
--- a/locales/zh-CN/spend.json
+++ b/locales/zh-CN/spend.json
@@ -19,6 +19,7 @@
"table.columns.trigger.enums.agent_share": "助手分享",
"table.columns.trigger.enums.agent_signal": "代理信号",
"table.columns.trigger.enums.api": "API 调用",
+ "table.columns.trigger.enums.asr": "语音转写",
"table.columns.trigger.enums.bot": "Bot 消息",
"table.columns.trigger.enums.builder_suggestion": "构建建议",
"table.columns.trigger.enums.chat": "聊天消息",
diff --git a/packages/locales/src/default/spend.ts b/packages/locales/src/default/spend.ts
index cd99672603e..82ec5884b7e 100644
--- a/packages/locales/src/default/spend.ts
+++ b/packages/locales/src/default/spend.ts
@@ -18,6 +18,7 @@ export default {
'table.columns.trigger.enums.agent_share': 'Agent Share',
'table.columns.trigger.enums.agent_signal': 'Agent Signal',
'table.columns.trigger.enums.api': 'API Call',
+ 'table.columns.trigger.enums.asr': 'Voice Transcription',
'table.columns.trigger.enums.bot': 'Bot Message',
'table.columns.trigger.enums.builder_suggestion': 'Builder Suggestions',
'table.columns.trigger.enums.chat': 'Chat Message',
diff --git a/packages/model-runtime/src/core/ModelRuntime.test.ts b/packages/model-runtime/src/core/ModelRuntime.test.ts
index 0fcfef997f4..5b32080f694 100644
--- a/packages/model-runtime/src/core/ModelRuntime.test.ts
+++ b/packages/model-runtime/src/core/ModelRuntime.test.ts
@@ -560,7 +560,12 @@ describe('ModelRuntime', () => {
describe('hooks', () => {
const createMockRuntime = (hooks?: ModelRuntimeHooks) => {
- const mockRuntimeAI = { chat: vi.fn(), embeddings: vi.fn(), generateObject: vi.fn() } as any;
+ const mockRuntimeAI = {
+ chat: vi.fn(),
+ embeddings: vi.fn(),
+ generateObject: vi.fn(),
+ transcribe: vi.fn(),
+ } as any;
return { runtime: new ModelRuntime(mockRuntimeAI, hooks), mockRuntimeAI };
};
@@ -937,5 +942,67 @@ describe('ModelRuntime', () => {
});
});
});
+
+ describe('transcribe hooks', () => {
+ const transcribePayload = {
+ file: new Blob([new Uint8Array([1, 2, 3])]),
+ model: 'gpt-4o-transcribe',
+ };
+
+ it('passes provider usage to onTranscribeFinal after beforeTranscribe', async () => {
+ const usage = { cost: 0.0004, inputAudioTokens: 59, outputTextTokens: 21 };
+ const beforeTranscribe = vi.fn();
+ const onTranscribeFinal = vi.fn();
+ const { runtime, mockRuntimeAI } = createMockRuntime({
+ beforeTranscribe,
+ onTranscribeFinal,
+ });
+ mockRuntimeAI.transcribe.mockImplementation(async (_payload: any, options: any) => {
+ await options.onUsage(usage);
+ return { text: 'hello' };
+ });
+
+ const options = { user: 'u1' };
+ const result = await runtime.transcribe(transcribePayload, options);
+
+ expect(result).toEqual({ text: 'hello' });
+ expect(beforeTranscribe).toHaveBeenCalledWith(transcribePayload, options);
+ expect(onTranscribeFinal).toHaveBeenCalledWith(
+ { latencyMs: expect.any(Number), usage },
+ { options, payload: transcribePayload },
+ );
+ });
+
+ it('still fires onTranscribeFinal without usage so reservations can be released', async () => {
+ const onTranscribeFinal = vi.fn();
+ const { runtime, mockRuntimeAI } = createMockRuntime({ onTranscribeFinal });
+ mockRuntimeAI.transcribe.mockResolvedValue({ text: 'hello' });
+
+ await runtime.transcribe(transcribePayload);
+
+ expect(onTranscribeFinal).toHaveBeenCalledWith(
+ { latencyMs: expect.any(Number), usage: undefined },
+ { options: undefined, payload: transcribePayload },
+ );
+ });
+
+ it('calls onTranscribeError and re-throws when the provider fails', async () => {
+ const providerError = { errorType: 'ProviderBizError', error: { message: 'boom' } };
+ const onTranscribeError = vi.fn();
+ const onTranscribeFinal = vi.fn();
+ const { runtime, mockRuntimeAI } = createMockRuntime({
+ onTranscribeError,
+ onTranscribeFinal,
+ });
+ mockRuntimeAI.transcribe.mockRejectedValue(providerError);
+
+ await expect(runtime.transcribe(transcribePayload)).rejects.toBe(providerError);
+ expect(onTranscribeFinal).not.toHaveBeenCalled();
+ expect(onTranscribeError).toHaveBeenCalledWith(providerError, {
+ options: undefined,
+ payload: transcribePayload,
+ });
+ });
+ });
});
});
diff --git a/packages/model-runtime/src/core/ModelRuntime.ts b/packages/model-runtime/src/core/ModelRuntime.ts
index 905d2a6f2a9..a6f82b897ac 100644
--- a/packages/model-runtime/src/core/ModelRuntime.ts
+++ b/packages/model-runtime/src/core/ModelRuntime.ts
@@ -112,6 +112,7 @@ export interface ModelRuntimeHooks {
payload: GenerateObjectPayload,
options?: GenerateObjectOptions,
) => Promise<void>;
+ beforeTranscribe?: (payload: ASRPayload, options?: ASROptions) => 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.
@@ -184,6 +185,21 @@ export interface ModelRuntimeHooks {
data: { speed?: ModelPerformance; usage?: ModelUsage },
context: { options?: GenerateObjectOptions; payload: GenerateObjectPayload },
) => void | Promise<void>;
+
+ onTranscribeError?: (
+ error: ChatCompletionErrorPayload,
+ context: { options?: ASROptions; payload: ASRPayload },
+ ) => void | Promise<void>;
+
+ /**
+ * Fires once after a successful transcription. `usage` is undefined when the
+ * provider reports none (e.g. duration-billed models), so consumers can still
+ * settle or release anything taken in `beforeTranscribe`.
+ */
+ onTranscribeFinal?: (
+ data: { latencyMs: number; usage?: ModelUsage },
+ context: { options?: ASROptions; payload: ASRPayload },
+ ) => void | Promise<void>;
}
export class ModelRuntime {
@@ -538,7 +554,45 @@ export class ModelRuntime {
}
async transcribe(payload: ASRPayload, options?: ASROptions) {
- return this._runtime.transcribe?.(payload, options);
+ try {
+ const hookOptions = this._hooks?.beforeTranscribe && !options ? {} : options;
+ await this._hooks?.beforeTranscribe?.(payload, hookOptions);
+
+ const startTime = Date.now();
+ let usage: ModelUsage | undefined;
+ const finalOptions = this._hooks?.onTranscribeFinal
+ ? {
+ ...hookOptions,
+ onUsage: async (reported: ModelUsage) => {
+ usage = reported;
+ await hookOptions?.onUsage?.(reported);
+ },
+ }
+ : hookOptions;
+
+ const result = await this._runtime.transcribe?.(payload, finalOptions);
+
+ if (this._hooks?.onTranscribeFinal) {
+ try {
+ await this._hooks.onTranscribeFinal(
+ { latencyMs: Date.now() - startTime, usage },
+ { options, payload },
+ );
+ } catch (e) {
+ console.error('[ModelRuntime] onTranscribeFinal hook error:', e);
+ }
+ }
+
+ return result;
+ } catch (error) {
+ if (this._hooks?.onTranscribeError) {
+ await this._hooks.onTranscribeError(error as ChatCompletionErrorPayload, {
+ options,
+ payload,
+ });
+ }
+ throw error;
+ }
}
async pullModel(params: PullModelParams, options?: ModelRequestOptions) {
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
index 36efb8a616a..bc5cf7ffd35 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
@@ -203,6 +203,39 @@ describe('createRouterRuntime', () => {
expect(mockChat).not.toHaveBeenCalled();
});
+ it('should forward transcribe metadata so lobehub route attempts carry the trigger', async () => {
+ vi.stubEnv('NODE_ENV', 'development');
+ const mockTranscribe = vi.fn().mockResolvedValue({ text: 'hello' });
+
+ class MockRuntime implements LobeRuntimeAI {
+ transcribe = mockTranscribe;
+ }
+
+ const Runtime = createRouterRuntime({
+ id: 'lobehub',
+ routers: [
+ {
+ apiType: 'openai',
+ models: ['gpt-4o-transcribe'],
+ options: { id: 'channel-1' },
+ runtime: MockRuntime as any,
+ },
+ ],
+ });
+
+ const runtime = new Runtime({ userId: 'user-1' });
+ const metadata: Record<string, unknown> = { trigger: RequestTrigger.Asr };
+
+ await expect(
+ runtime.transcribe(
+ { file: new Blob(['audio']), model: 'gpt-4o-transcribe' },
+ { metadata, user: 'user-1' },
+ ),
+ ).resolves.toEqual({ text: 'hello' });
+ expect(mockTranscribe).toHaveBeenCalled();
+ expect(metadata.routeAttempt).toEqual(expect.objectContaining({ success: true }));
+ });
+
it('should throw in development when lobehub route attempt is missing user', async () => {
vi.stubEnv('NODE_ENV', 'development');
const mockChat = vi.fn().mockResolvedValue('chat-response');
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
index 3eb490cfc73..edd4ef3a0bc 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
@@ -1379,7 +1379,7 @@ export const createRouterRuntime = ({
return this.runWithFallback(
payload.model,
(runtime) => runtime.transcribe!(payload, options),
- { method: 'transcribe', user: options?.user },
+ { metadata: options?.metadata, method: 'transcribe', user: options?.user },
);
}
};
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
index d003b2bba53..de8243ced29 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
@@ -4297,6 +4297,34 @@ describe('LobeOpenAICompatibleFactory', () => {
});
describe('transcribe', () => {
+ it('should report token usage of token-billed transcription models', async () => {
+ vi.spyOn(instance['client'].audio.transcriptions, 'create').mockResolvedValue({
+ text: 'hello world',
+ usage: { input_tokens: 151, output_tokens: 0, total_tokens: 151 },
+ } as any);
+ const onUsage = vi.fn();
+
+ const file = new File([new Uint8Array([1, 2, 3])], 'speech.m4a', { type: 'audio/mp4' });
+ await instance.transcribe!({ file, model: 'gpt-4o-transcribe' }, { onUsage });
+
+ expect(onUsage).toHaveBeenCalledWith(
+ expect.objectContaining({ inputAudioTokens: 151, totalInputTokens: 151 }),
+ );
+ });
+
+ it('should not report usage for duration-billed transcription models', async () => {
+ vi.spyOn(instance['client'].audio.transcriptions, 'create').mockResolvedValue({
+ text: 'hello world',
+ usage: { seconds: 6, type: 'duration' },
+ } as any);
+ const onUsage = vi.fn();
+
+ const file = new File([new Uint8Array([1, 2, 3])], 'speech.m4a', { type: 'audio/mp4' });
+ await instance.transcribe!({ file, model: 'whisper-1' }, { onUsage });
+
+ expect(onUsage).not.toHaveBeenCalled();
+ });
+
it('should transcribe audio and return the text', async () => {
const transcribeMock = vi
.spyOn(instance['client'].audio.transcriptions, 'create')
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
index a0f21d24e86..861adcbb8c9 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
@@ -75,7 +75,11 @@ import { resolveModelSamplingParameters } from '../parameterResolver';
import type { OpenAIStreamOptions } from '../streams';
import { OpenAIResponsesStream, OpenAIStream } from '../streams';
import { type ChatPayloadForTransformStream, readableFromAsyncIterable } from '../streams/protocol';
-import { convertOpenAIResponseUsage, convertOpenAIUsage } from '../usageConverters/openai';
+import {
+ convertOpenAIResponseUsage,
+ convertOpenAITranscriptionUsage,
+ convertOpenAIUsage,
+} from '../usageConverters/openai';
import { OpenAICompatibleClient } from './client';
import { createOpenAICompatibleImage } from './createImage';
import { createOpenAICompatibleVideo, pollOpenAICompatibleVideoStatus } from './createVideo';
@@ -1393,6 +1397,12 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
typeof transcription === 'string' ? transcription : ((transcription as any).text ?? '');
log('transcription completed, text length: %d', text.length);
+ if (options?.onUsage && typeof transcription !== 'string') {
+ const pricing = await getModelPricing(payload.model, this.id, options.pricingContext);
+ const usage = convertOpenAITranscriptionUsage((transcription as any).usage, pricing);
+ if (usage) await options.onUsage(usage);
+ }
+
return { text };
} catch (error) {
throw this.handleError(error);
diff --git a/packages/model-runtime/src/core/usageConverters/index.ts b/packages/model-runtime/src/core/usageConverters/index.ts
index 16fa397e307..f89ec801bf1 100644
--- a/packages/model-runtime/src/core/usageConverters/index.ts
+++ b/packages/model-runtime/src/core/usageConverters/index.ts
@@ -1,6 +1,10 @@
export { buildAnthropicInitialUsage, convertAnthropicUsage } from './anthropic';
export { convertGoogleAIUsage } from './google-ai';
-export { convertOpenAIResponseUsage, convertOpenAIUsage } from './openai';
+export {
+ convertOpenAIResponseUsage,
+ convertOpenAITranscriptionUsage,
+ convertOpenAIUsage,
+} from './openai';
export {
computeChatCost,
type ComputeChatCostOptions,
diff --git a/packages/model-runtime/src/core/usageConverters/openai.test.ts b/packages/model-runtime/src/core/usageConverters/openai.test.ts
index 6a6a841edc0..e4a8dd0feb9 100644
--- a/packages/model-runtime/src/core/usageConverters/openai.test.ts
+++ b/packages/model-runtime/src/core/usageConverters/openai.test.ts
@@ -2,7 +2,12 @@ import type { Pricing } from 'model-bank';
import type OpenAI from 'openai';
import { describe, expect, it } from 'vitest';
-import { convertOpenAIImageUsage, convertOpenAIResponseUsage, convertOpenAIUsage } from './openai';
+import {
+ convertOpenAIImageUsage,
+ convertOpenAIResponseUsage,
+ convertOpenAITranscriptionUsage,
+ convertOpenAIUsage,
+} from './openai';
describe('convertUsage', () => {
it('distinguishes an explicit zero cache read from missing cache usage', () => {
@@ -716,3 +721,47 @@ describe('convertOpenAIImageUsage', () => {
});
});
});
+
+describe('convertOpenAITranscriptionUsage', () => {
+ const pricing: Pricing = {
+ units: [
+ { name: 'textInput', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'audioInput', rate: 6, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textOutput', rate: 10, strategy: 'fixed', unit: 'millionTokens' },
+ ],
+ };
+
+ it('prices audio and text input separately when the modality split is reported', () => {
+ const usage = convertOpenAITranscriptionUsage(
+ {
+ input_token_details: { audio_tokens: 50, text_tokens: 9 },
+ input_tokens: 59,
+ output_tokens: 21,
+ total_tokens: 80,
+ type: 'tokens',
+ },
+ pricing,
+ );
+
+ expect(usage).toMatchObject({ inputAudioTokens: 50, inputTextTokens: 9, outputTextTokens: 21 });
+ // (50 * 6 + 9 * 2.5 + 21 * 10) / 1M = 0.0005325, rounded to 6 decimals by computeChatCost
+ expect(usage?.cost).toBe(0.000_533);
+ });
+
+ it('bills unsplit gateway input as audio', () => {
+ const usage = convertOpenAITranscriptionUsage(
+ { input_tokens: 151, output_tokens: 0, total_tokens: 151 },
+ pricing,
+ );
+
+ expect(usage).toMatchObject({ inputAudioTokens: 151, inputTextTokens: 0 });
+ expect(usage?.cost).toBe(0.000_906);
+ });
+
+ it('returns undefined for duration-billed usage', () => {
+ expect(convertOpenAITranscriptionUsage({ seconds: 6, type: 'duration' }, pricing)).toBe(
+ undefined,
+ );
+ expect(convertOpenAITranscriptionUsage(undefined, pricing)).toBe(undefined);
+ });
+});
diff --git a/packages/model-runtime/src/core/usageConverters/openai.ts b/packages/model-runtime/src/core/usageConverters/openai.ts
index c803c3bcc52..a8c0f51aa0a 100644
--- a/packages/model-runtime/src/core/usageConverters/openai.ts
+++ b/packages/model-runtime/src/core/usageConverters/openai.ts
@@ -223,3 +223,47 @@ export const convertOpenAIImageUsage = (
return withUsageCost(data as ModelUsage, pricing);
};
+
+/**
+ * Token usage of `POST /audio/transcriptions` for token-billed models such as
+ * `gpt-4o-transcribe`. Duration-billed models (`whisper-1`) report
+ * `{ type: 'duration', seconds }` instead and yield no token usage.
+ */
+interface OpenAITranscriptionTokenUsage {
+ input_token_details?: { audio_tokens?: number; text_tokens?: number };
+ input_tokens?: number;
+ output_tokens?: number;
+ total_tokens?: number;
+}
+
+export const convertOpenAITranscriptionUsage = (
+ usage: unknown,
+ pricing?: Pricing,
+): ModelUsage | undefined => {
+ if (!usage || typeof usage !== 'object') return;
+
+ const { input_token_details, input_tokens, output_tokens, total_tokens } =
+ usage as OpenAITranscriptionTokenUsage;
+ if (typeof input_tokens !== 'number') return;
+
+ const inputTextTokens = input_token_details?.text_tokens ?? 0;
+ // Some OpenAI-compatible gateways (e.g. OpenRouter) omit the modality split. The
+ // input of a transcription is the audio itself (the text prompt is optional), so
+ // bill the unsplit remainder as audio rather than at the cheaper text rate.
+ const inputAudioTokens =
+ input_token_details?.audio_tokens ?? Math.max(0, input_tokens - inputTextTokens);
+ const outputTextTokens = output_tokens ?? 0;
+
+ const data = {
+ inputAudioTokens,
+ inputTextTokens,
+ outputTextTokens,
+ totalInputTokens: input_tokens,
+ totalOutputTokens: outputTextTokens,
+ totalTokens: total_tokens ?? input_tokens + outputTextTokens,
+ } satisfies ModelTokensUsage;
+
+ log('convertOpenAITranscriptionUsage data: %O', data);
+
+ return withUsageCost(data, pricing);
+};
diff --git a/packages/model-runtime/src/providers/google/index.test.ts b/packages/model-runtime/src/providers/google/index.test.ts
index d3f976b9469..8f9f818aa4a 100644
--- a/packages/model-runtime/src/providers/google/index.test.ts
+++ b/packages/model-runtime/src/providers/google/index.test.ts
@@ -1772,6 +1772,54 @@ describe('models', () => {
expect(parts[1].text).toBeTruthy();
});
+ it('should report Gemini usage metadata of transcriptions', async () => {
+ vi.spyOn(instance['client'].models, 'generateContent').mockResolvedValue({
+ candidates: [{ content: { parts: [{ text: 'hi' }] }, finishReason: 'STOP' }],
+ text: 'hi',
+ usageMetadata: {
+ candidatesTokenCount: 5,
+ promptTokenCount: 160,
+ promptTokensDetails: [
+ { modality: 'AUDIO', tokenCount: 150 },
+ { modality: 'TEXT', tokenCount: 10 },
+ ],
+ totalTokenCount: 165,
+ },
+ } as any);
+ const onUsage = vi.fn();
+
+ const file = new File([new Uint8Array([1, 2, 3])], 'speech.m4a', { type: 'audio/mp4' });
+ const result = await instance.transcribe!(
+ { file, model: 'gemini-3.5-transcribe' },
+ { onUsage },
+ );
+
+ expect(result).toEqual({ text: 'hi' });
+ expect(onUsage).toHaveBeenCalledWith(
+ expect.objectContaining({ inputAudioTokens: 150, totalOutputTokens: 5 }),
+ );
+ });
+
+ it('should read the transcript from audioTranscription parts of dedicated ASR models', async () => {
+ vi.spyOn(instance['client'].models, 'generateContent').mockResolvedValue({
+ candidates: [
+ {
+ content: {
+ parts: [{ audioTranscription: { text: ' 帮我把登录页的按钮颜色改成蓝色。 ' } }],
+ },
+ finishReason: 'STOP',
+ },
+ ],
+ text: undefined,
+ } as any);
+
+ const file = new File([new Uint8Array([1, 2, 3])], 'speech.m4a', { type: 'audio/mp4' });
+
+ const result = await instance.transcribe!({ file, model: 'gemini-3.5-transcribe' });
+
+ expect(result).toEqual({ text: '帮我把登录页的按钮颜色改成蓝色。' });
+ });
+
it('should include the language hint when provided', async () => {
const generateContentMock = vi
.spyOn(instance['client'].models, 'generateContent')
diff --git a/packages/model-runtime/src/providers/google/index.ts b/packages/model-runtime/src/providers/google/index.ts
index 4ff4a5aba47..081ff9e2421 100644
--- a/packages/model-runtime/src/providers/google/index.ts
+++ b/packages/model-runtime/src/providers/google/index.ts
@@ -17,6 +17,7 @@ import {
} from '../../core/providerDiagnostics';
import { GoogleGenerativeAIStream } from '../../core/streams';
import { LOBE_ERROR_KEY } from '../../core/streams/google';
+import { convertGoogleAIUsage } from '../../core/usageConverters/google-ai';
import type {
ASROptions,
ASRPayload,
@@ -382,11 +383,18 @@ export class LobeGoogleAI implements LobeRuntimeAI {
*/
async transcribe(payload: ASRPayload, options?: ASROptions): Promise<ASRResponse> {
try {
- return await createGoogleTranscription(
+ const { text, usageMetadata } = await createGoogleTranscription(
this.client,
withMappedModelId(payload, this.modelIdMappingOptions),
options,
);
+
+ if (options?.onUsage && usageMetadata) {
+ const pricing = await getModelPricing(payload.model, this.provider, options.pricingContext);
+ await options.onUsage(convertGoogleAIUsage(usageMetadata, pricing));
+ }
+
+ return { text };
} catch (e) {
const err = e as Error;
diff --git a/packages/model-runtime/src/providers/google/transcribe.ts b/packages/model-runtime/src/providers/google/transcribe.ts
index 6c31b7285d0..c1f82df6365 100644
--- a/packages/model-runtime/src/providers/google/transcribe.ts
+++ b/packages/model-runtime/src/providers/google/transcribe.ts
@@ -1,4 +1,10 @@
-import type { GenerateContentConfig, GoogleGenAI, Part } from '@google/genai';
+import type {
+ GenerateContentConfig,
+ GenerateContentResponse,
+ GenerateContentResponseUsageMetadata,
+ GoogleGenAI,
+ Part,
+} from '@google/genai';
import { createPartFromUri, FileState } from '@google/genai';
import Debug from 'debug';
@@ -37,6 +43,16 @@ const guessMimeFromName = (fileName?: string): string | undefined => {
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+/**
+ * Dedicated speech-to-text models (e.g. `gemini-3.5-transcribe`) return the
+ * transcript in `Part.audioTranscription` instead of a text part, so
+ * `response.text` is empty for them.
+ */
+const getAudioTranscriptionText = (response: GenerateContentResponse): string =>
+ response.candidates?.[0]?.content?.parts
+ ?.map((part) => part.audioTranscription?.text ?? '')
+ .join('') ?? '';
+
/**
* Upload audio via the Gemini Files API and wait until it is processed, then
* reference it by URI. Used for payloads too large for an inline request.
@@ -80,7 +96,7 @@ export const createGoogleTranscription = async (
client: GoogleGenAI,
payload: ASRPayload,
options?: ASROptions,
-): Promise<ASRResponse> => {
+): Promise<ASRResponse & { usageMetadata?: GenerateContentResponseUsageMetadata }> => {
const { file, fileName, model, language, prompt } = payload;
const mimeType = file.type || guessMimeFromName(fileName ?? (file as File).name) || 'audio/mp3';
@@ -114,8 +130,8 @@ export const createGoogleTranscription = async (
model,
});
- const text = (response.text ?? '').trim();
+ const text = (response.text || getAudioTranscriptionText(response)).trim();
debug('transcription completed, text length %d', text.length);
- return { text };
+ return { text, usageMetadata: response.usageMetadata };
};
diff --git a/packages/model-runtime/src/types/asr.ts b/packages/model-runtime/src/types/asr.ts
index 67bf14990de..65ba63cb6c1 100644
--- a/packages/model-runtime/src/types/asr.ts
+++ b/packages/model-runtime/src/types/asr.ts
@@ -1,3 +1,7 @@
+import type { ModelUsage } from '@lobechat/types';
+
+import type { ModelPricingContext } from './pricing';
+
export interface ASRPayload {
/**
* The audio content to transcribe. A `File` is passed through as-is; any other
@@ -32,6 +36,14 @@ export interface ASRPayload {
export interface ASROptions {
headers?: Record<string, any>;
+ /** Metadata passed to hooks (billing, tracing, route attempts), e.g. `trigger`. */
+ metadata?: Record<string, unknown>;
+ /**
+ * Receives the provider-reported token usage (with `cost` when the model has
+ * pricing) after a successful transcription.
+ */
+ onUsage?: (usage: ModelUsage) => void | Promise<void>;
+ pricingContext?: ModelPricingContext;
signal?: AbortSignal;
/**
* userId for the request
diff --git a/packages/types/src/agentRuntime.ts b/packages/types/src/agentRuntime.ts
index d972ebb055a..1195c3fa978 100644
--- a/packages/types/src/agentRuntime.ts
+++ b/packages/types/src/agentRuntime.ts
@@ -18,6 +18,8 @@ export enum RequestTrigger {
AgentShare = 'agent_share',
AgentSignal = 'agent_signal',
Api = 'api',
+ /** Speech-to-text transcription, e.g. voice messages and `lh generate asr`. */
+ Asr = 'asr',
Bot = 'bot',
/** Agent builder suggestion chips. */
BuilderSuggestion = 'builder_suggestion',