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

api.codemode.ts

196 lines6.4 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { chat, maxIterations, toServerSentEventsStream } from '@tanstack/ai'
3import { createCodeMode } from '@tanstack/ai-code-mode'
4import { anthropicText } from '@tanstack/ai-anthropic'
5import { openaiText } from '@tanstack/ai-openai'
6import { geminiText } from '@tanstack/ai-gemini'
7import type { AnyTextAdapter, StreamChunk } from '@tanstack/ai'
8import { allTools } from '@/lib/tools'
9import { CODE_MODE_SYSTEM_PROMPT } from '@/lib/prompts'
10import { exportConversationToPdfTool } from '@/lib/tools/export-pdf-tool'
11import { maxTokensModelOptions } from '@/lib/max-tokens-model-options'
12​
13type Provider = 'anthropic' | 'openai' | 'gemini'
14​
15function getAdapter(provider: Provider, model?: string): AnyTextAdapter {
16 switch (provider) {
17 case 'openai':
18 return openaiText((model || 'gpt-4o') as 'gpt-4o')
19 case 'gemini':
20 return geminiText((model || 'gemini-2.5-flash') as 'gemini-2.5-flash')
21 case 'anthropic':
22 default:
23 return anthropicText((model || 'claude-haiku-4-5') as 'claude-haiku-4-5')
24 }
26​
27import {
28 createIsolateDriver,
29 type IsolateVM,
30} from '@/lib/create-isolate-driver'
31​
32type CodeModeEntry = {
33 tool: ReturnType<typeof createCodeMode>['tool']
34 systemPrompt: string
36const codeModeCacheByVM = new Map<IsolateVM, CodeModeEntry>()
37​
38async function getCodeModeTools(vm: IsolateVM = 'node') {
39 let entry = codeModeCacheByVM.get(vm)
40 if (!entry) {
41 const driver = await createIsolateDriver(vm)
42 const { tool, systemPrompt } = createCodeMode({
43 driver,
44 tools: allTools,
45 timeout: 60000,
46 memoryLimit: 128,
47 })
48 entry = { tool, systemPrompt }
49 codeModeCacheByVM.set(vm, entry)
50 }
51 return entry
53​
54export const Route = createFileRoute('/_npm-github-chat/api/codemode')({
55 server: {
56 handlers: {
57 POST: async ({ request }) => {
58 const requestSignal = request.signal
59 if (requestSignal.aborted) {
60 return new Response(null, { status: 499 })
61 }
62​
63 const abortController = new AbortController()
64 const body = await request.json()
65 const { messages, data } = body
66​
67 const provider: Provider = data?.provider || 'anthropic'
68 const model: string | undefined = data?.model
69 const vm: IsolateVM = data?.vm || 'node'
70 const serverRuntime =
71 typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined'
72 ? 'bun'
73 : 'node'
74 console.info(
75 `[api/codemode] request provider=${provider} model=${model ?? 'default'} vm=${vm} serverRuntime=${serverRuntime}`,
76 )
77​
78 const adapter = getAdapter(provider, model)
79 const baseChatStream = adapter.chatStream.bind(adapter)
80 let llmCallCount = 0
81 let totalContextBytes = 0
82 const textEncoder = new TextEncoder()
83 const instrumentedAdapter: AnyTextAdapter = {
84 ...adapter,
85 chatStream: (options) => {
86 llmCallCount += 1
87 let contextBytes = 0
88 try {
89 contextBytes = textEncoder.encode(
90 JSON.stringify(options.messages ?? []),
91 ).length
92 } catch {
93 contextBytes = 0
94 }
95 totalContextBytes += contextBytes
96 const averageContextBytes =
97 llmCallCount > 0
98 ? Math.round(totalContextBytes / llmCallCount)
99 : 0
100 const stream = baseChatStream(options)
101 async function* instrumentedStream(): AsyncGenerator<StreamChunk> {
102 yield {
103 type: 'CUSTOM',
104 timestamp: Date.now(),
105 name: 'code_mode:llm_call',
106 value: {
107 count: llmCallCount,
108 contextBytes,
109 totalContextBytes,
110 averageContextBytes,
111 },
112 } as StreamChunk
113 for await (const chunk of stream) {
114 yield chunk
115 }
116 }
117 return instrumentedStream()
118 },
119 }
120 const { tool, systemPrompt } = await getCodeModeTools(vm)
121​
122 try {
123 const stream = chat({
124 adapter: instrumentedAdapter,
125 messages,
126 tools: [tool, exportConversationToPdfTool],
127 systemPrompts: [CODE_MODE_SYSTEM_PROMPT, systemPrompt],
128 agentLoopStrategy: maxIterations(15),
129 abortController,
130 // Increase max tokens to allow for complex code generation
131 modelOptions: maxTokensModelOptions(adapter, 8192),
132 })
133​
134 const requestStartTimeMs = Date.now()
135 const instrumentedStream =
136 (async function* (): AsyncGenerator<StreamChunk> {
137 yield {
138 type: 'CUSTOM',
139 timestamp: requestStartTimeMs,
140 name: 'code_mode:chat_start',
141 value: { startTimeMs: requestStartTimeMs },
142 } as StreamChunk
143 for await (const chunk of stream) {
144 if (chunk.type === 'RUN_FINISHED') {
145 const endTimeMs = Date.now()
146 yield {
147 type: 'CUSTOM',
148 timestamp: endTimeMs,
149 name: 'code_mode:chat_end',
150 value: {
151 endTimeMs,
152 durationMs: endTimeMs - requestStartTimeMs,
153 },
154 } as StreamChunk
155 }
156 yield chunk
157 }
158 })()
159​
160 const sseStream = toServerSentEventsStream(
161 instrumentedStream,
162 abortController,
163 )
164​
165 return new Response(sseStream, {
166 headers: {
167 'Content-Type': 'text/event-stream',
168 'Cache-Control': 'no-cache',
169 Connection: 'keep-alive',
170 },
171 })
172 } catch (error: unknown) {
173 console.error('[API Route] Error:', error)
174​
175 if (
176 (error instanceof Error && error.name === 'AbortError') ||
177 abortController.signal.aborted
178 ) {
179 return new Response(null, { status: 499 })
180 }
181​
182 return new Response(
183 JSON.stringify({
184 error:
185 error instanceof Error ? error.message : 'An error occurred',
186 }),
187 {
188 status: 500,
189 headers: { 'Content-Type': 'application/json' },
190 },
191 )
192 }
193 },
194 },
195 },
196})