Open History to see the last commit
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 })
47}
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 { data?: unknown } | null)?.data
64 if (rawData == null) {
65 return jsonError(400, {
66 error: 'missing_data',
67 message: 'Request body must include a `data` field',
68 })
69 }
70
71 const parsed = TRANSCRIBE_BODY_SCHEMA.safeParse(rawData)
72 if (!parsed.success) {
73 return jsonError(400, {
74 error: 'validation_failed',
75 message: 'Request data failed validation',
76 details: z.treeifyError(parsed.error),
77 })
78 }
79
80 const { audio, language, responseFormat, modelOptions, provider } =
81 parsed.data
82
83 // The AG-UI envelope also carries the generation's identity. Persistence
84 // files the run under it, so a reload hydrates the same slot.
85 let threadId: string | undefined
86 let runId: string | undefined
87 try {
88 ;({ threadId, runId } = generationParamsFromBody(
89 'transcription',
90 body,
91 ))
92 } catch (err) {
93 return jsonError(400, {
94 error: 'invalid_envelope',
95 message:
96 err instanceof Error ? err.message : 'Invalid request envelope',
97 })
98 }
99
100 // Persistence needs the scope named. It is a type error to wire the
101 // middleware without one, so reject the request rather than inventing
102 // an id the client could never hydrate by.
103 if (!threadId) {
104 return jsonError(400, {
105 error: 'missing_thread_id',
106 message:
107 '`threadId` is required — it is the scope this generation is filed under.',
108 })
109 }
110
111 try {
112 let adapter
113 if (provider === 'byteplus') {
114 const apiKey = getByokKey(request, byteplusVoiceByok)
115 if (!apiKey) return byokMissing(byteplusVoiceByok)
116 adapter = buildTranscriptionAdapter('byteplus', apiKey)
117 } else {
118 adapter = buildTranscriptionAdapter(provider ?? 'openai')
119 }
120
121 const stream = generateTranscription({
122 adapter,
123 audio,
124 language,
125 responseFormat,
126 modelOptions,
127 stream: true,
128 ...(threadId ? { threadId } : {}),
129 ...(runId ? { runId } : {}),
130 // Transcription produces text, not media — what gets persisted here
131 // is the run record plus the INPUT audio as an artifact, so a
132 // restored run still shows what was transcribed.
133 middleware: [
134 withGenerationPersistence(generationServerPersistence(), {
135 threadId,
136 artifactUrl: (ref) => artifactServeUrl(ref.artifactId),
137 }),
138 ],
139 })
140
141 // Delivery durability: chunks are logged and id-tagged, so a
142 // reconnect or a mount-time `joinRun` replays instead of re-running
143 // the model. The run still ends with the request — this activity is
144 // short enough to simply re-run.
145 return toServerSentEventsResponse(stream, {
146 durability: { adapter: memoryStream(request) },
147 })
148 } catch (err) {
149 if (err instanceof InvalidModelOverrideError) {
150 return jsonError(400, {
151 error: 'invalid_model_override',
152 message: err.message,
153 provider: err.providerId,
154 requestedModel: err.requestedModel,
155 allowedModels: err.allowedModels,
156 })
157 }
158 // Defense-in-depth: the Zod enum schema above should already reject
159 // unknown providers, but surface a typed 400 here in case that
160 // validation drifts or is bypassed.
161 if (err instanceof UnknownProviderError) {
162 return jsonError(400, {
163 error: 'unknown_provider',
164 message: err.message,
165 provider: err.providerId,
166 allowedProviders: err.allowedProviders,
167 })
168 }
169 return jsonError(500, {
170 error: 'transcription_failed',
171 message:
172 err instanceof Error ? err.message : 'Transcription failed',
173 })
174 }
175 },
176
177 // Two independent jobs, resolved in order (like the image route):
178 // 1. `joinRun` delivery replay, when the request carries a resume offset.
179 // 2. Mount hydration for `persistence: true`: the latest run for
180 // `?threadId=`, as `{ resumeSnapshot, activeRun }`, so a completed
181 // transcription still restores after a reload once its log ages out.
182 GET: async ({ request }) =>
183 replayGenerationIfResuming(request) ??
184 (await reconstructGeneration(generationServerPersistence(), request)),
185 },
186 },
187})