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'
4import { z } from 'zod'
5
6// No network: `fakeText` answers from a script. The first answer calls a
7// tool, the second answer is the final text.
8export const Route = createFileRoute('/api/fake-text')({
9 server: {
10 handlers: {
11 POST: async () => {
12 const fake = fakeText()
13 fake.setResponses([
14 { toolCalls: [{ name: 'getWeather', input: { city: 'Oslo' } }] },
15 ({ request }) => ({
16 text: `Tool said: ${String(request.messages.at(-1)?.content)}`,
17 }),
18 ])
19
20 const getWeather = toolDefinition({
21 name: 'getWeather',
22 description: 'Get the weather for a city',
23 inputSchema: z.object({ city: z.string() }),
24 }).server(({ city }) => `sunny in ${city}`)
25
26 const { text } = await chat({
27 adapter: fake,
28 messages: [{ role: 'user', content: 'Weather in Oslo?' }],
29 tools: [getWeather],
30 stream: false,
31 })
32
33 return Response.json({
34 text,
35 callCount: fake.state.callCount,
36 pending: fake.pendingResponses(),
37 })
38 },
39 },
40 },
41})