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

api.tts.stream.ts

48 lines1.6 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { generateSpeech, toHttpResponse } from '@tanstack/ai'
3import { createTTSAdapter } from '@/lib/media-providers'
4import type { TTSTurn } from '@tanstack/ai'
5import type { Provider } from '@/lib/types'
6​
7export const Route = createFileRoute('/api/tts/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.forwardedProps ?? body.data ?? body
15 const { text, turns, timestamps, voice, provider, testId, aimockPort } =
16 data as {
17 text?: string
18 turns?: Array<TTSTurn>
19 timestamps?: boolean
20 voice?: string
21 provider: Provider
22 testId?: string
23 aimockPort?: number
24 }
25​
26 const adapter = createTTSAdapter(provider, aimockPort, testId)
27​
28 try {
29 const stream = turns
30 ? generateSpeech({ adapter, turns, timestamps, stream: true })
31 : generateSpeech({
32 adapter,
33 text: text ?? '',
34 voice,
35 timestamps,
36 stream: true,
37 })
38 return toHttpResponse(stream, { abortController })
39 } catch (error: any) {
40 return new Response(JSON.stringify({ error: error.message }), {
41 status: 500,
42 headers: { 'Content-Type': 'application/json' },
43 })
44 }
45 },
46 },
47 },
48})