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

api.image-tool-repro.ts

72 lines2.6 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequestBody,
5 maxIterations,
6 toServerSentEventsResponse,
7} from '@tanstack/ai'
8import { openaiText } from '@tanstack/ai-openai'
9import { getReproImage } from '@/lib/image-tool-repro'
10​
11/**
12 * Repro endpoint for https://github.com/TanStack/ai/issues/363
13 *
14 * Uses a single server tool (`getReproImage`) that returns a multimodal
15 * content-part array. The system prompt forces the model to declare whether it
16 * could actually SEE the returned image, giving a crisp pass/fail signal.
17 */
18const SYSTEM_PROMPT = `You are a vision QA assistant. You have one tool: getReproImage(), which returns an image.
19​
20When the user asks you to inspect the image, follow these steps exactly:
211. Call the getReproImage tool.
222. Look at what the tool returned.
233. If you can actually SEE an image, begin your reply with "VISIBLE:" followed by the exact number printed in the image.
244. If the tool result was only text, JSON, or base64 data that you cannot view as an image, begin your reply with "NOT-VISIBLE:" and explain that you only received data you could not view.
25​
26Never guess the number. Only report a number you can actually read in an image. If you cannot see an image, you must say NOT-VISIBLE.`
27​
28export const Route = createFileRoute('/api/image-tool-repro')({
29 server: {
30 handlers: {
31 POST: async ({ request }) => {
32 if (request.signal.aborted) {
33 return new Response(null, { status: 499 })
34 }
35​
36 const abortController = new AbortController()
37​
38 let params
39 try {
40 params = await chatParamsFromRequestBody(await request.json())
41 } catch (error) {
42 return new Response(
43 error instanceof Error ? error.message : 'Bad request',
44 { status: 400 },
45 )
46 }
47​
48 try {
49 const stream = chat({
50 adapter: openaiText('gpt-4o'),
51 tools: [getReproImage],
52 systemPrompts: [SYSTEM_PROMPT],
53 agentLoopStrategy: maxIterations(5),
54 messages: params.messages,
55 threadId: params.threadId,
56 runId: params.runId,
57 abortController,
58 })
59 return toServerSentEventsResponse(stream, { abortController })
60 } catch (error: any) {
61 if (error.name === 'AbortError' || abortController.signal.aborted) {
62 return new Response(null, { status: 499 })
63 }
64 return new Response(
65 JSON.stringify({ error: error.message || 'An error occurred' }),
66 { status: 500, headers: { 'Content-Type': 'application/json' } },
67 )
68 }
69 },
70 },
71 },
72})