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

server-fns.ts

516 lines15.7 KB

1import { createServerFn } from '@tanstack/react-start'
2import { z } from 'zod'
3import {
4 chat,
5 generateAudio,
6 generateImage,
7 generateSpeech,
8 generateTranscription,
9 generateVideo,
10 getVideoJobStatus,
11 memoryStream,
12 replayRunStream,
13 summarize,
14 toServerSentEventsResponse,
15} from '@tanstack/ai'
16import {
17 getGenerationHydration,
18 withGenerationPersistence,
19} from '@tanstack/ai-persistence'
20import { openaiSummarize, openaiText } from '@tanstack/ai-openai'
21import { grokImage, grokVideo } from '@tanstack/ai-grok'
22import type { UIMessage } from '@tanstack/ai'
23import {
24 InvalidModelOverrideError,
25 UnknownProviderError,
26 buildAudioAdapter,
27 buildSpeechAdapter,
28 buildTranscriptionAdapter,
29} from './server-audio-adapters'
30import {
31 artifactServeUrl,
32 generationServerPersistence,
33} from './generation-server-store'
34​
35/**
36 * Server-fn error with a stable `code` property clients can switch on.
37 *
38 * TanStack Start's `createServerFn` surfaces thrown errors as a generic 500
39 * without a structured payload. We can't influence the status code from here,
40 * so we attach a `code` field the client can read to distinguish well-known
41 * failure modes (invalid_model_override, unknown_provider) from truly
42 * unexpected errors.
43 */
44class ServerFnError extends Error {
45 readonly code: string
46 readonly details?: Record<string, unknown>
47​
48 constructor(
49 code: string,
50 message: string,
51 details?: Record<string, unknown>,
52 ) {
53 super(message)
54 this.name = 'ServerFnError'
55 this.code = code
56 this.details = details
57 }
59​
60/**
61 * Translate the typed audio-adapter errors into a `ServerFnError` with a stable
62 * `code`. Any other error is re-thrown untouched so the framework's default
63 * 500 path handles it.
64 */
65function rethrowAudioAdapterError(err: unknown): never {
66 if (err instanceof InvalidModelOverrideError) {
67 throw new ServerFnError('invalid_model_override', err.message, {
68 providerId: err.providerId,
69 requestedModel: err.requestedModel,
70 allowedModels: err.allowedModels,
71 })
72 }
73 if (err instanceof UnknownProviderError) {
74 throw new ServerFnError('unknown_provider', err.message, {
75 providerId: err.providerId,
76 allowedProviders: err.allowedProviders,
77 })
78 }
79 throw err
81​
82const SPEECH_PROVIDER_SCHEMA = z
83 .enum(['openai', 'gemini', 'fal', 'grok', 'elevenlabs', 'byteplus'])
84 .optional()
85​
86const TRANSCRIPTION_PROVIDER_SCHEMA = z
87 .enum(['openai', 'openai-diarize', 'fal', 'grok', 'elevenlabs', 'byteplus'])
88 .optional()
89​
90const TRANSCRIPTION_RESPONSE_FORMAT_SCHEMA = z
91 .enum(['json', 'text', 'srt', 'verbose_json', 'vtt'])
92 .optional()
93​
94const AUDIO_PROVIDER_SCHEMA = z
95 .enum([
96 'gemini-lyria',
97 'fal-audio',
98 'fal-sfx',
99 'elevenlabs-music',
100 'elevenlabs-sfx',
101 ])
102 .optional()
103​
104// =============================================================================
105// Image generation — server-driven persistence (direct + streaming server fns)
106// =============================================================================
107//
108// Same stores as `/api/generate/image` (`generationServerPersistence` +
109// `/api/artifacts`). Direct and streaming server-fn modes have no GET route, so
110// the client supplies `hydrateGeneration` / `joinRun` via the companion
111// functions below. See docs/persistence/generation-persistence.md.
112​
113const imageGenerateInputSchema = z.object({
114 prompt: z.string(),
115 numberOfImages: z.number().optional(),
116 size: z.string().optional(),
117 // Required: the slot successive runs are filed under for hydration.
118 threadId: z.string().min(1),
119})
120​
121function imagePersistenceMiddleware() {
122 return withGenerationPersistence(generationServerPersistence(), {
123 artifactUrl: (ref) => artifactServeUrl(ref.artifactId),
124 })
126​
127// =============================================================================
128// Direct server functions (non-streaming, return the result directly)
129// =============================================================================
130​
131export const generateImageFn = createServerFn({ method: 'POST' })
132 .inputValidator(imageGenerateInputSchema)
133 .handler(async ({ data }) => {
134 return generateImage({
135 adapter: grokImage('grok-imagine-image'),
136 prompt: data.prompt,
137 numberOfImages: data.numberOfImages,
138 size: data.size as any,
139 threadId: data.threadId,
140 middleware: [imagePersistenceMiddleware()],
141 })
142 })
143​
144export const generateSpeechFn = createServerFn({ method: 'POST' })
145 .inputValidator(
146 z.object({
147 threadId: z.string().min(1),
148 text: z.string(),
149 voice: z.string().optional(),
150 format: z.enum(['mp3', 'opus', 'aac', 'flac', 'wav', 'pcm']).optional(),
151 provider: SPEECH_PROVIDER_SCHEMA,
152 }),
153 )
154 .handler(async ({ data }) => {
155 // `buildSpeechAdapter` can throw `UnknownProviderError` (defense-in-depth;
156 // Zod should catch this first). Translate into a `ServerFnError` so
157 // clients can distinguish it from a generic failure via the stable `code`.
158 let adapter
159 try {
160 adapter = buildSpeechAdapter(data.provider ?? 'openai')
161 } catch (err) {
162 rethrowAudioAdapterError(err)
163 }
164 return generateSpeech({
165 adapter,
166 threadId: data.threadId,
167 text: data.text,
168 voice: data.voice,
169 format: data.format,
170 })
171 })
172​
173export const transcribeFn = createServerFn({ method: 'POST' })
174 .inputValidator(
175 z.object({
176 threadId: z.string().min(1),
177 audio: z.string(),
178 language: z.string().optional(),
179 responseFormat: TRANSCRIPTION_RESPONSE_FORMAT_SCHEMA,
180 modelOptions: z.record(z.string(), z.any()).optional(),
181 provider: TRANSCRIPTION_PROVIDER_SCHEMA,
182 }),
183 )
184 .handler(async ({ data }) => {
185 // `buildTranscriptionAdapter` can throw `UnknownProviderError`
186 // (defense-in-depth; Zod should catch this first). Translate into a
187 // `ServerFnError` so clients can distinguish it from a generic failure
188 // via the stable `code`.
189 let adapter
190 try {
191 adapter = buildTranscriptionAdapter(data.provider ?? 'openai')
192 } catch (err) {
193 rethrowAudioAdapterError(err)
194 }
195 return generateTranscription({
196 adapter,
197 threadId: data.threadId,
198 audio: data.audio,
199 language: data.language,
200 responseFormat: data.responseFormat,
201 modelOptions: data.modelOptions,
202 })
203 })
204​
205export const generateAudioFn = createServerFn({ method: 'POST' })
206 .inputValidator(
207 z.object({
208 threadId: z.string().min(1),
209 prompt: z.string(),
210 duration: z.number().optional(),
211 provider: AUDIO_PROVIDER_SCHEMA,
212 model: z.string().optional(),
213 }),
214 )
215 .handler(async ({ data }) => {
216 // `buildAudioAdapter` can throw `InvalidModelOverrideError` (unknown
217 // model id) or `UnknownProviderError` (defense-in-depth; Zod should
218 // catch this first). Translate both into a `ServerFnError` so clients
219 // can distinguish them from a generic failure via the stable `code`.
220 let adapter
221 try {
222 adapter = buildAudioAdapter(data.provider ?? 'gemini-lyria', data.model)
223 } catch (err) {
224 rethrowAudioAdapterError(err)
225 }
226 return generateAudio({
227 adapter,
228 threadId: data.threadId,
229 prompt: data.prompt,
230 duration: data.duration,
231 })
232 })
233​
234export const summarizeFn = createServerFn({ method: 'POST' })
235 .inputValidator(
236 z.object({
237 threadId: z.string().min(1),
238 text: z.string(),
239 maxLength: z.number().optional(),
240 style: z.enum(['bullet-points', 'paragraph', 'concise']).optional(),
241 model: z.string().optional(),
242 }),
243 )
244 .handler(async ({ data }) => {
245 return summarize({
246 adapter: openaiSummarize((data.model ?? 'gpt-4o-mini') as 'gpt-4o-mini'),
247 threadId: data.threadId,
248 text: data.text,
249 maxLength: data.maxLength,
250 style: data.style,
251 })
252 })
253​
254export const generateVideoFn = createServerFn({ method: 'POST' })
255 .inputValidator(
256 z.object({
257 threadId: z.string().min(1),
258 prompt: z.string(),
259 size: z.string().optional(),
260 duration: z.number().optional(),
261 }),
262 )
263 .handler(async ({ data }) => {
264 const adapter = grokVideo('grok-imagine-video')
265​
266 // Create the job
267 const { jobId } = await generateVideo({
268 adapter,
269 threadId: data.threadId,
270 prompt: data.prompt,
271 size: data.size as any,
272 duration: data.duration,
273 })
274​
275 // Poll until complete (max 10 minutes)
276 const MAX_POLLS = 120
277 let polls = 0
278 let status = await getVideoJobStatus({ adapter, jobId })
279 while (status.status !== 'completed' && status.status !== 'failed') {
280 if (++polls > MAX_POLLS) {
281 throw new Error('Video generation timed out')
282 }
283 await new Promise((r) => setTimeout(r, 5000))
284 status = await getVideoJobStatus({ adapter, jobId })
285 }
286​
287 if (status.status === 'failed') {
288 throw new Error(status.error || 'Video generation failed')
289 }
290​
291 if (!status.url) {
292 throw new Error('Video generation completed but no URL was provided')
293 }
294​
295 return {
296 jobId,
297 status: 'completed' as const,
298 url: status.url,
299 }
300 })
301​
302// =============================================================================
303// Streaming server functions (return SSE Response for client-side parsing)
304// Used with: fetchServerSentEvents((input) => streamFn({ data: input }))
305// =============================================================================
306​
307export const generateImageStreamFn = createServerFn({ method: 'POST' })
308 .inputValidator(imageGenerateInputSchema)
309 .handler(({ data }) => {
310 // One run id for the durability log and the run record so join can replay
311 // exactly the run hydration reports.
312 const runId = crypto.randomUUID()
313 const stream = generateImage({
314 adapter: grokImage('grok-imagine-image'),
315 prompt: data.prompt,
316 numberOfImages: data.numberOfImages,
317 size: data.size as any,
318 threadId: data.threadId,
319 runId,
320 stream: true,
321 middleware: [imagePersistenceMiddleware()],
322 })
323 return toServerSentEventsResponse(stream, {
324 durability: { adapter: memoryStream({ runId }) },
325 })
326 })
327​
328/**
329 * Wire shape for mount hydration. Parsed with Zod so:
330 * - TanStack Start gets a JSON-serializable return type (no `unknown`)
331 * - the store's loose `result` is validated before it crosses the wire
332 */
333const generationHydrationSchema = z.object({
334 resumeSnapshot: z
335 .object({
336 schemaVersion: z.literal(1),
337 resumeState: z
338 .object({
339 threadId: z.string(),
340 runId: z.string(),
341 })
342 .nullable(),
343 status: z.enum(['idle', 'running', 'complete', 'error']),
344 // `z.any()` (not `z.unknown()`) so Start's serializer accepts the values.
345 result: z.record(z.string(), z.any()).optional(),
346 error: z
347 .object({
348 message: z.string(),
349 code: z.string().optional(),
350 })
351 .optional(),
352 activity: z.string().optional(),
353 })
354 .nullable(),
355 activeRun: z.object({ runId: z.string() }).nullable(),
356})
357​
358/** Mount hydration for image `persistence: true` over a fetcher (no GET route). */
359export const getImageHydrationFn = createServerFn({ method: 'GET' })
360 .inputValidator(z.string().min(1))
361 .handler(async ({ data: threadId }) => {
362 // No auth in this single-user demo — gate on session in a multi-user app.
363 return generationHydrationSchema.parse(
364 await getGenerationHydration(generationServerPersistence(), threadId),
365 )
366 })
367​
368/**
369 * Rejoin an in-flight image run over a server function (replay + live tail).
370 * Returns an SSE `Response` — the client parses it the same way
371 * `generateImageStreamFn` does (see `chunksFromSseResponse` on the page).
372 */
373export const joinImageRunFn = createServerFn({ method: 'GET' })
374 .inputValidator(z.string().min(1))
375 .handler(({ data: runId }) =>
376 toServerSentEventsResponse(replayRunStream(memoryStream({ runId }))),
377 )
378​
379export const generateSpeechStreamFn = createServerFn({ method: 'POST' })
380 .inputValidator(
381 z.object({
382 threadId: z.string().min(1),
383 text: z.string(),
384 voice: z.string().optional(),
385 format: z.enum(['mp3', 'opus', 'aac', 'flac', 'wav', 'pcm']).optional(),
386 provider: SPEECH_PROVIDER_SCHEMA,
387 }),
388 )
389 .handler(({ data }) => {
390 // `buildSpeechAdapter` can throw `UnknownProviderError` (defense-in-depth;
391 // Zod should catch this first). Translate into a `ServerFnError` so
392 // clients can distinguish it from a generic failure via the stable `code`.
393 let adapter
394 try {
395 adapter = buildSpeechAdapter(data.provider ?? 'openai')
396 } catch (err) {
397 rethrowAudioAdapterError(err)
398 }
399 return toServerSentEventsResponse(
400 generateSpeech({
401 adapter,
402 threadId: data.threadId,
403 text: data.text,
404 voice: data.voice,
405 format: data.format,
406 stream: true,
407 }),
408 )
409 })
410​
411export const transcribeStreamFn = createServerFn({ method: 'POST' })
412 .inputValidator(
413 z.object({
414 threadId: z.string().min(1),
415 audio: z.string(),
416 language: z.string().optional(),
417 responseFormat: TRANSCRIPTION_RESPONSE_FORMAT_SCHEMA,
418 modelOptions: z.record(z.string(), z.any()).optional(),
419 provider: TRANSCRIPTION_PROVIDER_SCHEMA,
420 }),
421 )
422 .handler(({ data }) => {
423 // `buildTranscriptionAdapter` can throw `UnknownProviderError`
424 // (defense-in-depth; Zod should catch this first). Translate into a
425 // `ServerFnError` so clients can distinguish it from a generic failure
426 // via the stable `code`.
427 let adapter
428 try {
429 adapter = buildTranscriptionAdapter(data.provider ?? 'openai')
430 } catch (err) {
431 rethrowAudioAdapterError(err)
432 }
433 return toServerSentEventsResponse(
434 generateTranscription({
435 adapter,
436 threadId: data.threadId,
437 audio: data.audio,
438 language: data.language,
439 responseFormat: data.responseFormat,
440 modelOptions: data.modelOptions,
441 stream: true,
442 }),
443 )
444 })
445​
446export const summarizeStreamFn = createServerFn({ method: 'POST' })
447 .inputValidator(
448 z.object({
449 threadId: z.string().min(1),
450 text: z.string(),
451 maxLength: z.number().optional(),
452 style: z.enum(['bullet-points', 'paragraph', 'concise']).optional(),
453 model: z.string().optional(),
454 }),
455 )
456 .handler(({ data }) => {
457 return toServerSentEventsResponse(
458 summarize({
459 adapter: openaiSummarize(
460 (data.model ?? 'gpt-4o-mini') as 'gpt-4o-mini',
461 ),
462 threadId: data.threadId,
463 text: data.text,
464 maxLength: data.maxLength,
465 style: data.style,
466 stream: true,
467 }),
468 )
469 })
470​
471export const generateVideoStreamFn = createServerFn({ method: 'POST' })
472 .inputValidator(
473 z.object({
474 threadId: z.string().min(1),
475 prompt: z.string(),
476 size: z.string().optional(),
477 duration: z.number().optional(),
478 }),
479 )
480 .handler(({ data }) => {
481 return toServerSentEventsResponse(
482 generateVideo({
483 adapter: grokVideo('grok-imagine-video'),
484 threadId: data.threadId,
485 prompt: data.prompt,
486 size: data.size as any,
487 duration: data.duration,
488 stream: true,
489 }),
490 )
491 })
492​
493// =============================================================================
494// Chat server function — pairs with useChat({ fetcher })
495// =============================================================================
496​
497export const chatFn = createServerFn({ method: 'POST' })
498 .inputValidator(
499 (data: {
500 messages: Array<UIMessage>
501 threadId: string
502 data?: Record<string, any>
503 }) => data,
504 )
505 .handler(({ data }) =>
506 toServerSentEventsResponse(
507 chat({
508 adapter: openaiText('gpt-5.2'),
509 threadId: data.threadId,
510 messages: data.messages as any,
511 systemPrompts: [
512 'You are a helpful assistant. Keep replies short and friendly.',
513 ],
514 }),
515 ),
516 )