Building Agents
The ToolLoopAgent provides a structured way to encapsulate LLM configuration, tools, and behavior into reusable components. It handles the agent loop for you, allowing the LLM to call tools multiple times in sequence to accomplish complex tasks. Define agents once and use them across your application.Why Use the ToolLoopAgent Class?
When building AI applications, you often need to:- Reuse configurations - Same model settings, tools, and prompts across different parts of your application
- Maintain consistency - Ensure the same behavior and capabilities throughout your codebase
- Simplify API routes - Reduce boilerplate in your endpoints
- Type safety - Get full TypeScript support for your agent’s tools and outputs
Creating an Agent
Define an agent by instantiating the ToolLoopAgent class with your desired configuration:Configuration Options
The ToolLoopAgent accepts all the same settings asgenerateText and streamText. Configure:
Model and System Instructions
Tools
Provide tools that the agent can use to accomplish tasks:Loop Control
By default, agents run for 20 steps (stopWhen: stepCountIs(20)). In each step, the model either generates text or calls a tool. If it generates text, the agent completes. If it calls a tool, the AI SDK executes that tool.
To let agents call multiple tools in sequence, configure stopWhen to allow more steps. After each tool execution, the agent triggers a new generation where the model can call another tool or generate text:
- A finish reasoning other than tool-calls is returned, or
- A tool that is invoked does not have an execute function, or
- A tool call needs approval, or
- A stop condition is met
Tool Choice
Control how the agent uses tools:Structured Output
Define structured output schemas:Define Agent Behavior with System Instructions
System instructions define your agent’s behavior, personality, and constraints. They set the context for all interactions and guide how the agent responds to user queries and uses tools.Basic System Instructions
Set the agent’s role and expertise:Detailed Behavioral Instructions
Provide specific guidelines for agent behavior:Constrain Agent Behavior
Set boundaries and ensure consistent behavior:Tool Usage Instructions
Guide how the agent should use available tools:Format and Style Instructions
Control the output format and communication style:Using an Agent
Once defined, you can use your agent in three ways:Generate Text
Usegenerate() for one-time text generation:
Stream Text
Usestream() for streaming responses:
Respond to UI Messages
UsecreateAgentUIStreamResponse() to create API responses for client applications:
Lifecycle Callbacks
Experimental callbacks are subject to breaking changes in incremental package
releases.
experimental_onStart: Called once when the agent operation begins, before any LLM calls. Receives model info, prompt, settings, and telemetry metadata.experimental_onStepStart: Called before each step (LLM call). Receives the step number, model, messages being sent, tools, and prior steps.experimental_onToolCallStart: Called right before a tool’sexecutefunction runs. Receives the tool call object with tool name, call ID, and input.experimental_onToolCallFinish: Called right after a tool’sexecutefunction completes or errors. Receives the tool call,durationMs, and asuccessdiscriminator (outputwhen successful,errorwhen failed).onStepFinish: Called after each step finishes. Receives step results including usage, finish reason, and tool calls.onFinish: Called when all steps are finished and the response is complete. Receives all step results, total usage, and telemetry metadata.
Constructor vs. Method Callbacks
All lifecycle callbacks can be defined in the constructor for agent-wide tracking, in thegenerate()/stream() call for per-call tracking, or both. When both are provided, both are called (constructor first, then the method callback):
End-to-end Type Safety
You can infer types for your agent’sUIMessages:
useChat:
Next Steps
Now that you understand building agents, you can:- Explore workflow patterns for structured patterns using core functions
- Learn about loop control for advanced execution control
- See manual loop examples for custom workflow implementations