Execute Agent

executeAgent

The executeAgent function takes a prepared Agent object, and executes the code inside the runtime environment.

API Reference

executeAgent(options)

Executes an agent with the following options:

Parameters

  • options:
    • agent (Agent, required): The prepared agent object to execute
    • input (object, optional): Input for the agent if needed
    • ticks (number, optional): Maximum amount of ticks to run in a single execution cycle, defaults to infinity
    • timeout (number | Date, optional): Time until the execution times out, could be milliseconds from now, or a Date
    • until (function, optional): Callback to check if the agent has to stop execution, has higher priority than timeout

Returns

Returns a Promise that resolves with execution results:

  • ticks: The number of ticks that the agent was executed (one tick is one async call)
  • done: Boolean, that indicates if the agent has finished execution or not

Example

import { AnthropicModel } from 'agentscript-ai/anthropic';
import { defineTool, inferAgent, executeAgent } from 'agentscript-ai/core';
import * as s from 'agentscript-ai/schema';
 
const add = defineTool({
    name: 'add',
    description: 'Add two numbers.',
    input: {
        a: s.number(),
        b: s.number(),
    },
    output: s.number(),
    handler: ({input}) => input.a + input.b
});
 
const llm = AnthropicModel({
    model: 'claude-3-5-sonnet-latest',
    apiKey: process.env.ANTHROPIC_API_KEY,
});
 
const tools = { add };
const prompt = 'Add numbers 1 and 2';
const output = s.number();
 
const agent = await inferAgent({
    tools,
    output,
    llm,
    prompt
});
 
const result = await executeAgent({ agent, ticks: 2 });
console.log(agent.state?.output) // 3