Error Handling
AgentScript provides mechanisms for handling errors that may occur during agent execution.
RuntimeError
The RuntimeError
is a custom error class that is thrown by the AgentScript runtime when an error occurs during code execution. This can happen due to:
- Invalid function calls
- Accessing undefined variables
- Type mismatches
- Other runtime issues
Handling Errors in Tools
You can handle errors within your tool's handler
function using standard JavaScript try...catch
blocks.
import { defineTool } from 'agentscript-ai/core';
import * as s from 'agentscript-ai/schema';
const myTool = defineTool({
name: 'myTool',
description: 'A tool that might throw an error.',
input: {
shouldError: s.boolean(),
},
output: s.void(),
handler: async ({ input }) => {
try {
if (input.shouldError) {
throw new Error('This is a test error.');
}
console.log('Tool executed successfully.');
} catch (error) {
console.error('Error in myTool:', error);
throw error; // Re-throw the error to stop the agent execution
}
},
});
In this example, if shouldError
is true, the tool will throw an error. The catch block logs the error and then re-throws it, which will stop the agent execution.
Handling Errors in executeAgent
The executeAgent
function will throw an error if the agent fails to complete its task. You can catch this error using a try...catch block:
import { AnthropicModel } from 'agentscript-ai/anthropic';
import { defineTool, inferAgent, executeAgent, RuntimeError } from 'agentscript-ai/core';
import * as s from 'agentscript-ai/schema';
const myTool = defineTool({
name: 'myTool',
description: 'A tool that might throw an error.',
input: {
shouldError: s.boolean(),
},
output: s.void(),
handler: async ({ input }) => {
if (input.shouldError) {
throw new Error('This is a test error.');
}
console.log('Tool executed successfully.');
},
});
const llm = AnthropicModel({
model: 'claude-3-5-sonnet-latest',
apiKey: process.env.ANTHROPIC_API_KEY,
});
const tools = {
myTool,
};
const prompt = 'Call myTool with shouldError set to true';
const output = s.void();
async function main() {
try {
const agent = await inferAgent({
tools,
output,
llm,
prompt,
});
await executeAgent({ agent });
} catch (error) {
if (error instanceof RuntimeError) {
console.error('Agent execution failed:', error.message);
} else {
console.error('An unexpected error occurred:', error);
}
}
}
main();
Key Points
- RuntimeError: Catch this error to handle issues during agent execution
- try...catch: Use try...catch blocks in your tool handlers to handle errors gracefully
- Re-throwing Errors: Re-throw errors in your tool handlers to stop the agent execution when necessary