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(model-runtime): add ASR (transcribe) with OpenAI + Gemini-native backends, expose via tRPC (#15992)

Arvin Xu09ba6cd69bbc
diff --git a/apps/cli/src/commands/generate.test.ts b/apps/cli/src/commands/generate.test.ts
index 478c2272902..edb80e96089 100644
--- a/apps/cli/src/commands/generate.test.ts
+++ b/apps/cli/src/commands/generate.test.ts
@@ -1,3 +1,7 @@
+import { rm as fsRm, writeFile as fsWriteFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
import { Command } from 'commander';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -6,6 +10,9 @@ import { registerGenerateCommand } from './generate';
const { mockTrpcClient } = vi.hoisted(() => ({
mockTrpcClient: {
+ asr: {
+ transcribe: { mutate: vi.fn() },
+ },
generation: {
deleteGeneration: { mutate: vi.fn() },
getGenerationStatus: { query: vi.fn() },
@@ -35,6 +42,15 @@ const { writeFileSync: mockWriteFileSync } = vi.hoisted(() => ({
writeFileSync: vi.fn(),
}));
+const { uploadLocalFile: mockUploadLocalFile } = vi.hoisted(() => ({
+ uploadLocalFile: vi.fn(),
+}));
+
+vi.mock('../utils/uploadLocalFile', async (importOriginal) => {
+ const actual: Record<string, unknown> = await importOriginal();
+ return { ...actual, uploadLocalFile: mockUploadLocalFile };
+});
+
vi.mock('../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));
vi.mock('../api/http', () => ({ getAuthInfo: mockGetAuthInfo }));
vi.mock('node:fs', async (importOriginal) => {
@@ -370,20 +386,39 @@ describe('generate command', () => {
expect(exitSpy).toHaveBeenCalledWith(1);
});
+ it('should upload large local audio and transcribe by fileId', async () => {
+ // Real >3MB temp file so existsSync/statSync (unmocked) see it as large.
+ const bigPath = path.join(os.tmpdir(), `lh-asr-test-${process.pid}-${Date.now()}.mp3`);
+ await fsWriteFile(bigPath, Buffer.alloc(4 * 1024 * 1024));
+ mockUploadLocalFile.mockResolvedValue({ id: 'file_999' });
+ mockTrpcClient.asr.transcribe.mutate.mockResolvedValue({ text: 'big result' });
+
+ try {
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'generate', 'asr', bigPath]);
+
+ expect(mockUploadLocalFile).toHaveBeenCalledWith(expect.anything(), bigPath);
+ expect(mockTrpcClient.asr.transcribe.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ fileId: 'file_999', model: 'whisper-1', provider: 'openai' }),
+ );
+ // never inlines bytes for the large file
+ expect(mockTrpcClient.asr.transcribe.mutate.mock.calls[0][0]).not.toHaveProperty(
+ 'audioBase64',
+ );
+ expect(stdoutSpy).toHaveBeenCalledWith('big result');
+ } finally {
+ await fsRm(bigPath, { force: true });
+ }
+ });
+
it('should download and transcribe an audio URL', async () => {
- const fetchMock = vi
- .fn()
- // first call: download the remote audio
- .mockResolvedValueOnce({
- blob: vi.fn().mockResolvedValue(new Blob(['audio-bytes'])),
- ok: true,
- })
- // second call: STT endpoint
- .mockResolvedValueOnce({
- json: vi.fn().mockResolvedValue({ text: 'hello world' }),
- ok: true,
- });
+ const fetchMock = vi.fn().mockResolvedValue({
+ arrayBuffer: vi.fn().mockResolvedValue(new TextEncoder().encode('audio-bytes').buffer),
+ headers: new Headers(),
+ ok: true,
+ });
vi.stubGlobal('fetch', fetchMock);
+ mockTrpcClient.asr.transcribe.mutate.mockResolvedValue({ text: 'hello world' });
const program = createProgram();
await program.parseAsync([
@@ -394,16 +429,68 @@ describe('generate command', () => {
'https://example.com/audio/sample.mp3',
]);
- expect(fetchMock).toHaveBeenNthCalledWith(1, 'https://example.com/audio/sample.mp3');
- expect(fetchMock).toHaveBeenNthCalledWith(
- 2,
- 'https://app.lobehub.com/webapi/stt/openai',
- expect.objectContaining({ method: 'POST' }),
+ expect(fetchMock).toHaveBeenCalledWith('https://example.com/audio/sample.mp3');
+ expect(mockTrpcClient.asr.transcribe.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ audioBase64: Buffer.from('audio-bytes').toString('base64'),
+ fileName: 'sample.mp3',
+ model: 'whisper-1',
+ provider: 'openai',
+ }),
);
expect(stdoutSpy).toHaveBeenCalledWith('hello world');
expect(exitSpy).not.toHaveBeenCalled();
});
+ it('should derive an extension and mime type from Content-Type when the URL has none', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue({
+ arrayBuffer: vi.fn().mockResolvedValue(new TextEncoder().encode('audio-bytes').buffer),
+ headers: new Headers({ 'content-type': 'audio/mpeg; charset=binary' }),
+ ok: true,
+ }),
+ );
+ mockTrpcClient.asr.transcribe.mutate.mockResolvedValue({ text: 'ok' });
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'generate', 'asr', 'https://example.com/download']);
+
+ expect(mockTrpcClient.asr.transcribe.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ fileName: 'download.mp3',
+ mimeType: 'audio/mpeg',
+ }),
+ );
+ });
+
+ it('should prefer the filename from Content-Disposition', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue({
+ arrayBuffer: vi.fn().mockResolvedValue(new TextEncoder().encode('audio-bytes').buffer),
+ headers: new Headers({
+ 'content-disposition': 'attachment; filename="recording.wav"',
+ }),
+ ok: true,
+ }),
+ );
+ mockTrpcClient.asr.transcribe.mutate.mockResolvedValue({ text: 'ok' });
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'generate',
+ 'asr',
+ 'https://example.com/files/abc123?sig=xyz',
+ ]);
+
+ expect(mockTrpcClient.asr.transcribe.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ fileName: 'recording.wav' }),
+ );
+ });
+
it('should exit when audio URL download fails', async () => {
vi.stubGlobal(
'fetch',
diff --git a/apps/cli/src/commands/generate/asr.ts b/apps/cli/src/commands/generate/asr.ts
index ad66b7e20ea..602cc165328 100644
--- a/apps/cli/src/commands/generate/asr.ts
+++ b/apps/cli/src/commands/generate/asr.ts
@@ -1,10 +1,18 @@
-import { createReadStream, existsSync } from 'node:fs';
+import { existsSync, statSync } from 'node:fs';
+import { readFile, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
import path from 'node:path';
import type { Command } from 'commander';
-import { getAuthInfo } from '../../api/http';
+import { getTrpcClient } from '../../api/client';
import { log } from '../../utils/logger';
+import { uploadLocalFile } from '../../utils/uploadLocalFile';
+
+// Audio at or below this size is sent inline as base64; anything larger is
+// uploaded first and transcribed by `fileId`. Kept in sync with the server-side
+// inline cap in `apps/server/src/routers/lambda/asr.ts`.
+const MAX_INLINE_AUDIO_BYTES = 3 * 1024 * 1024;
export function registerAsrCommand(parent: Command) {
parent
@@ -13,6 +21,7 @@ export function registerAsrCommand(parent: Command) {
'Convert speech to text (automatic speech recognition). Accepts a local path or a URL',
)
.option('--model <model>', 'STT model', 'whisper-1')
+ .option('--provider <provider>', 'AI provider', 'openai')
.option('--language <lang>', 'Language code (e.g. en, zh)')
.option('--json', 'Output raw JSON')
.action(
@@ -22,6 +31,7 @@ export function registerAsrCommand(parent: Command) {
json?: boolean;
language?: string;
model: string;
+ provider: string;
},
) => {
const isUrl = audioFile.startsWith('http://') || audioFile.startsWith('https://');
@@ -32,19 +42,26 @@ export function registerAsrCommand(parent: Command) {
return;
}
- const { serverUrl, headers } = await getAuthInfo();
-
- const sttOptions: Record<string, any> = { model: options.model };
- if (options.language) sttOptions.language = options.language;
-
- let fileBuffer: Blob;
+ // Resolve the input to a local file path (downloading URLs to a temp
+ // file) so large audio can reuse the shared upload flow.
+ let localPath: string;
let fileName: string;
+ let mimeType: string | undefined;
+ let size: number;
+ let tempPath: string | undefined;
try {
if (isUrl) {
- ({ blob: fileBuffer, name: fileName } = await fetchAudioFromUrl(audioFile));
+ const downloaded = await fetchAudioFromUrl(audioFile);
+ fileName = downloaded.name;
+ mimeType = downloaded.mimeType;
+ size = downloaded.bytes.byteLength;
+ tempPath = path.join(os.tmpdir(), `lh-asr-${process.pid}-${Date.now()}-${fileName}`);
+ await writeFile(tempPath, downloaded.bytes);
+ localPath = tempPath;
} else {
- fileBuffer = await readFileAsBlob(audioFile);
+ localPath = audioFile;
fileName = path.basename(audioFile);
+ size = statSync(audioFile).size;
}
} catch (error) {
log.error(error instanceof Error ? error.message : String(error));
@@ -52,65 +69,137 @@ export function registerAsrCommand(parent: Command) {
return;
}
- const formData = new FormData();
- formData.append('speech', fileBuffer, fileName);
- formData.append('options', JSON.stringify(sttOptions));
-
- // Remove Content-Type for multipart/form-data (let fetch set it with boundary)
- const { 'Content-Type': _, ...formHeaders } = headers;
-
- const res = await fetch(`${serverUrl}/webapi/stt/openai`, {
- body: formData,
- headers: formHeaders,
- method: 'POST',
- });
+ try {
+ const client = await getTrpcClient();
+
+ let result: { text: string };
+ if (size > MAX_INLINE_AUDIO_BYTES) {
+ // Large audio: upload to storage, then transcribe by fileId so the
+ // bytes never travel inline through tRPC.
+ process.stderr.write(
+ `Audio is ${(size / 1024 / 1024).toFixed(1)}MB — uploading before transcription…\n`,
+ );
+ const record = (await uploadLocalFile(client, localPath)) as { id: string };
+ result = await client.asr.transcribe.mutate({
+ fileId: record.id,
+ language: options.language,
+ model: options.model,
+ provider: options.provider,
+ });
+ } else {
+ const bytes = await readFile(localPath);
+ result = await client.asr.transcribe.mutate({
+ audioBase64: Buffer.from(bytes).toString('base64'),
+ fileName,
+ language: options.language,
+ mimeType,
+ model: options.model,
+ provider: options.provider,
+ });
+ }
- if (!res.ok) {
- const errText = await res.text();
- log.error(`ASR failed: ${res.status} ${errText}`);
+ if (options.json) {
+ console.log(JSON.stringify(result, null, 2));
+ } else {
+ process.stdout.write(result.text);
+ process.stdout.write('\n');
+ }
+ } catch (error) {
+ log.error(`ASR failed: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
- return;
- }
-
- const result = await res.json();
-
- if (options.json) {
- console.log(JSON.stringify(result, null, 2));
- } else {
- const text = (result as any).text || JSON.stringify(result);
- process.stdout.write(text);
- process.stdout.write('\n');
+ } finally {
+ if (tempPath) {
+ await rm(tempPath, { force: true }).catch(() => {});
+ }
}
},
);
}
-async function readFileAsBlob(filePath: string): Promise<Blob> {
- const chunks: Uint8Array[] = [];
- const stream = createReadStream(filePath);
- for await (const chunk of stream) {
- chunks.push(chunk as Uint8Array);
- }
- return new Blob(chunks);
-}
-
-async function fetchAudioFromUrl(url: string): Promise<{ blob: Blob; name: string }> {
+// Common audio MIME types mapped to a file extension the transcription
+// provider can recognize. Keep the extensions within the set OpenAI's
+// /audio/transcriptions endpoint accepts.
+const AUDIO_MIME_TO_EXT: Record<string, string> = {
+ 'audio/aac': 'aac',
+ 'audio/flac': 'flac',
+ 'audio/m4a': 'm4a',
+ 'audio/mp3': 'mp3',
+ 'audio/mp4': 'm4a',
+ 'audio/mpeg': 'mp3',
+ 'audio/mpga': 'mp3',
+ 'audio/ogg': 'ogg',
+ 'audio/opus': 'ogg',
+ 'audio/wav': 'wav',
+ 'audio/wave': 'wav',
+ 'audio/webm': 'webm',
+ 'audio/x-m4a': 'm4a',
+ 'audio/x-wav': 'wav',
+};
+
+async function fetchAudioFromUrl(
+ url: string,
+): Promise<{ bytes: Uint8Array; mimeType?: string; name: string }> {
const res = await fetch(url);
if (!res.ok) {
throw new Error(`Failed to download audio: ${res.status} ${res.statusText}`);
}
- const blob = await res.blob();
+ const bytes = new Uint8Array(await res.arrayBuffer());
+
+ // Strip any parameters from the Content-Type (e.g. `audio/mpeg; charset=...`).
+ const contentType = res.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();
+ const mimeType = contentType?.startsWith('audio/') ? contentType : undefined;
+
+ // Prefer the name the server advertises, then the URL path, then a fallback.
+ const name =
+ fileNameFromContentDisposition(res.headers.get('content-disposition')) ||
+ basenameFromUrl(url) ||
+ 'audio';
+
+ // Transcription providers infer the audio format from the file extension, so
+ // make sure the name carries one. Signed URLs and /download endpoints often
+ // have no extension in the path — in that case borrow it from the
+ // Content-Type when we recognize it.
+ const ext = contentType ? AUDIO_MIME_TO_EXT[contentType] : undefined;
+ const finalName = path.extname(name) || !ext ? name : `${name}.${ext}`;
+
+ return { bytes, mimeType, name: finalName };
+}
- // Derive a file name from the URL path, falling back to a generic name.
- const pathname = (() => {
+// Extract a file name from a Content-Disposition header, handling both the
+// plain `filename="x"` form and the RFC 5987 extended `filename*=UTF-8''x` form.
+function fileNameFromContentDisposition(header: string | null): string | undefined {
+ if (!header) return undefined;
+
+ // Extended form takes precedence and may be percent-encoded.
+ const extended = /filename\*=\s*(?:UTF-8|ISO-8859-1)?''([^;]+)/i.exec(header);
+ if (extended?.[1]) {
try {
- return new URL(url).pathname;
+ return path.basename(decodeURIComponent(extended[1].trim()));
} catch {
- return '';
+ // Malformed encoding — fall through to the plain form.
}
- })();
- const name = path.basename(pathname) || 'audio';
+ }
+
+ const plain = /filename=\s*"?([^";]+)"?/i.exec(header);
+ const value = plain?.[1]?.trim();
+ return value ? path.basename(value) : undefined;
+}
- return { blob, name };
+// Derive the (URL-decoded) last path segment of a URL, if any.
+function basenameFromUrl(url: string): string | undefined {
+ let pathname: string;
+ try {
+ pathname = new URL(url).pathname;
+ } catch {
+ return undefined;
+ }
+
+ const base = path.basename(pathname);
+ if (!base) return undefined;
+ try {
+ return decodeURIComponent(base);
+ } catch {
+ return base;
+ }
}
diff --git a/apps/cli/src/utils/uploadLocalFile.ts b/apps/cli/src/utils/uploadLocalFile.ts
index 0a7a5d3701a..f87ac65f30f 100644
--- a/apps/cli/src/utils/uploadLocalFile.ts
+++ b/apps/cli/src/utils/uploadLocalFile.ts
@@ -9,21 +9,27 @@ import type { TrpcClient } from '../api/client';
* Unknown extensions fall back to `application/octet-stream`.
*/
const MIME_MAP: Record<string, string> = {
+ aac: 'audio/aac',
csv: 'text/csv',
doc: 'application/msword',
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ flac: 'audio/flac',
gif: 'image/gif',
jpeg: 'image/jpeg',
jpg: 'image/jpeg',
json: 'application/json',
+ m4a: 'audio/mp4',
md: 'text/markdown',
mp3: 'audio/mpeg',
mp4: 'video/mp4',
+ ogg: 'audio/ogg',
pdf: 'application/pdf',
png: 'image/png',
pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
svg: 'image/svg+xml',
txt: 'text/plain',
+ wav: 'audio/wav',
+ webm: 'audio/webm',
webp: 'image/webp',
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
};
diff --git a/apps/server/src/routers/lambda/__tests__/asr.test.ts b/apps/server/src/routers/lambda/__tests__/asr.test.ts
new file mode 100644
index 00000000000..6893b72238c
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/asr.test.ts
@@ -0,0 +1,118 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { asrRouter } from '../asr';
+
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(() => ({})),
+}));
+
+const transcribeMock = vi.fn();
+vi.mock('@/server/modules/ModelRuntime', () => ({
+ initModelRuntimeFromDB: vi.fn(async () => ({ transcribe: transcribeMock })),
+}));
+
+const findByIdMock = vi.fn();
+vi.mock('@/database/models/file', () => ({
+ FileModel: vi.fn(() => ({ findById: findByIdMock })),
+}));
+
+const getFileByteArrayMock = vi.fn();
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn(() => ({ getFileByteArray: getFileByteArrayMock })),
+}));
+
+const caller = asrRouter.createCaller({ jwtPayload: { userId: 'u1' }, userId: 'u1' } as any);
+
+beforeEach(() => {
+ transcribeMock.mockResolvedValue({ text: 'hello world' });
+});
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('asrRouter.transcribe', () => {
+ it('transcribes inline base64 audio', async () => {
+ const res = await caller.transcribe({
+ audioBase64: Buffer.from('audio-bytes').toString('base64'),
+ fileName: 'clip.mp3',
+ model: 'whisper-1',
+ provider: 'openai',
+ });
+
+ expect(res).toEqual({ text: 'hello world' });
+ expect(findByIdMock).not.toHaveBeenCalled();
+
+ const payload = transcribeMock.mock.calls[0][0];
+ expect(payload.file).toBeInstanceOf(File);
+ expect(payload.fileName).toBe('clip.mp3');
+ expect(await payload.file.text()).toBe('audio-bytes');
+ });
+
+ it('resolves a fileId by downloading the bytes from storage', async () => {
+ findByIdMock.mockResolvedValue({
+ fileType: 'audio/mp4',
+ name: 'meeting.m4a',
+ url: 's3-key/meeting.m4a',
+ });
+ getFileByteArrayMock.mockResolvedValue(new Uint8Array(Buffer.from('from-s3')));
+
+ const res = await caller.transcribe({ fileId: 'file_123', model: 'whisper-1' });
+
+ expect(res).toEqual({ text: 'hello world' });
+ expect(findByIdMock).toHaveBeenCalledWith('file_123');
+ expect(getFileByteArrayMock).toHaveBeenCalledWith('s3-key/meeting.m4a');
+
+ const payload = transcribeMock.mock.calls[0][0];
+ expect(payload.fileName).toBe('meeting.m4a');
+ expect(payload.file.type).toBe('audio/mp4');
+ expect(await payload.file.text()).toBe('from-s3');
+ });
+
+ it('rejects when neither fileId nor audioBase64 is provided', async () => {
+ await expect(caller.transcribe({ model: 'whisper-1' } as any)).rejects.toThrow();
+ });
+
+ it('rejects oversized inline base64 and guides to fileId', async () => {
+ // > 3MB decoded → base64 string exceeds the cap
+ const tooBig = 'A'.repeat(5 * 1024 * 1024);
+
+ await expect(caller.transcribe({ audioBase64: tooBig, model: 'whisper-1' })).rejects.toThrow(
+ /fileId/i,
+ );
+ expect(transcribeMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects when both fileId and audioBase64 are provided', async () => {
+ await expect(
+ caller.transcribe({
+ audioBase64: Buffer.from('x').toString('base64'),
+ fileId: 'file_123',
+ model: 'whisper-1',
+ } as any),
+ ).rejects.toThrow();
+ });
+
+ it('throws NOT_FOUND when the fileId does not exist', async () => {
+ findByIdMock.mockResolvedValue(undefined);
+
+ await expect(caller.transcribe({ fileId: 'missing', model: 'whisper-1' })).rejects.toThrow(
+ /not found/i,
+ );
+ expect(getFileByteArrayMock).not.toHaveBeenCalled();
+ });
+
+ it('throws NOT_FOUND when the stored object is gone (NoSuchKey)', async () => {
+ findByIdMock.mockResolvedValue({
+ fileType: 'audio/mp4',
+ name: 'gone.m4a',
+ url: 's3-key/gone.m4a',
+ });
+ getFileByteArrayMock.mockRejectedValue({ Code: 'NoSuchKey' });
+
+ await expect(caller.transcribe({ fileId: 'file_x', model: 'whisper-1' })).rejects.toThrow(
+ /no longer available/i,
+ );
+ });
+});
diff --git a/apps/server/src/routers/lambda/asr.ts b/apps/server/src/routers/lambda/asr.ts
new file mode 100644
index 00000000000..3bd09c94cd4
--- /dev/null
+++ b/apps/server/src/routers/lambda/asr.ts
@@ -0,0 +1,161 @@
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { FileModel } from '@/database/models/file';
+import type { LobeChatDatabase } from '@/database/type';
+import { router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
+import { FileService } from '@/server/services/file';
+
+const asrProcedure = wsCompatProcedure.use(serverDatabase);
+
+// Inline base64 is only for short clips. The whole request must fit inside the
+// platform body limit (≈4.5MB on serverless deploys) and base64 inflates bytes
+// by ~4/3, so cap the decoded audio well under that — anything larger should be
+// uploaded and passed as `fileId`.
+const MAX_INLINE_AUDIO_BYTES = 3 * 1024 * 1024;
+// base64 length ≈ ceil(bytes / 3) * 4; validating the string length lets us
+// reject oversized payloads before allocating/decoding them.
+const MAX_INLINE_AUDIO_BASE64_CHARS = Math.ceil(MAX_INLINE_AUDIO_BYTES / 3) * 4;
+
+interface ResolvedAudio {
+ bytes: Uint8Array;
+ fileName: string;
+ mimeType?: string;
+}
+
+export const asrRouter = router({
+ /**
+ * Automatic Speech Recognition (speech-to-text).
+ *
+ * Accepts the audio either as an already-uploaded `fileId` (preferred — the
+ * server streams the bytes from storage, nothing large travels over tRPC) or
+ * inline as base64 for short clips (capped at `MAX_INLINE_AUDIO_BYTES`;
+ * larger payloads are rejected with guidance to upload and pass `fileId`).
+ *
+ * Note on base64: tRPC here uses an `httpLink` + superjson (JSON only), which
+ * has no binary representation for a `Buffer`/`Uint8Array` — a raw buffer would
+ * serialize to a per-byte JSON object, far worse than base64. So inline bytes
+ * stay base64; use `fileId` to avoid inlining entirely.
+ *
+ * Transcription is a single request/response (not streamed), so a mutation is
+ * the right shape.
+ */
+ transcribe: asrProcedure
+ .input(
+ z
+ .object({
+ /** Base64-encoded audio bytes (short clips only). Mutually exclusive with `fileId`. */
+ audioBase64: z
+ .string()
+ .min(1)
+ .max(MAX_INLINE_AUDIO_BASE64_CHARS, {
+ message: `Inline audio is limited to ${MAX_INLINE_AUDIO_BYTES / 1024 / 1024}MB. Upload the file and pass \`fileId\` instead.`,
+ })
+ .optional(),
+ /** Already-uploaded audio file id. Mutually exclusive with `audioBase64`. */
+ fileId: z.string().min(1).optional(),
+ /** Original file name (base64 path); its extension helps format detection. */
+ fileName: z.string().optional(),
+ /** ISO-639-1 language code (e.g. `en`, `zh`). */
+ language: z.string().optional(),
+ /** Audio mime type (base64 path, e.g. `audio/mp4`). */
+ mimeType: z.string().optional(),
+ model: z.string().min(1),
+ /** Optional text to guide the model's style. */
+ prompt: z.string().optional(),
+ provider: z.string().default('openai'),
+ responseFormat: z.enum(['json', 'srt', 'text', 'verbose_json', 'vtt']).optional(),
+ })
+ .refine((d) => Boolean(d.fileId) !== Boolean(d.audioBase64), {
+ message: 'Provide exactly one of `fileId` or `audioBase64`.',
+ }),
+ )
+ .mutation(async ({ ctx, input }): Promise<{ text: string }> => {
+ const workspaceId = ctx.workspaceId ?? undefined;
+
+ const { bytes, fileName, mimeType } = await resolveAudio(ctx, input, workspaceId);
+
+ // Resolve the user's provider config (key + baseURL) from the database,
+ // falling back to server env keys, exactly like chat/embeddings do.
+ const runtime = await initModelRuntimeFromDB(
+ ctx.serverDB,
+ ctx.userId,
+ input.provider,
+ workspaceId,
+ );
+
+ // `Uint8Array` is a valid BlobPart at runtime; the cast sidesteps the
+ // `Uint8Array<ArrayBufferLike>` vs BlobPart generic mismatch in lib.dom.
+ const file = new File([bytes as BlobPart], fileName, {
+ type: mimeType || 'application/octet-stream',
+ });
+
+ const result = await runtime.transcribe(
+ {
+ file,
+ fileName,
+ language: input.language,
+ model: input.model,
+ prompt: input.prompt,
+ responseFormat: input.responseFormat,
+ },
+ { user: ctx.userId },
+ );
+
+ if (!result) {
+ throw new TRPCError({
+ code: 'NOT_IMPLEMENTED',
+ message: `Provider "${input.provider}" does not support ASR.`,
+ });
+ }
+
+ return result;
+ }),
+});
+
+/**
+ * Turn the request into raw audio bytes + metadata, from either a stored file
+ * (downloaded from S3, ownership enforced by the userId-scoped FileModel) or the
+ * inline base64 payload.
+ */
+async function resolveAudio(
+ ctx: { serverDB: LobeChatDatabase; userId: string },
+ input: { audioBase64?: string; fileId?: string; fileName?: string; mimeType?: string },
+ workspaceId?: string,
+): Promise<ResolvedAudio> {
+ if (input.fileId) {
+ const fileModel = new FileModel(ctx.serverDB, ctx.userId, workspaceId);
+ const fileItem = await fileModel.findById(input.fileId);
+
+ if (!fileItem) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: `File "${input.fileId}" not found.` });
+ }
+
+ const fileService = new FileService(ctx.serverDB, ctx.userId, workspaceId);
+ let bytes: Uint8Array;
+ try {
+ bytes = await fileService.getFileByteArray(fileItem.url);
+ } catch (error) {
+ if ((error as { Code?: string }).Code === 'NoSuchKey') {
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: `File "${input.fileId}" is no longer available in storage.`,
+ });
+ }
+ throw error;
+ }
+
+ return { bytes, fileName: fileItem.name, mimeType: fileItem.fileType };
+ }
+
+ return {
+ bytes: new Uint8Array(Buffer.from(input.audioBase64!, 'base64')),
+ fileName: input.fileName || 'audio',
+ mimeType: input.mimeType,
+ };
+}
+
+export type AsrRouter = typeof asrRouter;
diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.ts
index 146bec470ec..11dc29cf945 100644
--- a/apps/server/src/routers/lambda/index.ts
+++ b/apps/server/src/routers/lambda/index.ts
@@ -32,6 +32,7 @@ import { aiChatRouter } from './aiChat';
import { aiModelRouter } from './aiModel';
import { aiProviderRouter } from './aiProvider';
import { apiKeyRouter } from './apiKey';
+import { asrRouter } from './asr';
import { botMessageRouter } from './botMessage';
import { briefRouter } from './brief';
import { changelogRouter } from './changelog';
@@ -98,6 +99,7 @@ export const lambdaRouter = router({
aiModel: aiModelRouter,
aiProvider: aiProviderRouter,
apiKey: apiKeyRouter,
+ asr: asrRouter,
chunk: chunkRouter,
comfyui: comfyuiRouter,
config: configRouter,
diff --git a/packages/model-runtime/src/core/BaseAI.ts b/packages/model-runtime/src/core/BaseAI.ts
index b2099658f71..5865fbd0338 100644
--- a/packages/model-runtime/src/core/BaseAI.ts
+++ b/packages/model-runtime/src/core/BaseAI.ts
@@ -2,6 +2,9 @@ import type { AIBaseModelCard } from 'model-bank';
import type OpenAI from 'openai';
import type {
+ ASROptions,
+ ASRPayload,
+ ASRResponse,
ChatMethodOptions,
ChatStreamPayload,
CreateImageMethodOptions,
@@ -64,6 +67,8 @@ export interface LobeRuntimeAI {
payload: TextToSpeechPayload,
options?: TextToSpeechOptions,
) => Promise<ArrayBuffer>;
+
+ transcribe?: (payload: ASRPayload, options?: ASROptions) => Promise<ASRResponse>;
}
/* eslint-enabled */
@@ -84,4 +89,8 @@ export abstract class LobeOpenAICompatibleRuntime {
payload: EmbeddingsPayload,
options?: EmbeddingsOptions,
): Promise<Embeddings[]>;
+
+ transcribe?(payload: ASRPayload, options?: ASROptions): Promise<ASRResponse>;
+
+ textToSpeech?(payload: TextToSpeechPayload, options?: TextToSpeechOptions): Promise<ArrayBuffer>;
}
diff --git a/packages/model-runtime/src/core/ModelRuntime.ts b/packages/model-runtime/src/core/ModelRuntime.ts
index 4218617d6f6..78ba41b591d 100644
--- a/packages/model-runtime/src/core/ModelRuntime.ts
+++ b/packages/model-runtime/src/core/ModelRuntime.ts
@@ -7,6 +7,8 @@ import type { LobeCloudflareParams } from '../providers/cloudflare';
import { LobeOpenAI } from '../providers/openai';
import { providerRuntimeMap } from '../runtimeMap';
import type {
+ ASROptions,
+ ASRPayload,
ChatCompletionErrorPayload,
ChatMethodOptions,
ChatStreamPayload,
@@ -450,6 +452,10 @@ export class ModelRuntime {
return this._runtime.textToSpeech?.(payload, options);
}
+ async transcribe(payload: ASRPayload, options?: ASROptions) {
+ return this._runtime.transcribe?.(payload, options);
+ }
+
async pullModel(params: PullModelParams, options?: ModelRequestOptions) {
return this._runtime.pullModel?.(params, options);
}
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
index dc1d9e9c908..bef0a411fd4 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
@@ -13,6 +13,8 @@ import type { Stream } from 'openai/streaming';
import { LobeOpenAI } from '../../providers/openai';
import { LobeVertexAI } from '../../providers/vertexai';
import type {
+ ASROptions,
+ ASRPayload,
ChatCompletionErrorPayload,
ChatMethodOptions,
ChatStreamCallbacks,
@@ -771,6 +773,12 @@ export const createRouterRuntime = ({
runtime.textToSpeech!(payload, options),
);
}
+
+ async transcribe(payload: ASRPayload, options?: ASROptions) {
+ return this.runWithFallback(payload.model, (runtime) =>
+ runtime.transcribe!(payload, options),
+ );
+ }
};
};
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
index fc2d724342c..4c80ff60123 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
@@ -3511,4 +3511,76 @@ describe('LobeOpenAICompatibleFactory', () => {
]);
});
});
+
+ describe('transcribe', () => {
+ it('should transcribe audio and return the text', async () => {
+ const transcribeMock = vi
+ .spyOn(instance['client'].audio.transcriptions, 'create')
+ .mockResolvedValue({ text: 'hello world' } as any);
+
+ const file = new File([new Uint8Array([1, 2, 3])], 'speech.mp3', { type: 'audio/mpeg' });
+
+ const result = await instance.transcribe!({ file, model: 'whisper-1' });
+
+ expect(result).toEqual({ text: 'hello world' });
+ expect(transcribeMock).toHaveBeenCalledWith(
+ expect.objectContaining({ file, model: 'whisper-1' }),
+ expect.anything(),
+ );
+ });
+
+ it('should forward language, prompt and responseFormat to the provider', async () => {
+ const transcribeMock = vi
+ .spyOn(instance['client'].audio.transcriptions, 'create')
+ .mockResolvedValue({ text: '你好' } as any);
+
+ const file = new File([new Uint8Array([1, 2, 3])], 'speech.m4a', { type: 'audio/mp4' });
+
+ await instance.transcribe!(
+ {
+ file,
+ language: 'zh',
+ model: 'whisper-1',
+ prompt: 'hint',
+ responseFormat: 'verbose_json',
+ },
+ { signal: new AbortController().signal },
+ );
+
+ expect(transcribeMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ file,
+ language: 'zh',
+ model: 'whisper-1',
+ prompt: 'hint',
+ response_format: 'verbose_json',
+ }),
+ expect.objectContaining({ signal: expect.any(AbortSignal) }),
+ );
+ });
+
+ it('should wrap a bare Blob into a File using fileName', async () => {
+ const transcribeMock = vi
+ .spyOn(instance['client'].audio.transcriptions, 'create')
+ .mockResolvedValue({ text: 'ok' } as any);
+
+ const blob = new Blob([new Uint8Array([1, 2, 3])], { type: 'audio/wav' });
+
+ await instance.transcribe!({ file: blob, fileName: 'remote.wav', model: 'whisper-1' });
+
+ const passedFile = (transcribeMock.mock.calls[0][0] as any).file as File;
+ expect(passedFile).toBeInstanceOf(File);
+ expect(passedFile.name).toBe('remote.wav');
+ });
+
+ it('should throw an error when transcription fails', async () => {
+ vi.spyOn(instance['client'].audio.transcriptions, 'create').mockRejectedValue(
+ new Error('boom'),
+ );
+
+ const file = new File([new Uint8Array([1, 2, 3])], 'speech.mp3', { type: 'audio/mpeg' });
+
+ await expect(instance.transcribe!({ file, model: 'whisper-1' })).rejects.toBeDefined();
+ });
+ });
});
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
index c44a2a8a698..e7af2f7373e 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
@@ -11,6 +11,9 @@ import type { Stream } from 'openai/streaming';
import { isGPT5ProResponsesModel, responsesAPIModels } from '../../const/models';
import { ErrorClassifier } from '../../errors';
import type {
+ ASROptions,
+ ASRPayload,
+ ASRResponse,
ChatCompletionErrorPayload,
ChatCompletionTool,
ChatMethodOptions,
@@ -1112,6 +1115,39 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
}
}
+ async transcribe(payload: ASRPayload, options?: ASROptions): Promise<ASRResponse> {
+ const log = debug(`${this.logPrefix}:transcribe`);
+ const { file, fileName, model, language, prompt, responseFormat, temperature } = payload;
+ log('transcribe called with model: %s, audio size: %d bytes', model, file?.size || 0);
+
+ try {
+ // The OpenAI SDK only accepts `File` uploads; wrap bare blobs so the
+ // provider can infer the audio format from the file extension.
+ const uploadFile =
+ file instanceof File ? file : new File([file], fileName || 'audio', { type: file.type });
+
+ const transcription = await this.client.audio.transcriptions.create(
+ {
+ file: uploadFile,
+ language,
+ model,
+ prompt,
+ response_format: responseFormat,
+ temperature,
+ },
+ { headers: options?.headers, signal: options?.signal },
+ );
+
+ const text =
+ typeof transcription === 'string' ? transcription : ((transcription as any).text ?? '');
+ log('transcription completed, text length: %d', text.length);
+
+ return { text };
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
protected handleError(error: any): ChatCompletionErrorPayload {
const log = debug(`${this.logPrefix}:error`);
log('handling error: %O', error);
diff --git a/packages/model-runtime/src/providers/google/index.test.ts b/packages/model-runtime/src/providers/google/index.test.ts
index bd4b9735090..53720b15d6b 100644
--- a/packages/model-runtime/src/providers/google/index.test.ts
+++ b/packages/model-runtime/src/providers/google/index.test.ts
@@ -996,4 +996,106 @@ describe('models', () => {
'x-goog-api-key': apiKey,
});
});
+
+ describe('transcribe', () => {
+ it('should transcribe audio via native generateContent and return text', async () => {
+ const generateContentMock = vi
+ .spyOn(instance['client'].models, 'generateContent')
+ .mockResolvedValue({ text: ' 你好,我感觉很不开心。 ' } as any);
+
+ const file = new File([new Uint8Array([1, 2, 3])], 'speech.m4a', { type: 'audio/mp4' });
+
+ const result = await instance.transcribe!({ file, model: 'gemini-2.5-flash' });
+
+ // text is trimmed
+ expect(result).toEqual({ text: '你好,我感觉很不开心。' });
+
+ // sends inline audio + a text instruction part to the model
+ const callArg = generateContentMock.mock.calls[0][0] as any;
+ expect(callArg.model).toBe('gemini-2.5-flash');
+ const parts = callArg.contents[0].parts;
+ expect(parts[0].inlineData.mimeType).toBe('audio/mp4');
+ expect(typeof parts[0].inlineData.data).toBe('string');
+ expect(parts[1].text).toBeTruthy();
+ });
+
+ it('should include the language hint when provided', async () => {
+ const generateContentMock = vi
+ .spyOn(instance['client'].models, 'generateContent')
+ .mockResolvedValue({ text: 'hi' } as any);
+
+ const file = new File([new Uint8Array([1, 2, 3])], 'speech.wav', { type: '' });
+
+ await instance.transcribe!({ file, language: 'zh', model: 'gemini-2.5-flash' });
+
+ const callArg = generateContentMock.mock.calls[0][0] as any;
+ // mime inferred from the .wav extension when the blob has no type
+ expect(callArg.contents[0].parts[0].inlineData.mimeType).toBe('audio/wav');
+ expect(callArg.contents[0].parts[1].text).toContain('zh');
+ });
+
+ it('should map provider errors through AgentRuntimeError', async () => {
+ vi.spyOn(instance['client'].models, 'generateContent').mockRejectedValue(new Error('boom'));
+
+ const file = new File([new Uint8Array([1, 2, 3])], 'speech.m4a', { type: 'audio/mp4' });
+
+ await expect(
+ instance.transcribe!({ file, model: 'gemini-2.5-flash' }),
+ ).rejects.toHaveProperty('provider', 'google');
+ });
+
+ it('should upload large audio via the Files API and reference it by uri', async () => {
+ const uploadMock = vi.spyOn(instance['client'].files, 'upload').mockResolvedValue({
+ mimeType: 'audio/mp4',
+ name: 'files/abc',
+ state: 'ACTIVE',
+ uri: 'https://generativelanguage.googleapis.com/files/abc',
+ } as any);
+ const generateContentMock = vi
+ .spyOn(instance['client'].models, 'generateContent')
+ .mockResolvedValue({ text: 'big transcript' } as any);
+
+ // 15MB > the 14MB inline threshold → Files API path
+ const big = new File([new Uint8Array(15 * 1024 * 1024)], 'long.m4a', { type: 'audio/mp4' });
+
+ const result = await instance.transcribe!({ file: big, model: 'gemini-2.5-flash' });
+
+ expect(result).toEqual({ text: 'big transcript' });
+ expect(uploadMock).toHaveBeenCalledWith(
+ expect.objectContaining({ config: { mimeType: 'audio/mp4' } }),
+ );
+
+ // references the uploaded file by uri (fileData), not inline base64
+ const parts = (generateContentMock.mock.calls[0][0] as any).contents[0].parts;
+ expect(parts[0].fileData.fileUri).toBe('https://generativelanguage.googleapis.com/files/abc');
+ expect(parts[0].inlineData).toBeUndefined();
+ });
+
+ it('should poll until the uploaded file becomes ACTIVE', async () => {
+ vi.spyOn(instance['client'].files, 'upload').mockResolvedValue({
+ mimeType: 'audio/mp4',
+ name: 'files/xyz',
+ state: 'PROCESSING',
+ } as any);
+ const getMock = vi
+ .spyOn(instance['client'].files, 'get')
+ .mockResolvedValueOnce({ name: 'files/xyz', state: 'PROCESSING' } as any)
+ .mockResolvedValueOnce({
+ mimeType: 'audio/mp4',
+ name: 'files/xyz',
+ state: 'ACTIVE',
+ uri: 'https://generativelanguage.googleapis.com/files/xyz',
+ } as any);
+ vi.spyOn(instance['client'].models, 'generateContent').mockResolvedValue({
+ text: 'ok',
+ } as any);
+
+ const big = new File([new Uint8Array(15 * 1024 * 1024)], 'long.m4a', { type: 'audio/mp4' });
+
+ const result = await instance.transcribe!({ file: big, model: 'gemini-2.5-flash' });
+
+ expect(result).toEqual({ text: 'ok' });
+ expect(getMock).toHaveBeenCalledTimes(2);
+ }, 15_000);
+ });
});
diff --git a/packages/model-runtime/src/providers/google/index.ts b/packages/model-runtime/src/providers/google/index.ts
index a23da159e8c..b7dc4f6af5f 100644
--- a/packages/model-runtime/src/providers/google/index.ts
+++ b/packages/model-runtime/src/providers/google/index.ts
@@ -12,6 +12,9 @@ import { buildGoogleMessages, buildGoogleTools } from '../../core/contextBuilder
import { GoogleGenerativeAIStream } from '../../core/streams';
import { LOBE_ERROR_KEY } from '../../core/streams/google';
import {
+ type ASROptions,
+ type ASRPayload,
+ type ASRResponse,
type ChatCompletionTool,
type ChatMethodOptions,
type ChatStreamPayload,
@@ -30,6 +33,7 @@ import { createGoogleImage } from './createImage';
import { createGoogleVideo, pollGoogleVideoOperation } from './createVideo';
import { createGoogleGenerateObject, createGoogleGenerateObjectWithTools } from './generateObject';
import { resolveGoogleThinkingConfig } from './thinkingResolver';
+import { createGoogleTranscription } from './transcribe';
const log = debug('model-runtime:google');
@@ -317,6 +321,32 @@ export class LobeGoogleAI implements LobeRuntimeAI {
return createGoogleVideo(this.client, this.provider, payload);
}
+ /**
+ * Transcribe audio (ASR) with Gemini's native multimodal API.
+ * @see https://ai.google.dev/gemini-api/docs/audio
+ */
+ async transcribe(payload: ASRPayload, options?: ASROptions): Promise<ASRResponse> {
+ try {
+ return await createGoogleTranscription(this.client, payload, options);
+ } catch (e) {
+ const err = e as Error;
+
+ if (isAbortError(err)) {
+ log('Request was cancelled');
+ throw AgentRuntimeError.chat({
+ error: { message: 'Request was cancelled' },
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ provider: this.provider,
+ });
+ }
+
+ log('Error: %O', err);
+ const { errorType, error } = parseGoogleErrorMessage(err.message);
+
+ throw AgentRuntimeError.chat({ error, errorType, provider: this.provider });
+ }
+ }
+
async handlePollVideoStatus(inferenceId: string) {
return pollGoogleVideoOperation(this.client, inferenceId, this.provider, this.apiKey!);
}
diff --git a/packages/model-runtime/src/providers/google/transcribe.ts b/packages/model-runtime/src/providers/google/transcribe.ts
new file mode 100644
index 00000000000..6c31b7285d0
--- /dev/null
+++ b/packages/model-runtime/src/providers/google/transcribe.ts
@@ -0,0 +1,121 @@
+import type { GenerateContentConfig, GoogleGenAI, Part } from '@google/genai';
+import { createPartFromUri, FileState } from '@google/genai';
+import Debug from 'debug';
+
+import type { ASROptions, ASRPayload, ASRResponse } from '../../types';
+
+const debug = Debug('lobe-model-runtime:google:transcribe');
+
+const DEFAULT_PROMPT =
+ 'Transcribe the speech in this audio verbatim. Output only the transcript text — no commentary, labels, speaker tags, or timestamps.';
+
+// Gemini caps an inline request at ~20MB total. base64 inflates bytes by ~4/3,
+// so anything above ~14MB raw must go through the Files API instead of inline.
+// @see https://ai.google.dev/gemini-api/docs/audio
+const INLINE_MAX_BYTES = 14 * 1024 * 1024;
+
+// Bound the wait for the Files API to finish processing an uploaded audio.
+const FILE_PROCESS_TIMEOUT_MS = 60_000;
+const FILE_POLL_INTERVAL_MS = 1_000;
+
+// Audio mime types accepted by the Gemini API.
+// @see https://ai.google.dev/gemini-api/docs/audio#supported-formats
+const EXT_TO_MIME: Record<string, string> = {
+ aac: 'audio/aac',
+ aiff: 'audio/aiff',
+ flac: 'audio/flac',
+ m4a: 'audio/mp4',
+ mp3: 'audio/mp3',
+ ogg: 'audio/ogg',
+ wav: 'audio/wav',
+};
+
+const guessMimeFromName = (fileName?: string): string | undefined => {
+ const ext = fileName?.split('.').pop()?.toLowerCase();
+ return ext ? EXT_TO_MIME[ext] : undefined;
+};
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+/**
+ * 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.
+ */
+const uploadAudioFile = async (
+ client: GoogleGenAI,
+ file: Blob,
+ mimeType: string,
+ options?: ASROptions,
+): Promise<Part> => {
+ debug('audio exceeds inline limit, uploading via Files API');
+ let uploaded = await client.files.upload({ config: { mimeType }, file });
+
+ const deadline = Date.now() + FILE_PROCESS_TIMEOUT_MS;
+ while (uploaded.state === FileState.PROCESSING) {
+ if (options?.signal?.aborted) throw new Error('Request was cancelled');
+ if (Date.now() > deadline) throw new Error('Gemini file processing timed out');
+ await sleep(FILE_POLL_INTERVAL_MS);
+ uploaded = await client.files.get({ name: uploaded.name! });
+ }
+
+ if (uploaded.state === FileState.FAILED || !uploaded.uri) {
+ throw new Error(`Gemini file processing failed (state: ${uploaded.state})`);
+ }
+
+ debug('Files API upload ready: %s', uploaded.uri);
+ return createPartFromUri(uploaded.uri, uploaded.mimeType ?? mimeType);
+};
+
+/**
+ * Transcribe audio with Gemini's native multimodal `generateContent` API.
+ *
+ * Unlike the OpenAI-compatible `audio/transcriptions` endpoint, Gemini has no
+ * dedicated speech endpoint — audio is passed alongside a text prompt and the
+ * model returns the transcript as plain text. Small files are sent inline;
+ * larger ones go through the Files API.
+ *
+ * @see https://ai.google.dev/gemini-api/docs/audio
+ */
+export const createGoogleTranscription = async (
+ client: GoogleGenAI,
+ payload: ASRPayload,
+ options?: ASROptions,
+): Promise<ASRResponse> => {
+ const { file, fileName, model, language, prompt } = payload;
+
+ const mimeType = file.type || guessMimeFromName(fileName ?? (file as File).name) || 'audio/mp3';
+
+ const audioPart: Part =
+ file.size <= INLINE_MAX_BYTES
+ ? {
+ inlineData: {
+ data: Buffer.from(await file.arrayBuffer()).toString('base64'),
+ mimeType,
+ },
+ }
+ : await uploadAudioFile(client, file, mimeType, options);
+
+ const instruction = [
+ prompt || DEFAULT_PROMPT,
+ language ? `The spoken language is "${language}".` : '',
+ ]
+ .filter(Boolean)
+ .join(' ');
+
+ debug('transcribe via gemini model %s, audio %d bytes, mime %s', model, file.size, mimeType);
+
+ const config: GenerateContentConfig = {
+ abortSignal: options?.signal,
+ };
+
+ const response = await client.models.generateContent({
+ config,
+ contents: [{ parts: [audioPart, { text: instruction }], role: 'user' }],
+ model,
+ });
+
+ const text = (response.text ?? '').trim();
+ debug('transcription completed, text length %d', text.length);
+
+ return { text };
+};
diff --git a/packages/model-runtime/src/types/asr.ts b/packages/model-runtime/src/types/asr.ts
new file mode 100644
index 00000000000..67bf14990de
--- /dev/null
+++ b/packages/model-runtime/src/types/asr.ts
@@ -0,0 +1,47 @@
+export interface ASRPayload {
+ /**
+ * The audio content to transcribe. A `File` is passed through as-is; any other
+ * `Blob` is wrapped into a `File` using `fileName` so the provider can infer
+ * the format from the extension.
+ */
+ file: Blob;
+ /**
+ * Optional file name used when `file` is a plain `Blob`. The extension helps
+ * providers detect the audio format (e.g. `audio.mp3`, `speech.m4a`).
+ */
+ fileName?: string;
+ /**
+ * ISO-639-1 language code of the input audio (e.g. `en`, `zh`). Supplying it
+ * improves accuracy and latency.
+ */
+ language?: string;
+ model: string;
+ /**
+ * Optional text to guide the model's style or continue a previous segment.
+ */
+ prompt?: string;
+ /**
+ * Transcript output format. Defaults to the provider's default (`json`).
+ */
+ responseFormat?: 'json' | 'srt' | 'text' | 'verbose_json' | 'vtt';
+ /**
+ * Sampling temperature between 0 and 1.
+ */
+ temperature?: number;
+}
+
+export interface ASROptions {
+ headers?: Record<string, any>;
+ signal?: AbortSignal;
+ /**
+ * userId for the request
+ */
+ user?: string;
+}
+
+export interface ASRResponse {
+ /**
+ * The transcribed text.
+ */
+ text: string;
+}
diff --git a/packages/model-runtime/src/types/index.ts b/packages/model-runtime/src/types/index.ts
index f36ab902b9a..a1063db0914 100644
--- a/packages/model-runtime/src/types/index.ts
+++ b/packages/model-runtime/src/types/index.ts
@@ -1,3 +1,4 @@
+export * from './asr';
export * from './chat';
export * from './embeddings';
export * from './error';