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

api.byok-chat.ts

73 lines2.3 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequestBody,
5 toServerSentEventsResponse,
6} from '@tanstack/ai'
7import { byokMissing, getByokKey } from '@tanstack/ai/byok/server'
8import { createTextAdapter } from '@/lib/providers'
9​
10export const Route = createFileRoute('/api/byok-chat')({
11 server: {
12 handlers: {
13 POST: async ({ request }) => {
14 await import('@/lib/llmock-server').then((m) => m.ensureLLMock())
15 if (request.signal.aborted) {
16 return new Response(null, { status: 499 })
17 }
18​
19 const key = getByokKey(request, 'openai')
20 if (!key) return byokMissing('openai')
21​
22 const abortController = new AbortController()
23​
24 let params
25 try {
26 params = await chatParamsFromRequestBody(await request.json())
27 } catch (error) {
28 return new Response(
29 error instanceof Error ? error.message : 'Bad request',
30 { status: 400 },
31 )
32 }
33​
34 const fp = params.forwardedProps
35 const testId = typeof fp.testId === 'string' ? fp.testId : undefined
36 const aimockPort =
37 fp.aimockPort != null ? Number(fp.aimockPort) : undefined
38​
39 try {
40 const adapterOptions = createTextAdapter(
41 'openai',
42 undefined,
43 aimockPort,
44 testId,
45 'chat',
46 )
47 const stream = chat({
48 ...adapterOptions,
49 systemPrompts: ['You are a helpful assistant for a guitar store.'],
50 messages: params.messages,
51 threadId: params.threadId,
52 runId: params.runId,
53 abortController,
54 })
55 return toServerSentEventsResponse(stream, { abortController })
56 } catch (error) {
57 if (
58 (error instanceof Error && error.name === 'AbortError') ||
59 abortController.signal.aborted
60 ) {
61 return new Response(null, { status: 499 })
62 }
63 const message =
64 error instanceof Error ? error.message : 'An error occurred'
65 return new Response(JSON.stringify({ error: message }), {
66 status: 500,
67 headers: { 'Content-Type': 'application/json' },
68 })
69 }
70 },
71 },
72 },
73})