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

api.execute-prompt.ts

136 lines4.7 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('/_execute-prompt/api/execute-prompt')({
37 server: {
38 handlers: {
39 POST: async ({ request }) => {
40 try {
41 let body: unknown
42 try {
43 body = await request.json()
44 } catch {
45 return new Response(
46 JSON.stringify({ error: 'Invalid or empty JSON body' }),
47 { status: 400, headers: { 'Content-Type': 'application/json' } },
48 )
49 }
50 const prompt =
51 body &&
52 typeof body === 'object' &&
53 'prompt' in body &&
54 typeof (body as { prompt?: unknown }).prompt === 'string'
55 ? (body as { prompt: string }).prompt
56 : undefined
57 if (typeof prompt !== 'string' || !prompt.trim()) {
58 return new Response(
59 JSON.stringify({ error: 'Missing or invalid "prompt" string' }),
60 { status: 400, headers: { 'Content-Type': 'application/json' } },
61 )
62 }
63​
64 const driver = await getDriver()
65 const adapter = anthropicText('claude-haiku-4-5')
66 const codeMode = createCodeMode({
67 driver,
68 tools: productTools,
69 timeout: 60000,
70 memoryLimit: 128,
71 })
72​
73 const executions: Array<CodeExecution> = []
74 const rawCodeTool = codeMode.tool
75 const tracedInner = {
76 ...codeMode,
77 tool: {
78 ...rawCodeTool,
79 execute: async (
80 input: { typescriptCode: string },
81 ctx?: unknown,
82 ) => {
83 const output = await rawCodeTool.execute!(
84 input,
85 ctx as Parameters<NonNullable<typeof rawCodeTool.execute>>[1],
86 )
87 const o = output as {
88 success: boolean
89 result?: unknown
90 logs?: Array<string>
91 error?: { message: string; name?: string }
92 }
93 executions.push({
94 typescriptCode: input.typescriptCode,
95 success: o.success,
96 result: o.result,
97 logs: o.logs,
98 error: o.error,
99 })
100 return output
101 },
102 },
103 }
104​
105 const { tool } = createExecutePromptTool({
106 adapter,
107 inner: tracedInner,
108 system: SHOE_EXECUTE_PROMPT_SYSTEM,
109 })
110​
111 const result = await tool.execute!({ prompt: prompt.trim() })
112​
113 return new Response(
114 JSON.stringify({
115 data: result.data,
116 executions,
117 }),
118 {
119 status: 200,
120 headers: { 'Content-Type': 'application/json' },
121 },
122 )
123 } catch (error: unknown) {
124 console.error('[API execute-prompt]', error)
125 return new Response(
126 JSON.stringify({
127 error:
128 error instanceof Error ? error.message : 'executePrompt failed',
129 }),
130 { status: 500, headers: { 'Content-Type': 'application/json' } },
131 )
132 }
133 },
134 },
135 },
136})