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

api.generate.speech.ts

167 lines5.7 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 { forwardedProps?: unknown } | null)
59 ?.forwardedProps
60 if (rawData == null) {
61 return jsonError(400, {
62 error: 'missing_forwarded_props',
63 message: 'Request body must include a `forwardedProps` field',
64 })
65 }
66​
67 const parsed = SPEECH_BODY_SCHEMA.safeParse(rawData)
68 if (!parsed.success) {
69 return jsonError(400, {
70 error: 'validation_failed',
71 message: 'Request data failed validation',
72 details: z.treeifyError(parsed.error),
73 })
74 }
75​
76 const { text, voice, format, provider } = parsed.data
77​
78 // The AG-UI envelope also carries the generation's identity. Persistence
79 // files the run under it, so a reload hydrates the same slot.
80 let threadId: string
81 let runId: string
82 try {
83 ;({ threadId, runId } = generationParamsFromBody('tts', body))
84 } catch (err) {
85 return jsonError(400, {
86 error: 'invalid_envelope',
87 message:
88 err instanceof Error ? err.message : 'Invalid request envelope',
89 })
90 }
91​
92 try {
93 let adapter
94 if (provider === 'byteplus') {
95 const apiKey = getByokKey(request, byteplusVoiceByok)
96 if (!apiKey) return byokMissing(byteplusVoiceByok)
97 adapter = buildSpeechAdapter('byteplus', apiKey)
98 } else {
99 adapter = buildSpeechAdapter(provider ?? 'openai')
100 }
101​
102 const stream = generateSpeech({
103 adapter,
104 text,
105 voice,
106 format,
107 stream: true,
108 threadId,
109 runId,
110 // Copies the synthesized speech into our blob store and rewrites the
111 // result to the shared `/api/artifacts` serve URL, so a restored run
112 // still plays after the provider's link expires.
113 middleware: [
114 withGenerationPersistence(generationServerPersistence(), {
115 threadId,
116 artifactUrl: (ref) => artifactServeUrl(ref.artifactId),
117 }),
118 ],
119 })
120​
121 // Delivery durability: chunks are logged and id-tagged, so a
122 // reconnect or a mount-time `joinRun` replays instead of re-running
123 // the model. The run still ends with the request — this activity is
124 // short enough to simply re-run.
125 return toServerSentEventsResponse(stream, {
126 durability: { adapter: memoryStream(request) },
127 })
128 } catch (err) {
129 if (err instanceof InvalidModelOverrideError) {
130 return jsonError(400, {
131 error: 'invalid_model_override',
132 message: err.message,
133 provider: err.providerId,
134 requestedModel: err.requestedModel,
135 allowedModels: err.allowedModels,
136 })
137 }
138 // Defense-in-depth: the Zod enum schema above should already reject
139 // unknown providers, but surface a typed 400 here in case that
140 // validation drifts or is bypassed.
141 if (err instanceof UnknownProviderError) {
142 return jsonError(400, {
143 error: 'unknown_provider',
144 message: err.message,
145 provider: err.providerId,
146 allowedProviders: err.allowedProviders,
147 })
148 }
149 return jsonError(500, {
150 error: 'generation_failed',
151 message:
152 err instanceof Error ? err.message : 'Speech generation failed',
153 })
154 }
155 },
156​
157 // Two independent jobs, resolved in order (like the image route):
158 // 1. `joinRun` delivery replay, when the request carries a resume offset.
159 // 2. Mount hydration for `persistence: true`: the latest run for
160 // `?threadId=`, as `{ resumeSnapshot, activeRun }`, so a completed
161 // clip still restores after a reload once its delivery log ages out.
162 GET: async ({ request }) =>
163 replayGenerationIfResuming(request) ??
164 (await reconstructGeneration(generationServerPersistence(), request)),
165 },
166 },
167})