Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

api.transcribe.ts

177 lines6.0 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 generateTranscription,
4 generationParamsFromBody,
5 memoryStream,
6 toServerSentEventsResponse,
7} from '@tanstack/ai'
8import {
9 reconstructGeneration,
10 withGenerationPersistence,
11} from '@tanstack/ai-persistence'
12import { z } from 'zod'
13import { byokMissing, getByokKey } from '@tanstack/ai/byok/server'
14import { byteplusVoiceByok } from '@tanstack/ai-byteplus/byok'
15import {
16 InvalidModelOverrideError,
17 UnknownProviderError,
18 buildTranscriptionAdapter,
19} from '../lib/server-audio-adapters'
20import { replayGenerationIfResuming } from '../lib/generation-durability'
21import {
22 artifactServeUrl,
23 generationServerPersistence,
24} from '../lib/generation-server-store'
25​
26const TRANSCRIPTION_PROVIDER_SCHEMA = z
27 .enum(['openai', 'openai-diarize', 'fal', 'grok', 'elevenlabs', 'byteplus'])
28 .optional()
29​
30const TRANSCRIPTION_RESPONSE_FORMAT_SCHEMA = z
31 .enum(['json', 'text', 'srt', 'verbose_json', 'vtt'])
32 .optional()
33​
34const TRANSCRIBE_BODY_SCHEMA = z.object({
35 audio: z.string().min(1),
36 language: z.string().optional(),
37 responseFormat: TRANSCRIPTION_RESPONSE_FORMAT_SCHEMA,
38 modelOptions: z.record(z.string(), z.any()).optional(),
39 provider: TRANSCRIPTION_PROVIDER_SCHEMA,
40})
41​
42function jsonError(status: number, payload: Record<string, unknown>) {
43 return new Response(JSON.stringify(payload), {
44 status,
45 headers: { 'content-type': 'application/json' },
46 })
48​
49export const Route = createFileRoute('/api/transcribe')({
50 server: {
51 handlers: {
52 POST: async ({ request }) => {
53 let body: unknown
54 try {
55 body = await request.json()
56 } catch {
57 return jsonError(400, {
58 error: 'invalid_json',
59 message: 'Request body must be valid JSON',
60 })
61 }
62​
63 const rawData = (body as { forwardedProps?: unknown } | null)
64 ?.forwardedProps
65 if (rawData == null) {
66 return jsonError(400, {
67 error: 'missing_forwarded_props',
68 message: 'Request body must include a `forwardedProps` field',
69 })
70 }
71​
72 const parsed = TRANSCRIBE_BODY_SCHEMA.safeParse(rawData)
73 if (!parsed.success) {
74 return jsonError(400, {
75 error: 'validation_failed',
76 message: 'Request data failed validation',
77 details: z.treeifyError(parsed.error),
78 })
79 }
80​
81 const { audio, language, responseFormat, modelOptions, provider } =
82 parsed.data
83​
84 // The AG-UI envelope also carries the generation's identity. Persistence
85 // files the run under it, so a reload hydrates the same slot.
86 let threadId: string
87 let runId: string
88 try {
89 ;({ threadId, runId } = generationParamsFromBody(
90 'transcription',
91 body,
92 ))
93 } catch (err) {
94 return jsonError(400, {
95 error: 'invalid_envelope',
96 message:
97 err instanceof Error ? err.message : 'Invalid request envelope',
98 })
99 }
100​
101 try {
102 let adapter
103 if (provider === 'byteplus') {
104 const apiKey = getByokKey(request, byteplusVoiceByok)
105 if (!apiKey) return byokMissing(byteplusVoiceByok)
106 adapter = buildTranscriptionAdapter('byteplus', apiKey)
107 } else {
108 adapter = buildTranscriptionAdapter(provider ?? 'openai')
109 }
110​
111 const stream = generateTranscription({
112 adapter,
113 audio,
114 language,
115 responseFormat,
116 modelOptions,
117 stream: true,
118 threadId,
119 runId,
120 // Transcription produces text, not media — what gets persisted here
121 // is the run record plus the INPUT audio as an artifact, so a
122 // restored run still shows what was transcribed.
123 middleware: [
124 withGenerationPersistence(generationServerPersistence(), {
125 threadId,
126 artifactUrl: (ref) => artifactServeUrl(ref.artifactId),
127 }),
128 ],
129 })
130​
131 // Delivery durability: chunks are logged and id-tagged, so a
132 // reconnect or a mount-time `joinRun` replays instead of re-running
133 // the model. The run still ends with the request — this activity is
134 // short enough to simply re-run.
135 return toServerSentEventsResponse(stream, {
136 durability: { adapter: memoryStream(request) },
137 })
138 } catch (err) {
139 if (err instanceof InvalidModelOverrideError) {
140 return jsonError(400, {
141 error: 'invalid_model_override',
142 message: err.message,
143 provider: err.providerId,
144 requestedModel: err.requestedModel,
145 allowedModels: err.allowedModels,
146 })
147 }
148 // Defense-in-depth: the Zod enum schema above should already reject
149 // unknown providers, but surface a typed 400 here in case that
150 // validation drifts or is bypassed.
151 if (err instanceof UnknownProviderError) {
152 return jsonError(400, {
153 error: 'unknown_provider',
154 message: err.message,
155 provider: err.providerId,
156 allowedProviders: err.allowedProviders,
157 })
158 }
159 return jsonError(500, {
160 error: 'transcription_failed',
161 message:
162 err instanceof Error ? err.message : 'Transcription failed',
163 })
164 }
165 },
166​
167 // Two independent jobs, resolved in order (like the image route):
168 // 1. `joinRun` delivery replay, when the request carries a resume offset.
169 // 2. Mount hydration for `persistence: true`: the latest run for
170 // `?threadId=`, as `{ resumeSnapshot, activeRun }`, so a completed
171 // transcription still restores after a reload once its log ages out.
172 GET: async ({ request }) =>
173 replayGenerationIfResuming(request) ??
174 (await reconstructGeneration(generationServerPersistence(), request)),
175 },
176 },
177})