Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { chat, toolDefinition } from '@tanstack/ai'
3import { fakeText } from '@tanstack/ai/testing'
4
5// No network: `fakeText` answers from a script. The first answer calls a
6// JSON Schema tool twice: once with a value that cannot be repaired, once
7// with a number sent as a string. It also calls an OpenAPI 3.0 tool with
8// `null` for a `nullable` field. The second answer repeats the tool results.
9// MCP tools have the same raw JSON Schema input. With `{ repair: 'custom' }`,
10// a `repairToolInput` function replaces the built-in repair: it maps
11// `'many'` to 2 and repairs nothing else.
12export const Route = createFileRoute('/api/json-schema-tool-input')({
13 server: {
14 handlers: {
15 POST: async ({ request }) => {
16 const body: unknown = await request.json().catch(() => ({}))
17 const custom =
18 typeof body === 'object' &&
19 body !== null &&
20 'repair' in body &&
21 body.repair === 'custom'
22
23 const fake = fakeText()
24 fake.setResponses([
25 {
26 toolCalls: [
27 { name: 'count_items', input: { count: 'many' } },
28 { name: 'count_items', input: { count: '3' } },
29 { name: 'label_item', input: { label: null } },
30 ],
31 },
32 ({ request }) => ({
33 text: request.messages
34 .filter((message) => message.role === 'tool')
35 .map((message) => `Tool said: ${String(message.content)}`)
36 .join('\n'),
37 }),
38 ])
39
40 const runs: Array<unknown> = []
41 const countItems = toolDefinition({
42 name: 'count_items',
43 description: 'Count the items',
44 inputSchema: {
45 $schema: 'http://json-schema.org/draft-07/schema#',
46 type: 'object',
47 properties: { count: { type: 'integer' } },
48 required: ['count'],
49 },
50 }).server((input) => {
51 runs.push(input)
52 return 'counted'
53 })
54 const labelItem = toolDefinition({
55 name: 'label_item',
56 description: 'Label the item',
57 inputSchema: {
58 type: 'object',
59 properties: { label: { type: 'string', nullable: true } },
60 required: ['label'],
61 },
62 }).server((input) => {
63 runs.push(input)
64 return 'labeled'
65 })
66
67 const { text } = await chat({
68 threadId: 'json-schema-tool-input',
69 adapter: fake,
70 messages: [{ role: 'user', content: 'Count the items' }],
71 tools: [countItems, labelItem],
72 stream: false,
73 ...(custom && {
74 repairToolInput: ({ input }) =>
75 typeof input === 'object' &&
76 input !== null &&
77 'count' in input &&
78 input.count === 'many'
79 ? { count: 2 }
80 : undefined,
81 }),
82 })
83
84 return Response.json({ text, runs })
85 },
86 },
87 },
88})