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

tool-registry-example.ts

325 lines10.0 KB

1/**
2 * Tool Registry Example
3 *
4 * Demonstrates the new tool registry API where tools are defined once
5 * in the constructor and then referenced by name in chat calls.
6 */
7
8import { AI } from "@ts-poc/ai";
9import { OpenAIAdapter } from "@ts-poc/ai-openai";
10import { OllamaAdapter } from "@ts-poc/ai-ollama";
12// Define all tools in a type-safe registry
13const tools = {
14 get_weather: {
15 type: "function" as const,
16 function: {
17 name: "get_weather",
18 description: "Get current weather for a location",
19 parameters: {
20 type: "object",
21 properties: {
22 location: {
23 type: "string",
24 description: "City name, e.g. 'San Francisco'"
25 },
26 unit: {
27 type: "string",
28 enum: ["celsius", "fahrenheit"],
29 description: "Temperature unit"
30 }
31 },
32 required: ["location"],
33 },
34 },
35 execute: async (args: { location: string; unit?: string }) => {
36 console.log(` → Fetching weather for ${args.location} in ${args.unit || "fahrenheit"}`);
37 // Simulate API call
38 return JSON.stringify({
39 location: args.location,
40 temperature: args.unit === "celsius" ? 22 : 72,
41 condition: "sunny",
42 humidity: 65,
43 });
44 },
45 },
47 calculate: {
48 type: "function" as const,
49 function: {
50 name: "calculate",
51 description: "Perform mathematical calculations",
52 parameters: {
53 type: "object",
54 properties: {
55 expression: {
56 type: "string",
57 description: "Math expression to evaluate, e.g. '2 + 2'"
58 },
59 },
60 required: ["expression"],
61 },
62 },
63 execute: async (args: { expression: string }) => {
64 console.log(` → Calculating: ${args.expression}`);
65 try {
66 // In production, use a safe math parser!
67 const result = eval(args.expression);
68 return JSON.stringify({ result, expression: args.expression });
69 } catch (error: any) {
70 return JSON.stringify({ error: error.message });
71 }
72 },
73 },
75 search_database: {
76 type: "function" as const,
77 function: {
78 name: "search_database",
79 description: "Search the product database",
80 parameters: {
81 type: "object",
82 properties: {
83 query: {
84 type: "string",
85 description: "Search query"
86 },
87 limit: {
88 type: "number",
89 description: "Maximum number of results",
90 default: 5
91 }
92 },
93 required: ["query"],
94 },
95 },
96 execute: async (args: { query: string; limit?: number }) => {
97 console.log(` → Searching database for: "${args.query}" (limit: ${args.limit || 5})`);
98 // Simulate database search
99 return JSON.stringify({
100 query: args.query,
101 results: [
102 { id: 1, name: "Product A", relevance: 0.95 },
103 { id: 2, name: "Product B", relevance: 0.87 },
104 ],
105 });
106 },
107 },
109 send_email: {
110 type: "function" as const,
111 function: {
112 name: "send_email",
113 description: "Send an email notification",
114 parameters: {
115 type: "object",
116 properties: {
117 to: { type: "string", description: "Email recipient" },
118 subject: { type: "string", description: "Email subject" },
119 body: { type: "string", description: "Email body" },
120 },
121 required: ["to", "subject", "body"],
122 },
123 },
124 execute: async (args: { to: string; subject: string; body: string }) => {
125 console.log(` → Sending email to ${args.to}: "${args.subject}"`);
126 // Simulate email sending
127 return JSON.stringify({
128 success: true,
129 messageId: `msg-${Date.now()}`,
130 });
131 },
132 },
133} as const;
135// Initialize AI with tool registry
136const ai = new AI({
137 adapters: {
138 openai: new OpenAIAdapter({
139 apiKey: process.env.OPENAI_API_KEY || "",
140 }),
141 ollama: new OllamaAdapter({
142 baseURL: "http://localhost:11434",
143 }),
144 },
145 tools, // ← Register all tools here!
146});
148// ============================================================================
149// Example 1: Use specific tools by name (type-safe!)
150// ============================================================================
151async function weatherExample() {
152 console.log("\n=== Weather Example ===\n");
154 const result = await ai.chat({
155 adapter: "openai",
156 model: "gpt-4",
157 messages: [
158 { role: "user", content: "What's the weather in San Francisco and New York?" },
159 ],
160 tools: ["get_weather"], // ← Type-safe! Only registered tool names allowed
161 toolChoice: "auto",
162 maxIterations: 5,
163 });
165 console.log("\nFinal response:", result.content);
166}
168// ============================================================================
169// Example 2: Use multiple tools
170// ============================================================================
171async function calculatorExample() {
172 console.log("\n=== Calculator Example ===\n");
174 const result = await ai.chat({
175 adapter: "openai",
176 model: "gpt-4",
177 messages: [
178 { role: "user", content: "What's 123 * 456? Also tell me the weather in Tokyo." },
179 ],
180 tools: ["calculate", "get_weather"], // ← Multiple tools, type-safe!
181 toolChoice: "auto",
182 maxIterations: 5,
183 });
185 console.log("\nFinal response:", result.content);
186}
188// ============================================================================
189// Example 3: Streaming with tools
190// ============================================================================
191async function streamingWithTools() {
192 console.log("\n=== Streaming with Tools ===\n");
194 const stream = ai.chat({
195 adapter: "openai",
196 model: "gpt-4",
197 messages: [
198 { role: "user", content: "Search for 'guitar' and calculate 299 + 399" },
199 ],
200 tools: ["search_database", "calculate"], // ← Type-safe tool names
201 toolChoice: "auto",
202 maxIterations: 5,
203 as: "stream" as const,
204 });
206 for await (const chunk of stream) {
207 if (chunk.type === "content") {
208 process.stdout.write(chunk.delta);
209 } else if (chunk.type === "tool_call") {
210 console.log(`\n→ Calling tool: ${chunk.toolCall.function.name}`);
211 } else if (chunk.type === "done") {
212 console.log("\n\n✓ Done");
213 }
214 }
215}
217// ============================================================================
218// Example 4: All tools available
219// ============================================================================
220async function allToolsExample() {
221 console.log("\n=== All Tools Example ===\n");
223 const result = await ai.chat({
224 adapter: "openai",
225 model: "gpt-4",
226 messages: [
227 {
228 role: "user",
229 content: "What's the weather in Paris? Calculate 50*20. Search for 'laptop'. Send an email to test@example.com with subject 'Hello'."
230 },
231 ],
232 tools: ["get_weather", "calculate", "search_database", "send_email"], // ← All tools!
233 toolChoice: "auto",
234 maxIterations: 10, // More iterations for multiple tool calls
235 });
237 console.log("\nFinal response:", result.content);
238}
240// ============================================================================
241// Example 5: No tools (regular chat)
242// ============================================================================
243async function noToolsExample() {
244 console.log("\n=== No Tools Example ===\n");
246 const result = await ai.chat({
247 adapter: "openai",
248 model: "gpt-4",
249 messages: [
250 { role: "user", content: "Tell me a short joke about TypeScript" },
251 ],
252 // No tools specified - regular chat
253 });
255 console.log("Response:", result.content);
256}
258// ============================================================================
259// Example 6: Get available tools programmatically
260// ============================================================================
261function listAvailableTools() {
262 console.log("\n=== Available Tools ===\n");
264 const toolNames = ai.toolNames;
265 console.log("Registered tools:", toolNames);
267 toolNames.forEach(name => {
268 const tool = ai.getTool(name);
269 console.log(`\n${name}:`);
270 console.log(` Description: ${tool.function.description}`);
271 console.log(` Has execute: ${!!tool.execute}`);
272 });
273}
275// ============================================================================
276// Example 7: Type safety demonstration
277// ============================================================================
278async function typeSafetyDemo() {
279 console.log("\n=== Type Safety Demo ===\n");
281 // ✅ This works - valid tool names
282 const result1 = await ai.chat({
283 adapter: "openai",
284 model: "gpt-4",
285 messages: [{ role: "user", content: "Test" }],
286 tools: ["get_weather", "calculate"], // TypeScript validates these!
287 });
289 // ❌ This would be a TypeScript error - invalid tool name
290 // const result2 = await ai.chat({
291 // adapter: "openai",
292 // model: "gpt-4",
293 // messages: [{ role: "user", content: "Test" }],
294 // tools: ["invalid_tool"], // TypeScript error!
295 // });
297 console.log("Type safety works! ✓");
298}
300// ============================================================================
301// Run examples
302// ============================================================================
303async function main() {
304 console.log("=".repeat(60));
305 console.log(" TOOL REGISTRY EXAMPLES");
306 console.log("=".repeat(60));
308 try {
309 listAvailableTools();
310 await noToolsExample();
311 await weatherExample();
312 await calculatorExample();
313 await streamingWithTools();
314 await allToolsExample();
315 await typeSafetyDemo();
316 } catch (error: any) {
317 console.error("\n❌ Error:", error.message);
318 }
320 console.log("\n" + "=".repeat(60));
321 console.log(" ALL EXAMPLES COMPLETED");
322 console.log("=".repeat(60) + "\n");
323}
325main();