Asynchronous

Asynchronous Operations

AgentScript handles asynchronous operations gracefully, allowing you to build agents that interact with external APIs, perform long-running tasks, and more.

How Asynchronous Operations Work

  • async Handlers: Tool handler functions can be asynchronous (return a Promise)
  • executeAgent and Ticks: The executeAgent function executes the agent code step by step. Each asynchronous operation (like a tool call) is considered a "tick"
  • ticks Option: You can control how many ticks the agent executes in a single call to executeAgent using the ticks option
  • Resumability: If an agent is paused due to an asynchronous operation, you can resume it later by calling executeAgent again with the same agent object

Example

import { AnthropicModel } from 'agentscript-ai/anthropic';
import { defineTool, inferAgent, executeAgent } from 'agentscript-ai/core';
import * as s from 'agentscript-ai/schema';
 
const delayTool = defineTool({
    name: 'delayTool',
    description: 'A tool that delays execution for a specified time.',
    input: {
        delay: s.number({ description: 'Delay in milliseconds' }),
    },
    output: s.void(),
    handler: async ({ input }) => {
        console.log(`Delaying for ${input.delay}ms`);
        await new Promise(resolve => setTimeout(resolve, input.delay));
        console.log('Delay complete');
    },
});
 
const llm = AnthropicModel({
    model: 'claude-3-5-sonnet-latest',
    apiKey: process.env.ANTHROPIC_API_KEY,
});
 
const tools = {
    delayTool,
};
 
const prompt = 'Delay for 1000ms';
const output = s.void();
 
async function main() {
    const agent = await inferAgent({
        tools,
        output,
        llm,
        prompt,
    });
 
    let result = await executeAgent({ agent, ticks: 1 });
    console.log('First execution:', result);
 
    result = await executeAgent({ agent, ticks: 1 });
    console.log('Second execution:', result);
}
 
main();

In this example:

  • The delayTool uses setTimeout to simulate an asynchronous operation
  • The first call to executeAgent executes the delayTool and pauses
  • The second call to executeAgent resumes the execution and completes the agent

Key Points

  • async: Use async keyword for tool handlers that perform asynchronous operations
  • ticks: Control the number of asynchronous operations that are executed in a single call to executeAgent
  • Resumability: AgentScript automatically handles pausing and resuming asynchronous operations