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

api.execute-prompt.ts

138 lines4.8 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { anthropicText } from '@tanstack/ai-anthropic'
3import { createCodeMode } from '@tanstack/ai-code-mode'
4import type { IsolateDriver } from '@tanstack/ai-code-mode'
5import type { CodeExecution } from '@/lib/execute-prompt-realtime-tools'
6import { createExecutePromptTool } from '@/lib/create-execute-prompt-tool'
7import { productTools } from '@/lib/tools/product-tools'
8​
9const SHOE_EXECUTE_PROMPT_SYSTEM = `You are an analytical assistant for a shoe product catalog. You can execute TypeScript code to query the product API and compute answers.
10​
11## Available External APIs (inside execute_typescript)
12​
13- \`external_getProductListPage({ page })\` — Returns { productIds: string[], totalPages: number } (10 product IDs per page, 1-based page number)
14- \`external_getProductByID({ id })\` — Returns full product details: { id, name, brand, price, category, color, sizeRange }
15​
16## Strategy
17​
18The product API is paginated. To get all products:
191. Call getProductListPage with page 1 to get the first page of IDs and totalPages
202. Fetch remaining pages as needed
213. Fetch each product by ID
224. Compute the answer from the data
23​
24Return JSON in whatever format is appropriate for the user's question. Output only JSON in your final message, nothing else.`
25​
26let cachedDriver: IsolateDriver | null = null
27​
28async function getDriver(): Promise<IsolateDriver> {
29 if (!cachedDriver) {
30 const { createIsolateDriver } = await import('@/lib/create-isolate-driver')
31 cachedDriver = await createIsolateDriver()
32 }
33 return cachedDriver
35​
36export const Route = createFileRoute(
37 '/_execute-prompt/api/execute-prompt' as any,
38)({
39 server: {
40 handlers: {
41 POST: async ({ request }) => {
42 try {
43 let body: unknown
44 try {
45 body = await request.json()
46 } catch {
47 return new Response(
48 JSON.stringify({ error: 'Invalid or empty JSON body' }),
49 { status: 400, headers: { 'Content-Type': 'application/json' } },
50 )
51 }
52 const prompt =
53 body &&
54 typeof body === 'object' &&
55 'prompt' in body &&
56 typeof (body as { prompt?: unknown }).prompt === 'string'
57 ? (body as { prompt: string }).prompt
58 : undefined
59 if (typeof prompt !== 'string' || !prompt.trim()) {
60 return new Response(
61 JSON.stringify({ error: 'Missing or invalid "prompt" string' }),
62 { status: 400, headers: { 'Content-Type': 'application/json' } },
63 )
64 }
65​
66 const driver = await getDriver()
67 const adapter = anthropicText('claude-haiku-4-5')
68 const codeMode = createCodeMode({
69 driver,
70 tools: productTools,
71 timeout: 60000,
72 memoryLimit: 128,
73 })
74​
75 const executions: Array<CodeExecution> = []
76 const rawCodeTool = codeMode.tool
77 const tracedInner = {
78 ...codeMode,
79 tool: {
80 ...rawCodeTool,
81 execute: async (
82 input: { typescriptCode: string },
83 ctx?: unknown,
84 ) => {
85 const output = await rawCodeTool.execute!(
86 input,
87 ctx as Parameters<NonNullable<typeof rawCodeTool.execute>>[1],
88 )
89 const o = output as {
90 success: boolean
91 result?: unknown
92 logs?: Array<string>
93 error?: { message: string; name?: string }
94 }
95 executions.push({
96 typescriptCode: input.typescriptCode,
97 success: o.success,
98 result: o.result,
99 logs: o.logs,
100 error: o.error,
101 })
102 return output
103 },
104 },
105 }
106​
107 const { tool } = createExecutePromptTool({
108 adapter,
109 inner: tracedInner,
110 system: SHOE_EXECUTE_PROMPT_SYSTEM,
111 })
112​
113 const result = await tool.execute!({ prompt: prompt.trim() })
114​
115 return new Response(
116 JSON.stringify({
117 data: result.data,
118 executions,
119 }),
120 {
121 status: 200,
122 headers: { 'Content-Type': 'application/json' },
123 },
124 )
125 } catch (error: unknown) {
126 console.error('[API execute-prompt]', error)
127 return new Response(
128 JSON.stringify({
129 error:
130 error instanceof Error ? error.message : 'executePrompt failed',
131 }),
132 { status: 500, headers: { 'Content-Type': 'application/json' } },
133 )
134 }
135 },
136 },
137 },
138})