/ examples / js / tools / basic-tools.ts
basic-tools.ts
 1  /**
 2   * Basic Tools Example
 3   * Demonstrates tool creation and usage
 4   */
 5  
 6  import { tool, ToolRegistry, getRegistry } from 'praisonai';
 7  
 8  async function main() {
 9    // Create tools
10    const calculator = tool({
11      name: 'calculator',
12      description: 'Perform basic math calculations',
13      parameters: {
14        type: 'object',
15        properties: {
16          expression: { type: 'string', description: 'Math expression to evaluate' }
17        },
18        required: ['expression']
19      },
20      execute: async ({ expression }) => {
21        try {
22          // Only allow safe numeric math characters
23          if (!/^[0-9+\-*/.() ]+$/.test(expression)) {
24            return 'Error: Only basic math expressions are allowed';
25          }
26          // Use Function constructor scoped to math only, no globals
27          const result = new Function(`"use strict"; return (${expression})`)();
28          if (typeof result !== 'number' || !isFinite(result)) {
29            return 'Error: Invalid result';
30          }
31          return `Result: ${result}`;
32        } catch (e) {
33          return 'Error: Invalid expression';
34        }
35      }
36    });
37  
38    const greeter = tool({
39      name: 'greeter',
40      description: 'Generate a greeting',
41      parameters: {
42        type: 'object',
43        properties: {
44          name: { type: 'string', description: 'Name to greet' }
45        },
46        required: ['name']
47      },
48      execute: async ({ name }) => `Hello, ${name}! Welcome to PraisonAI.`
49    });
50  
51    // Create registry and register tools
52    const registry = new ToolRegistry();
53    registry.register(calculator);
54    registry.register(greeter);
55  
56    console.log('Registered tools:', registry.list().map(t => t.name));
57  
58    // Execute tools
59    const calcResult = await calculator.execute({ expression: '10 * 5 + 2' });
60    console.log('\nCalculator:', calcResult);
61  
62    const greetResult = await greeter.execute({ name: 'Developer' });
63    console.log('Greeter:', greetResult);
64  
65    // Get OpenAI format
66    console.log('\nOpenAI tool format:', JSON.stringify(calculator.toOpenAITool(), null, 2));
67  }
68  
69  main().catch(console.error);