Tool State
Tools in AgentScript can maintain internal state between calls, allowing you to implement more complex workflows.
How Tool State Works
When you define a tool using defineTool
, you can specify a state
property with a schema for your tool's state. This will give the tool access to a special state
property, available as a part of the context.
import { defineTool } from 'agentscript-ai/core';
import * as s from 'agentscript-ai/schema';
const counterTool = defineTool({
name: 'counterTool',
description: 'A tool that counts the calls.',
input: {
message: s.string(),
},
state: s.object({
props: {
count: s.number(),
},
}),
handler: ({ input, state }) => {
if (!state.count) {
state.count = 0;
}
console.log(`Tool called with message: ${input.message}, count: ${state.count}`);
state.count++;
},
});
In this example, the counterTool maintains a count variable in its state. Each time the tool is called, the handler function increments the count.
Important Considerations
-
State Scope: Tool state is local to each tool call within a specific agent execution. It is not shared between different agent executions or different calls of the same tool in different agents.
-
Schema Definition: Always define a schema for your tool's state. This ensures type safety and helps the LLM understand the structure of the state.
-
Serialization: Tool state is serialized along with the agent's state, allowing you to resume execution later.
-
Initial State: If the state is not initialized, it will receive a default value based on the schema passed in.