AI SDK Agents
Build autonomous agents with ToolLoopAgent: reusable model + tools + loop control.
Quick Start
Assume Zod v4.3.5 for schema typing.
import { ToolLoopAgent, tool } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';
import { z } from 'zod';
const weatherAgent = new ToolLoopAgent({
model: anthropic('claude-sonnet-4-20250514'),
tools: {
weather: tool({
description: 'Get the weather in a location (F)',
inputSchema: z.object({ location: z.string() }),
execute: async ({ location }) => ({ location, temperature: 72 }),
}),
},
});
const result = await weatherAgent.generate({
prompt: 'What is the weather in San Francisco?',
});
When to Use ToolLoopAgent vs Core Functions
- Use ToolLoopAgent for dynamic, multi-step tasks where the model decides which tools to call.
- Use generateText/streamText for deterministic flows or strict ordering.
Essential Patterns
Structured Output
import { ToolLoopAgent, Output } from 'ai';
import { z } from 'zod';
const analysisAgent = new ToolLoopAgent({
model: 'openai/gpt-4o',
output: Output.object({
schema: z.object({
sentiment: z.enum(['positive', 'neutral', 'negative']),
summary: z.string(),
}),
}),
});
Streaming Agent
const stream = myAgent.stream({ prompt: 'Summarize this report' });
for await (const chunk of stream.textStream) {
process.stdout.write(chunk);
}
API Route
import { createAgentUIStreamResponse } from 'ai';
export async function POST(request: Request) {
const { messages } = await request.json();
return createAgentUIStreamResponse({ agent: myAgent, messages });
}
Type-Safe Client Integration
import { ToolLoopAgent, InferAgentUIMessage } from 'ai';
const myAgent = new ToolLoopAgent({ model, tools });
export type MyAgentUIMessage = InferAgentUIMessage<typeof myAgent>;
Loop Control Checklist
- Set
stopWhen (default: stepCountIs(20)) for safety.
- Use
hasToolCall('finalAnswer') to stop on terminal actions.
- Use
prepareStep to swap models, compress messages, or limit tools per step.
Runtime Configuration
- Use
callOptionsSchema to define type-safe runtime options.
- Use
prepareCall to select model/tools or inject RAG context once per call.
- Use
prepareStep for per-step decisions (budget limits, dynamic tools).
Reference Files
| Reference |
When to Use |
references/fundamentals.md |
ToolLoopAgent basics, Output types, streaming |
references/loop-control.md |
stopWhen, hasToolCall, prepareStep patterns |
references/configuration.md |
callOptionsSchema, prepareCall vs prepareStep |
references/workflow-patterns.md |
multi-agent workflows and routing |
references/real-world.md |
RAG, multimodal, file processing |
references/production.md |
monitoring, safety, cost control |
references/migration.md |
v6 migration notes |
1---2name: ai-sdk-agents3description: Expert guidance for building AI agents with ToolLoopAgent (AI SDK v6+). Use when creating agents, configuring stopWhen/prepareStep, callOptionsSchema/prepareCall, dynamic tool selection, tool loops, or agent workflows (sequential, routing, evaluator-optimizer, orchestrator-worker). Triggers: ToolLoopAgent, agent loop, stopWhen, stepCountIs, prepareStep, callOptionsSchema, prepareCall, hasToolCall, InferAgentUIMessage, agent workflows.4---56# AI SDK Agents78Build autonomous agents with ToolLoopAgent: reusable model + tools + loop control.910## Quick Start1112Assume Zod v4.3.5 for schema typing.1314```ts15import { ToolLoopAgent, tool } from 'ai';16import { anthropic } from '@ai-sdk/anthropic';17import { z } from 'zod';1819const weatherAgent = new ToolLoopAgent({20 model: anthropic('claude-sonnet-4-20250514'),21 tools: {22 weather: tool({23 description: 'Get the weather in a location (F)',24 inputSchema: z.object({ location: z.string() }),25 execute: async ({ location }) => ({ location, temperature: 72 }),26 }),27 },28});2930const result = await weatherAgent.generate({31 prompt: 'What is the weather in San Francisco?',32});33```3435## When to Use ToolLoopAgent vs Core Functions3637- Use **ToolLoopAgent** for dynamic, multi-step tasks where the model decides which tools to call.38- Use **generateText/streamText** for deterministic flows or strict ordering.3940## Essential Patterns4142### Structured Output4344```ts45import { ToolLoopAgent, Output } from 'ai';46import { z } from 'zod';4748const analysisAgent = new ToolLoopAgent({49 model: 'openai/gpt-4o',50 output: Output.object({51 schema: z.object({52 sentiment: z.enum(['positive', 'neutral', 'negative']),53 summary: z.string(),54 }),55 }),56});57```5859### Streaming Agent6061```ts62const stream = myAgent.stream({ prompt: 'Summarize this report' });63for await (const chunk of stream.textStream) {64 process.stdout.write(chunk);65}66```6768### API Route6970```ts71import { createAgentUIStreamResponse } from 'ai';7273export async function POST(request: Request) {74 const { messages } = await request.json();75 return createAgentUIStreamResponse({ agent: myAgent, messages });76}77```7879### Type-Safe Client Integration8081```ts82import { ToolLoopAgent, InferAgentUIMessage } from 'ai';8384const myAgent = new ToolLoopAgent({ model, tools });85export type MyAgentUIMessage = InferAgentUIMessage<typeof myAgent>;86```8788## Loop Control Checklist8990- Set `stopWhen` (default: `stepCountIs(20)`) for safety.91- Use `hasToolCall('finalAnswer')` to stop on terminal actions.92- Use `prepareStep` to swap models, compress messages, or limit tools per step.9394## Runtime Configuration9596- Use `callOptionsSchema` to define type-safe runtime options.97- Use `prepareCall` to select model/tools or inject RAG context once per call.98- Use `prepareStep` for per-step decisions (budget limits, dynamic tools).99100## Reference Files101102| Reference | When to Use |103|-----------|-------------|104| `references/fundamentals.md` | ToolLoopAgent basics, Output types, streaming |105| `references/loop-control.md` | stopWhen, hasToolCall, prepareStep patterns |106| `references/configuration.md` | callOptionsSchema, prepareCall vs prepareStep |107| `references/workflow-patterns.md` | multi-agent workflows and routing |108| `references/real-world.md` | RAG, multimodal, file processing |109| `references/production.md` | monitoring, safety, cost control |110| `references/migration.md` | v6 migration notes |