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

multimodal-tool-result-wire.spec.ts

226 lines12.2 KB

1import { test, expect } from './fixtures'
2​
3/**
4 * Wire-format verification for multimodal tool-result messages (#363).
5 *
6 * A tool message's `content` can be `Array<ContentPart>`, and the
7 * OpenAI / Anthropic / Gemini / Mistral adapters must convert it to structured provider
8 * tool output instead of `JSON.stringify`. This spec drives the route at
9 * `/api/multimodal-tool-result-wire` (which calls `chat()` with a pre-built
10 * conversation that includes a multimodal tool result), then inspects
11 * aimock's journal (`GET /v1/_requests`) to assert the outbound bytes contain
12 * structured tool output per provider.
13 *
14 * Aimock normalises Anthropic and Gemini request bodies to an OpenAI-compatible
15 * form before journalling. As a result:
16 * - OpenAI (Responses API) — image parts survive in body.messages[tool].content
17 * - Anthropic — aimock's claudeToCompletionRequest strips image
18 * blocks from tool_result content; only text survives
19 * - Gemini — aimock's geminiToCompletionRequest strips inlineData
20 * parts from functionResponse; only text survives
21 * The OpenAI assertion therefore verifies image presence directly. The Anthropic
22 * and Gemini assertions verify that the chat() call + adapter completed the
23 * end-to-end HTTP round-trip without a synchronous throw — proving serialization
24 * of the Array<ContentPart> tool result ran to completion. Structural correctness
25 * for those two providers is covered by adapter unit tests.
26 *
27 * Note: the Anthropic and Gemini adapters catch HTTP errors from aimock (no-fixture
28 * 404) and yield a RUN_ERROR stream event rather than throwing. The route therefore
29 * always returns ok:true as long as serialization does not crash synchronously.
30 * This makes ok:true a meaningful proof that the multimodal conversion succeeded.
31 */
32// Serial mode: each test clears then re-populates the aimock journal.
33// Parallel workers would otherwise race on the global journal — one test's
34// beforeEach DELETE clears a sibling test's entries before they are read.
35test.describe.configure({ mode: 'serial' })
36​
37test.describe('multimodal tool result — wire format', () => {
38 test.beforeEach(async ({ request, aimockPort }) => {
39 // Clear the aimock journal before each serial test so we only assert
40 // against the request triggered by this specific test.
41 await request.delete(`http://127.0.0.1:${aimockPort}/v1/_requests`)
42 })
43​
44 // ──────────────────────────────────────────────────────────────────────────
45 // OpenAI (Responses API — /v1/responses)
46 //
47 // aimock stores the normalised CompletionRequest for /v1/responses where
48 // function_call_output.output survives as-is in the tool message content.
49 // When output is an array (multimodal), it appears under
50 // body.messages[role=tool].content: Array<{type, ...}>
51 // with `input_image` and `input_text` items.
52 // ──────────────────────────────────────────────────────────────────────────
53 test('openai: tool message content is a structured array with an image part', async ({
54 request,
55 aimockPort,
56 testId,
57 }) => {
58 await request.post(
59 `/api/multimodal-tool-result-wire?provider=openai&testId=${encodeURIComponent(testId)}`,
60 )
61 const journal = await request.get(
62 `http://127.0.0.1:${aimockPort}/v1/_requests`,
63 )
64 const entries = (await journal.json()) as Array<{ body: any }>
65 // OpenAI Responses API: aimock normalises function_call_output → role:'tool'
66 // and preserves the output array as-is in the content field.
67 const toolMsg = entries[0]?.body?.messages?.find(
68 (m: any) => m.role === 'tool',
69 )
70 expect(Array.isArray(toolMsg?.content)).toBe(true)
71 expect(toolMsg.content.some((p: any) => p.type === 'input_image')).toBe(
72 true,
73 )
74 expect(toolMsg.content.some((p: any) => p.type === 'input_text')).toBe(true)
75 })
76​
77 // ──────────────────────────────────────────────────────────────────────────
78 // Anthropic (/v1/messages)
79 //
80 // The Anthropic adapter wraps the tool result in a user message with a
81 // tool_result block whose content is Array<TextBlock|ImageBlock>. However,
82 // aimock's claudeToCompletionRequest normalisation strips non-text blocks
83 // before journalling. The adapter also catches HTTP errors (aimock returns
84 // a 404 when no fixture matches) and yields a RUN_ERROR event rather than
85 // throwing, so the route always returns ok:true when serialization succeeds.
86 //
87 // Assertion: ok:true proves chat() + the Anthropic adapter serialized the
88 // Array<ContentPart> tool result and completed the round-trip without a
89 // synchronous throw (i.e. the multimodal conversion did not crash).
90 // ──────────────────────────────────────────────────────────────────────────
91 test('anthropic: multimodal tool result completes end-to-end (image structure covered by unit test)', async ({
92 request,
93 testId,
94 }) => {
95 const res = await request.post(
96 `/api/multimodal-tool-result-wire?provider=anthropic&testId=${encodeURIComponent(testId)}`,
97 )
98 const { ok } = (await res.json()) as { ok: boolean; error?: string }
99 // Structural proof that the image becomes a tool_result image block lives in packages/ai-anthropic/tests/tool-result-multimodal.test.ts — aimock's journal strips multimodal tool content so it can't be asserted here.
100 expect(ok).toBe(true)
101 })
102​
103 // ──────────────────────────────────────────────────────────────────────────
104 // Gemini (/v1beta/models/.../streamGenerateContent)
105 //
106 // The Gemini adapter emits a functionResponse with parts:[{inlineData:{...}}]
107 // for the image alongside response:{content:'screenshot'} for the text.
108 // aimock's geminiToCompletionRequest normalises this to role:'tool' and
109 // JSON.stringifies only the response object (dropping inlineData).
110 // The adapter catches HTTP errors (aimock 404 on no-fixture) and yields a
111 // RUN_ERROR event rather than throwing, so ok:true means serialization succeeded.
112 //
113 // Assertion: ok:true proves chat() + the Gemini adapter serialized the
114 // Array<ContentPart> tool result and completed the round-trip without a
115 // synchronous throw (i.e. the multimodal conversion did not crash).
116 // ──────────────────────────────────────────────────────────────────────────
117 test('gemini: multimodal tool result completes end-to-end (image structure covered by unit test)', async ({
118 request,
119 testId,
120 }) => {
121 const res = await request.post(
122 `/api/multimodal-tool-result-wire?provider=gemini&testId=${encodeURIComponent(testId)}`,
123 )
124 const { ok } = (await res.json()) as { ok: boolean; error?: string }
125 // Structural proof that the image becomes a functionResponse.parts inlineData entry lives in packages/ai-gemini/tests/tool-result-multimodal.test.ts — aimock's journal strips multimodal tool content so it can't be asserted here.
126 expect(ok).toBe(true)
127 })
128​
129 // ──────────────────────────────────────────────────────────────────────────
130 // Mistral (/v1/chat/completions)
131 //
132 // Mistral accepts image chunks in a tool message. aimock journals the
133 // chat-completions body as sent, so the tool message content must be an
134 // array with an `image_url` chunk, not a JSON string of the parts.
135 // ──────────────────────────────────────────────────────────────────────────
136 test('mistral: tool message content is an array with an image_url chunk', async ({
137 request,
138 aimockPort,
139 testId,
140 }) => {
141 await request.post(
142 `/api/multimodal-tool-result-wire?provider=mistral&testId=${encodeURIComponent(testId)}`,
143 )
144 const journal = await request.get(
145 `http://127.0.0.1:${aimockPort}/v1/_requests`,
146 )
147 const entries = (await journal.json()) as Array<{ body: any }>
148 const toolMsg = entries[0]?.body?.messages?.find(
149 (m: any) => m.role === 'tool',
150 )
151 expect(Array.isArray(toolMsg?.content)).toBe(true)
152 expect(toolMsg.content).toContainEqual({ type: 'text', text: 'screenshot' })
153 expect(
154 toolMsg.content.some(
155 (p: any) =>
156 p.type === 'image_url' &&
157 typeof p.image_url === 'string' &&
158 p.image_url.startsWith('data:image/png;base64,'),
159 ),
160 ).toBe(true)
161 })
162​
163 // ──────────────────────────────────────────────────────────────────────────
164 // Chat Completions (/v1/chat/completions) on `@tanstack/openai-base` and
165 // OpenRouter chat
166 //
167 // A Chat Completions tool message holds text only. The text goes in the
168 // tool message and the image goes in a user message after it.
169 // ──────────────────────────────────────────────────────────────────────────
170 for (const provider of ['openai-compatible', 'openrouter']) {
171 test(`${provider}: the image follows the tool message in a user message`, async ({
172 request,
173 aimockPort,
174 testId,
175 }) => {
176 await request.post(
177 `/api/multimodal-tool-result-wire?provider=${provider}&testId=${encodeURIComponent(testId)}`,
178 )
179 const journal = await request.get(
180 `http://127.0.0.1:${aimockPort}/v1/_requests`,
181 )
182 const entries = (await journal.json()) as Array<{ body: any }>
183 expect(entries[0]?.body?.messages?.slice(-2)).toMatchObject([
184 { role: 'tool', content: 'screenshot' },
185 {
186 role: 'user',
187 content: [
188 {
189 type: 'image_url',
190 image_url: {
191 url: expect.stringMatching(/^data:image\/png;base64,/),
192 },
193 },
194 ],
195 },
196 ])
197 })
198 }
199​
200 // ──────────────────────────────────────────────────────────────────────────
201 // OpenRouter Responses (/v1/responses)
202 //
203 // The image stays in the function call output, the same as OpenAI above.
204 // ──────────────────────────────────────────────────────────────────────────
205 test('openrouter-responses: tool message content is a structured array with an image part', async ({
206 request,
207 aimockPort,
208 testId,
209 }) => {
210 await request.post(
211 `/api/multimodal-tool-result-wire?provider=openrouter-responses&testId=${encodeURIComponent(testId)}`,
212 )
213 const journal = await request.get(
214 `http://127.0.0.1:${aimockPort}/v1/_requests`,
215 )
216 const entries = (await journal.json()) as Array<{ body: any }>
217 const toolMsg = entries[0]?.body?.messages?.find(
218 (m: any) => m.role === 'tool',
219 )
220 expect(Array.isArray(toolMsg?.content)).toBe(true)
221 expect(toolMsg.content.some((p: any) => p.type === 'input_image')).toBe(
222 true,
223 )
224 expect(toolMsg.content.some((p: any) => p.type === 'input_text')).toBe(true)
225 })
226})