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

api.generate.speech.ts

177 lines6.2 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 generateSpeech,
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 buildSpeechAdapter,
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 SPEECH_PROVIDER_SCHEMA = z
27 .enum(['openai', 'gemini', 'fal', 'grok', 'elevenlabs', 'byteplus'])
28 .optional()
29​
30const SPEECH_BODY_SCHEMA = z.object({
31 text: z.string().min(1),
32 voice: z.string().optional(),
33 format: z.enum(['mp3', 'opus', 'aac', 'flac', 'wav', 'pcm']).optional(),
34 provider: SPEECH_PROVIDER_SCHEMA,
35})
36​
37function jsonError(status: number, payload: Record<string, unknown>) {
38 return new Response(JSON.stringify(payload), {
39 status,
40 headers: { 'content-type': 'application/json' },
41 })
43​
44export const Route = createFileRoute('/api/generate/speech')({
45 server: {
46 handlers: {
47 POST: async ({ request }) => {
48 let body: unknown
49 try {
50 body = await request.json()
51 } catch {
52 return jsonError(400, {
53 error: 'invalid_json',
54 message: 'Request body must be valid JSON',
55 })
56 }
57​
58 const rawData = (body as { data?: unknown } | null)?.data
59 if (rawData == null) {
60 return jsonError(400, {
61 error: 'missing_data',
62 message: 'Request body must include a `data` field',
63 })
64 }
65​
66 const parsed = SPEECH_BODY_SCHEMA.safeParse(rawData)
67 if (!parsed.success) {
68 return jsonError(400, {
69 error: 'validation_failed',
70 message: 'Request data failed validation',
71 details: z.treeifyError(parsed.error),
72 })
73 }
74​
75 const { text, voice, format, provider } = parsed.data
76​
77 // The AG-UI envelope also carries the generation's identity. Persistence
78 // files the run under it, so a reload hydrates the same slot.
79 let threadId: string | undefined
80 let runId: string | undefined
81 try {
82 ;({ threadId, runId } = generationParamsFromBody('tts', body))
83 } catch (err) {
84 return jsonError(400, {
85 error: 'invalid_envelope',
86 message:
87 err instanceof Error ? err.message : 'Invalid request envelope',
88 })
89 }
90​
91 // Persistence needs the scope named. It is a type error to wire the
92 // middleware without one, so reject the request rather than inventing
93 // an id the client could never hydrate by.
94 if (!threadId) {
95 return jsonError(400, {
96 error: 'missing_thread_id',
97 message:
98 '`threadId` is required — it is the scope this generation is filed under.',
99 })
100 }
101​
102 try {
103 let adapter
104 if (provider === 'byteplus') {
105 const apiKey = getByokKey(request, byteplusVoiceByok)
106 if (!apiKey) return byokMissing(byteplusVoiceByok)
107 adapter = buildSpeechAdapter('byteplus', apiKey)
108 } else {
109 adapter = buildSpeechAdapter(provider ?? 'openai')
110 }
111​
112 const stream = generateSpeech({
113 adapter,
114 text,
115 voice,
116 format,
117 stream: true,
118 ...(threadId ? { threadId } : {}),
119 ...(runId ? { runId } : {}),
120 // Copies the synthesized speech into our blob store and rewrites the
121 // result to the shared `/api/artifacts` serve URL, so a restored run
122 // still plays after the provider's link expires.
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: 'generation_failed',
161 message:
162 err instanceof Error ? err.message : 'Speech generation 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 // clip still restores after a reload once its delivery log ages out.
172 GET: async ({ request }) =>
173 replayGenerationIfResuming(request) ??
174 (await reconstructGeneration(generationServerPersistence(), request)),
175 },
176 },
177})