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

api.audio.stream.ts

44 lines1.5 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { generateAudio, toHttpResponse } from '@tanstack/ai'
3import { createAudioAdapter } from '@/lib/media-providers'
4import type { ElevenLabsAudioModel } from '@tanstack/ai-elevenlabs'
5import type { Provider } from '@/lib/types'
6​
7export const Route = createFileRoute('/api/audio/stream')({
8 server: {
9 handlers: {
10 POST: async ({ request }) => {
11 await import('@/lib/llmock-server').then((m) => m.ensureLLMock())
12 const abortController = new AbortController()
13 const body = await request.json()
14 const data = body.data ?? body
15 const { prompt, model, duration, provider, testId, aimockPort } =
16 data as {
17 prompt: string
18 model?: ElevenLabsAudioModel
19 duration?: number
20 provider: Provider
21 testId?: string
22 aimockPort?: number
23 }
24​
25 const adapter = createAudioAdapter(provider, aimockPort, testId, model)
26​
27 try {
28 const stream = generateAudio({
29 adapter,
30 prompt,
31 ...(duration != null ? { duration } : {}),
32 stream: true,
33 })
34 return toHttpResponse(stream, { abortController })
35 } catch (error: any) {
36 return new Response(JSON.stringify({ error: error.message }), {
37 status: 500,
38 headers: { 'Content-Type': 'application/json' },
39 })
40 }
41 },
42 },
43 },
44})