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

tool-choice.spec.ts

125 lines3.6 KB

1import { test, expect } from './fixtures'
2import type { APIRequestContext } from '@playwright/test'
3​
4/**
5 * Wire-format verification for `chat({ toolChoice })`.
6 *
7 * OpenAI runs through `/api/chat` and aimock. The `tool-choice` feature asks
8 * for the named tool `getGuitars`, and aimock's journal keeps `tool_choice`
9 * for Responses requests, so the spec reads it back from there.
10 *
11 * aimock stores Anthropic requests in OpenAI shape and drops `tool_choice`.
12 * The Anthropic cases use `/api/tool-choice-wire`, which captures the request
13 * body with a custom `fetch`.
14 */
15test.describe('tool choice — wire format', () => {
16 test('openai sends a named tool as a function tool_choice', async ({
17 request,
18 testId,
19 aimockPort,
20 }) => {
21 const response = await request.post('/api/chat', {
22 data: {
23 threadId: 'thread-tool-choice-1',
24 runId: 'run-tool-choice-1',
25 state: {},
26 messages: [
27 {
28 id: 'u1',
29 role: 'user',
30 content: '[toolchoice] what guitars do you have in stock',
31 },
32 ],
33 tools: [],
34 context: [],
35 forwardedProps: {
36 provider: 'openai',
37 feature: 'tool-choice',
38 testId,
39 aimockPort,
40 },
41 },
42 })
43 expect(
44 response.ok(),
45 `expected 200, got ${response.status()}: ${await response.text()}`,
46 ).toBe(true)
47 const text = await response.text()
48 expect(text).toContain('RUN_FINISHED')
49 expect(text).not.toContain('RUN_ERROR')
50​
51 const bodies = await readCapturedBodies(request, aimockPort, testId)
52​
53 // The first request of the run carries the caller's choice.
54 expect(bodies[0]).toHaveProperty('tool_choice', {
55 type: 'function',
56 name: 'getGuitars',
57 })
58 })
59​
60 const anthropicCases = [
61 {
62 model: 'claude-sonnet-4-5',
63 label: 'forces the named tool',
64 expected: { type: 'tool', name: 'getGuitars' },
65 },
66 {
67 // This model rejects a forced tool, so the adapter falls back to auto.
68 model: 'claude-opus-5-5',
69 label: 'falls back to auto',
70 expected: { type: 'auto' },
71 },
72 ]
73​
74 for (const { model, label, expected } of anthropicCases) {
75 test(`anthropic ${model} ${label}`, async ({ request }) => {
76 const response = await request.post('/api/tool-choice-wire', {
77 data: { model },
78 })
79 expect(response.ok()).toBe(true)
80 const payload: {
81 ok: boolean
82 error?: string
83 capturedBodies: Array<unknown>
84 } = await response.json()
85 expect(payload, payload.error).toMatchObject({ ok: true })
86​
87 expect(payload.capturedBodies).toHaveLength(1)
88 expect(payload.capturedBodies[0]).toHaveProperty('tool_choice', expected)
89 })
90 }
91})
92​
93/**
94 * Reads the request bodies this test's own run sent to aimock, oldest first.
95 *
96 * aimock is a singleton shared by every Playwright worker, so select this
97 * test's entries by the `X-Test-Id` header that `createTextAdapter` adds, the
98 * same as `provider-tool-dispatch-wire.spec.ts`.
99 */
100async function readCapturedBodies(
101 request: APIRequestContext,
102 aimockPort: number,
103 testId: string,
104): Promise<Array<unknown>> {
105 const response = await request.get(
106 `http://127.0.0.1:${aimockPort}/v1/_requests`,
107 )
108 const entries: Array<{
109 headers?: Record<string, string>
110 body: unknown
111 }> = await response.json()
112​
113 const mine = entries.filter((entry) =>
114 Object.entries(entry.headers ?? {}).some(
115 ([key, value]) => key.toLowerCase() === 'x-test-id' && value === testId,
116 ),
117 )
118​
119 expect(
120 mine,
121 `no aimock journal entry carried X-Test-Id "${testId}"`,
122 ).not.toHaveLength(0)
123​
124 return mine.map((entry) => entry.body)