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

vite.config.ts

76 lines2.3 KB

1import { defineConfig } from 'vite'
2import angular from '@analogjs/vite-plugin-angular'
3import tailwindcss from '@tailwindcss/vite'
4import {
5 chat,
6 chatParamsFromRequestBody,
7 maxIterations,
8 mergeAgentTools,
9 toServerSentEventsStream,
10} from '@tanstack/ai'
11import { openaiText } from '@tanstack/ai-openai'
12import dotenv from 'dotenv'
13​
14dotenv.config()
15​
16export default defineConfig({
17 plugins: [
18 angular(),
19 tailwindcss(),
20 {
21 name: 'api-handler',
22 configureServer(server) {
23 server.middlewares.use('/api/chat', async (req, res) => {
24 if (req.method !== 'POST') {
25 res.statusCode = 405
26 res.end('Method Not Allowed')
27 return
28 }
29 let body = ''
30 for await (const chunk of req) body += chunk
31​
32 let params
33 try {
34 params = await chatParamsFromRequestBody(JSON.parse(body))
35 } catch (error) {
36 res.statusCode = 400
37 res.end(error instanceof Error ? error.message : 'Bad request')
38 return
39 }
40​
41 try {
42 const abortController = new AbortController()
43 const stream = chat({
44 adapter: openaiText('gpt-5.5'),
45 tools: mergeAgentTools([], params.tools),
46 systemPrompts: ['You are a helpful assistant.'],
47 agentLoopStrategy: maxIterations(10),
48 messages: params.messages,
49 threadId: params.threadId,
50 runId: params.runId,
51 abortController,
52 })
53 const readable = toServerSentEventsStream(stream, abortController)
54 res.setHeader('Content-Type', 'text/event-stream')
55 res.setHeader('Cache-Control', 'no-cache')
56 res.setHeader('Connection', 'keep-alive')
57 const reader = readable.getReader()
58 const pump = async () => {
59 while (true) {
60 const { done, value } = await reader.read()
61 if (done) break
62 res.write(value)
63 }
64 res.end()
65 }
66 pump().catch(() => res.end())
67 } catch (error: any) {
68 res.statusCode = 500
69 res.setHeader('Content-Type', 'application/json')
70 res.end(JSON.stringify({ error: error?.message ?? 'error' }))
71 }
72 })
73 },
74 },
75 ],
76})