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

chat-tools.ts

133 lines3.6 KB

1import { toolDefinition } from '@tanstack/ai'
2import { z } from 'zod'
3​
4/**
5 * A set of client-side tools that run in the browser. Each is defined with
6 * `toolDefinition(...).client(fn)` and wired into `injectChat` via
7 * `tools: clientTools(...)`. On the server they are passed through
8 * `mergeAgentTools([], params.tools)` as no-execute entries, so the model can
9 * request them and the browser executes them.
10 */
11​
12/** Returns the current local time as an ISO string. */
13export const getTimeTool = toolDefinition({
14 name: 'getTime',
15 description: 'Returns the current local time as an ISO string.',
16 inputSchema: z.object({}),
17 outputSchema: z.object({ time: z.string() }),
18}).client(() => ({
19 time: new Date().toISOString(),
20}))
21​
22/** Rolls one or more dice and returns each roll plus the total. */
23export const rollDiceTool = toolDefinition({
24 name: 'rollDice',
25 description:
26 'Roll one or more dice. Use for any "roll a die/dice" request. Defaults to a single six-sided die.',
27 inputSchema: z.object({
28 sides: z
29 .number()
30 .int()
31 .min(2)
32 .max(100)
33 .optional()
34 .describe('Number of sides per die (default 6).'),
35 count: z
36 .number()
37 .int()
38 .min(1)
39 .max(10)
40 .optional()
41 .describe('How many dice to roll (default 1).'),
42 }),
43 outputSchema: z.object({
44 rolls: z.array(z.number()),
45 total: z.number(),
46 }),
47}).client(({ sides, count }) => {
48 const faces = sides ?? 6
49 const dice = count ?? 1
50 const rolls = Array.from(
51 { length: dice },
52 () => 1 + Math.floor(Math.random() * faces),
53 )
54 return { rolls, total: rolls.reduce((sum, n) => sum + n, 0) }
55})
56​
57/** Flips a fair coin. */
58export const flipCoinTool = toolDefinition({
59 name: 'flipCoin',
60 description: 'Flip a fair coin and return heads or tails.',
61 inputSchema: z.object({}),
62 outputSchema: z.object({ result: z.enum(['heads', 'tails']) }),
63}).client(() => ({
64 result: Math.random() < 0.5 ? ('heads' as const) : ('tails' as const),
65}))
66​
67/** Performs basic arithmetic on two numbers. */
68export const calculateTool = toolDefinition({
69 name: 'calculate',
70 description:
71 'Perform basic arithmetic (add, subtract, multiply, divide) on two numbers.',
72 inputSchema: z.object({
73 a: z.number(),
74 b: z.number(),
75 operation: z.enum(['add', 'subtract', 'multiply', 'divide']),
76 }),
77 outputSchema: z.object({ result: z.number() }),
78}).client(({ a, b, operation }) => {
79 switch (operation) {
80 case 'add':
81 return { result: a + b }
82 case 'subtract':
83 return { result: a - b }
84 case 'multiply':
85 return { result: a * b }
86 case 'divide':
87 return { result: b === 0 ? NaN : a / b }
88 }
89})
90​
91/** Returns a mock weather report for a city (no network call). */
92const WEATHER_CONDITIONS = [
93 'Sunny',
94 'Partly cloudy',
95 'Cloudy',
96 'Rainy',
97 'Windy',
98 'Foggy',
99 'Snowy',
100] as const
101​
102export const getWeatherTool = toolDefinition({
103 name: 'getWeather',
104 description:
105 'Get a (mock) weather report for a city. Returns a temperature in Celsius and a condition.',
106 inputSchema: z.object({
107 city: z.string().describe('City name, e.g. "Tokyo".'),
108 }),
109 outputSchema: z.object({
110 city: z.string(),
111 temperatureC: z.number(),
112 condition: z.string(),
113 }),
114}).client(({ city }) => {
115 const seed = [...city.toLowerCase()].reduce(
116 (sum, ch) => sum + ch.charCodeAt(0),
117 0,
118 )
119 return {
120 city,
121 temperatureC: 4 + (seed % 26),
122 condition: WEATHER_CONDITIONS[seed % WEATHER_CONDITIONS.length],
123 }
124})
125​
126/** All client tools, ready to spread into `clientTools(...)`. */
127export const chatTools = [
128 getTimeTool,
129 rollDiceTool,
130 flipCoinTool,
131 calculateTool,
132 getWeatherTool,
133] as const