Simple Tools Example
This example demonstrates how to define and use simple tools within AgentScript.
Overview
This example showcases:
- Defining basic math tools (
add
,multiply
,divide
,square
,squareRoot
) - A basic agent that uses these tools to perform calculations
- A complete agent workflow, from code generation to execution
Setup
- Install dependencies:
yarn
- Create
.env
file:
ANTHROPIC_API_KEY=your-anthropic-api-key
- Run the example:
yarn start
Implementation
import chalk from 'chalk';
import { defineTool, executeAgent, inferAgent } from 'agentscript-ai';
import { AnthropicModel } from 'agentscript-ai/anthropic';
import * as s from 'agentscript-ai/schema';
// Define tools
const add = defineTool({
description: 'Add two numbers',
input: {
a: s.number(),
b: s.number(),
},
output: s.number(),
handler: ({ input }) => input.a + input.b,
});
const multiply = defineTool({
description: 'Multiply two numbers',
input: {
a: s.number(),
b: s.number(),
},
output: s.number(),
handler: ({ input }) => input.a * input.b,
});
const divide = defineTool({
description: 'Divide two numbers',
input: {
a: s.number(),
b: s.number(),
},
output: s.number(),
handler: ({ input }) => input.a / input.b,
});
const square = defineTool({
description: 'Square a number',
input: {
a: s.number(),
},
output: s.number(),
handler: ({ input }) => input.a * input.a,
});
const squareRoot = defineTool({
description: 'Square root of a number',
input: {
a: s.number(),
},
output: s.number(),
handler: ({ input }) => Math.sqrt(input.a),
});
// Configure the language model
const llm = AnthropicModel({
model: 'claude-3-5-sonnet-latest',
apiKey: process.env.ANTHROPIC_API_KEY,
maxTokens: 1024,
});
const tools = {
add,
multiply,
divide,
square,
squareRoot,
};
// Define a task for the agent
const prompt = 'Calculate the square root of eight times two';
// Define the expected output
const output = s.number();
// Let the LLM infer the agent based on the prompt and runtime
const agent = await inferAgent({
llm,
tools,
output,
prompt,
});
// Execute the agent
await executeAgent({ agent });
// Log the results
console.log(chalk.green('Agent output:'));
console.log(agent.output);
Key Features
- Tool Definition: Shows how to define simple mathematical tools
- Tool Composition: Demonstrates combining tools for complex calculations
- Code Generation: Highlights AgentScript's ability to generate mathematical operations
- Type Safety: Shows proper type definitions for inputs and outputs
- Error Handling: Demonstrates best practices for mathematical operations