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

api.transcribe.ts

52 lines1.5 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 generateTranscription,
4 generationParamsFromBody,
5 toServerSentEventsResponse,
6} from '@tanstack/ai'
7import { byokMissing, getByokKey } from '@tanstack/ai/byok/server'
8import { openaiByok } from '@tanstack/ai-openai/byok'
9import { createOpenaiTranscription } from '@tanstack/ai-openai'
10​
11export const Route = createFileRoute('/api/transcribe')({
12 server: {
13 handlers: {
14 GET: async () =>
15 new Response('Use POST', {
16 status: 405,
17 headers: { allow: 'POST' },
18 }),
19 POST: async ({ request }) => {
20 const apiKey = getByokKey(request, openaiByok)
21 if (!apiKey) return byokMissing(openaiByok)
22​
23 let params
24 try {
25 params = generationParamsFromBody(
26 'transcription',
27 await request.json(),
28 )
29 } catch (error) {
30 return new Response(
31 error instanceof Error ? error.message : 'Bad request',
32 { status: 400 },
33 )
34 }
35​
36 if (!params.threadId) {
37 return new Response('threadId is required.', { status: 400 })
38 }
39​
40 const stream = generateTranscription({
41 adapter: createOpenaiTranscription('gpt-4o-transcribe', apiKey),
42 ...params.input,
43 stream: true,
44 threadId: params.threadId,
45 runId: params.runId,
46 })
47​
48 return toServerSentEventsResponse(stream)
49 },
50 },
51 },
52})