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

api.generate.audio.ts

175 lines5.9 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 generateAudio,
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 {
14 InvalidModelOverrideError,
15 UnknownProviderError,
16 buildAudioAdapter,
17} from '../lib/server-audio-adapters'
18import { replayGenerationIfResuming } from '../lib/generation-durability'
19import {
20 artifactServeUrl,
21 generationServerPersistence,
22} from '../lib/generation-server-store'
23​
24const AUDIO_PROVIDER_SCHEMA = z
25 .enum([
26 'gemini-lyria',
27 'fal-audio',
28 'fal-sfx',
29 'elevenlabs-music',
30 'elevenlabs-sfx',
31 ])
32 .optional()
33​
34const AUDIO_BODY_SCHEMA = z.object({
35 prompt: z.string().min(1),
36 duration: z.number().optional(),
37 provider: AUDIO_PROVIDER_SCHEMA,
38 model: z.string().optional(),
39})
40​
41function jsonError(status: number, payload: Record<string, unknown>) {
42 return new Response(JSON.stringify(payload), {
43 status,
44 headers: { 'content-type': 'application/json' },
45 })
47​
48export const Route = createFileRoute('/api/generate/audio')({
49 server: {
50 handlers: {
51 POST: async ({ request }) => {
52 let body: unknown
53 try {
54 body = await request.json()
55 } catch {
56 return jsonError(400, {
57 error: 'invalid_json',
58 message: 'Request body must be valid JSON',
59 })
60 }
61​
62 const rawData = (body as { data?: unknown } | null)?.data
63 if (rawData == null) {
64 return jsonError(400, {
65 error: 'missing_data',
66 message: 'Request body must include a `data` field',
67 })
68 }
69​
70 const parsed = AUDIO_BODY_SCHEMA.safeParse(rawData)
71 if (!parsed.success) {
72 return jsonError(400, {
73 error: 'validation_failed',
74 message: 'Request data failed validation',
75 details: z.treeifyError(parsed.error),
76 })
77 }
78​
79 const { prompt, duration, provider, model } = parsed.data
80​
81 // The AG-UI envelope also carries the generation's identity. Persistence
82 // files the run under it, so a reload hydrates the same slot.
83 let threadId: string | undefined
84 let runId: string | undefined
85 try {
86 ;({ threadId, runId } = generationParamsFromBody('audio', body))
87 } catch (err) {
88 return jsonError(400, {
89 error: 'invalid_envelope',
90 message:
91 err instanceof Error ? err.message : 'Invalid request envelope',
92 })
93 }
94​
95 // Persistence needs the scope named. It is a type error to wire the
96 // middleware without one, so reject the request rather than inventing
97 // an id the client could never hydrate by.
98 if (!threadId) {
99 return jsonError(400, {
100 error: 'missing_thread_id',
101 message:
102 '`threadId` is required — it is the scope this generation is filed under.',
103 })
104 }
105​
106 try {
107 const adapter = buildAudioAdapter(provider ?? 'gemini-lyria', model)
108​
109 const stream = generateAudio({
110 adapter,
111 prompt,
112 duration,
113 stream: true,
114 ...(threadId ? { threadId } : {}),
115 ...(runId ? { runId } : {}),
116 // Copies the generated audio into our blob store and rewrites the
117 // result to the shared `/api/artifacts` serve URL, so a restored
118 // run still plays after the provider's link expires.
119 middleware: [
120 withGenerationPersistence(generationServerPersistence(), {
121 threadId,
122 artifactUrl: (ref) => artifactServeUrl(ref.artifactId),
123 }),
124 ],
125 })
126​
127 // Delivery durability: each chunk is logged and id-tagged, so a
128 // reconnect or a mount-time `joinRun` replays instead of re-running
129 // the model. The run itself still ends with the request — an audio
130 // clip is short enough to simply re-run.
131 return toServerSentEventsResponse(stream, {
132 durability: { adapter: memoryStream(request) },
133 })
134 } catch (err) {
135 if (err instanceof InvalidModelOverrideError) {
136 return jsonError(400, {
137 error: 'invalid_model_override',
138 message: err.message,
139 provider: err.providerId,
140 requestedModel: err.requestedModel,
141 allowedModels: err.allowedModels,
142 })
143 }
144 // Defense-in-depth: the Zod enum schema above should already reject
145 // unknown providers, but surface a typed 400 here in case that
146 // validation drifts or is bypassed.
147 if (err instanceof UnknownProviderError) {
148 return jsonError(400, {
149 error: 'unknown_provider',
150 message: err.message,
151 // Use `provider` consistently with the invalid_model_override
152 // branch and the request body's `provider` field.
153 provider: err.providerId,
154 allowedProviders: err.allowedProviders,
155 })
156 }
157 return jsonError(500, {
158 error: 'generation_failed',
159 message:
160 err instanceof Error ? err.message : 'Audio generation failed',
161 })
162 }
163 },
164​
165 // Two independent jobs, resolved in order (like the image route):
166 // 1. `joinRun` delivery replay, when the request carries a resume offset.
167 // 2. Mount hydration for `persistence: true`: the latest run for
168 // `?threadId=`, as `{ resumeSnapshot, activeRun }`, so a completed
169 // clip still restores after a reload once its delivery log ages out.
170 GET: async ({ request }) =>
171 replayGenerationIfResuming(request) ??
172 (await reconstructGeneration(generationServerPersistence(), request)),
173 },
174 },
175})