Open History to see the last commit
1import type { Tool } from "@tanstack/ai";
2
3/**
4 * Tool Definitions
5 */
6export const AVAILABLE_TOOLS: Tool[] = [
7 {
8 type: "function",
9 function: {
10 name: "get_weather",
11 description: "Get the current weather for a location",
12 parameters: {
13 type: "object",
14 properties: {
15 location: {
16 type: "string",
17 description: "The city and state, e.g. San Francisco, CA",
18 },
19 unit: {
20 type: "string",
21 enum: ["celsius", "fahrenheit"],
22 description: "The temperature unit to use",
23 },
24 },
25 required: ["location"],
26 },
27 },
28 execute: executeGetWeather,
29 },
30 {
31 type: "function",
32 function: {
33 name: "calculate",
34 description:
35 "Perform a mathematical calculation. Supports basic arithmetic operations.",
36 parameters: {
37 type: "object",
38 properties: {
39 expression: {
40 type: "string",
41 description:
42 "The mathematical expression to evaluate, e.g. '2 + 2' or '10 * 5'",
43 },
44 },
45 required: ["expression"],
46 },
47 },
48 execute: executeCalculate,
49 },
50 {
51 type: "function",
52 function: {
53 name: "search",
54 description: "Search for information on a topic",
55 parameters: {
56 type: "object",
57 properties: {
58 query: {
59 type: "string",
60 description: "The search query",
61 },
62 max_results: {
63 type: "number",
64 description: "Maximum number of results to return (1-10)",
65 minimum: 1,
66 maximum: 10,
67 },
68 },
69 required: ["query"],
70 },
71 },
72 execute: executeSearch,
73 },
74 {
75 type: "function",
76 function: {
77 name: "get_current_time",
78 description: "Get the current date and time",
79 parameters: {
80 type: "object",
81 properties: {
82 timezone: {
83 type: "string",
84 description:
85 "The timezone to use, e.g. 'America/New_York' or 'UTC'",
86 },
87 },
88 required: [],
89 },
90 },
91 execute: executeGetCurrentTime,
92 },
93];
94
95/**
96 * Tool Implementations
97 */
98
99export async function executeGetWeather(args: {
100 location: string;
101 unit?: string;
102}): Promise<string> {
103 // Mock implementation - in a real app, this would call a weather API
104 const { location, unit = "fahrenheit" } = args;
105
106 const temps = {
107 fahrenheit: Math.floor(Math.random() * 40) + 50, // 50-90°F
108 celsius: Math.floor(Math.random() * 25) + 10, // 10-35°C
109 };
110
111 const conditions = ["sunny", "cloudy", "rainy", "partly cloudy", "clear"];
112 const condition = conditions[Math.floor(Math.random() * conditions.length)];
113
114 const temp = temps[unit as keyof typeof temps] || temps.fahrenheit;
115
116 return JSON.stringify({
117 location,
118 temperature: temp,
119 unit,
120 condition,
121 humidity: Math.floor(Math.random() * 50) + 30,
122 wind_speed: Math.floor(Math.random() * 20) + 5,
123 });
124}
125
126export async function executeCalculate(args: {
127 expression: string;
128}): Promise<string> {
129 try {
130 const { expression } = args;
131
132 // Simple safe evaluation - only allows basic math
133 // In production, use a proper math parser library
134 const sanitized = expression.replace(/[^0-9+\-*/().\s]/g, "");
135
136 if (sanitized !== expression) {
137 throw new Error("Invalid characters in expression");
138 }
139
140 // eslint-disable-next-line no-eval
141 const result = eval(sanitized);
142
143 return JSON.stringify({
144 expression,
145 result,
146 formatted: `${expression} = ${result}`,
147 });
148 } catch (error: any) {
149 return JSON.stringify({
150 error: true,
151 message: `Failed to calculate: ${error.message}`,
152 });
153 }
154}
155
156export async function executeSearch(args: {
157 query: string;
158 max_results?: number;
159}): Promise<string> {
160 // Mock implementation - in a real app, this would call a search API
161 const { query, max_results = 3 } = args;
162
163 const mockResults = [
164 {
165 title: `Understanding ${query}`,
166 snippet: `Comprehensive guide to ${query} with examples and best practices.`,
167 url: `https://example.com/${query.toLowerCase().replace(/\s+/g, "-")}`,
168 },
169 {
170 title: `${query} - Complete Tutorial`,
171 snippet: `Learn everything about ${query} from basics to advanced concepts.`,
172 url: `https://tutorial.com/${query.toLowerCase().replace(/\s+/g, "-")}`,
173 },
174 {
175 title: `Top 10 ${query} Tips`,
176 snippet: `Expert tips and tricks for working with ${query}.`,
177 url: `https://tips.com/${query.toLowerCase().replace(/\s+/g, "-")}`,
178 },
179 ];
180
181 return JSON.stringify({
182 query,
183 results: mockResults.slice(0, max_results),
184 total_found: mockResults.length,
185 });
186}
187
188export async function executeGetCurrentTime(args: {
189 timezone?: string;
190}): Promise<string> {
191 const { timezone = "UTC" } = args;
192
193 try {
194 const now = new Date();
195 const formatted =
196 timezone === "UTC"
197 ? now.toUTCString()
198 : now.toLocaleString("en-US", { timeZone: timezone });
199
200 return JSON.stringify({
201 timezone,
202 datetime: formatted,
203 timestamp: now.getTime(),
204 iso: now.toISOString(),
205 });
206 } catch (error: any) {
207 return JSON.stringify({
208 error: true,
209 message: `Invalid timezone: ${timezone}`,
210 });
211 }
212}
213
214// Note: Tool execution is now handled automatically by streamChat
215// when tools have execute functions defined
216
217/**
218 * Get tool by name
219 */
220export function getToolByName(name: string): Tool | undefined {
221 return AVAILABLE_TOOLS.find((t) => t.function.name === name);
222}
223
224/**
225 * List all available tools
226 */
227export function listTools(): string {
228 return AVAILABLE_TOOLS.map(
229 (t) => `- ${t.function.name}: ${t.function.description}`
230 ).join("\n");
231}