Skip to main content

Overview

The Agent class provides a higher-level abstraction for building AI agents with persistent state, system prompts, and tool-calling capabilities. It wraps the core generate_text and stream_text functions with a more convenient interface for multi-turn conversations and agent workflows. Each agent has a unique name for identification and logging purposes.

Key Features

  • Named Agents: Each agent has a unique name for identification and logging
  • Persistent State: Maintains system prompts and tool configurations across multiple interactions
  • Tool Integration: Seamlessly works with the tool-calling system
  • Streaming Support: Both synchronous and streaming interfaces
  • Step Monitoring: Optional callback for monitoring agent progress
  • Safety Controls: Configurable maximum steps to prevent infinite loops

Basic Usage

Environment Setup

Make sure you have your API keys set up in a .env file:

Creating an Agent

Running the Agent

Streaming with the Agent

Advanced Configuration

Step Monitoring

Use the on_step callback to monitor the agent’s progress:
You can also use the built-in print_step function from ai_sdk.agent for detailed step monitoring.

Safety Controls

Set maximum steps to prevent infinite tool-calling loops:

Complete Example

Here’s a complete example of a multi-tool agent:

API Reference

Agent Constructor

Methods

run(user_input: str) -> str

Synchronously generate a response to user input.

stream(user_input: str) -> StreamTextResult

Stream a response to user input.

Best Practices

Use descriptive system prompts to define your agent’s personality and capabilities clearly.
Set appropriate max_steps limits to prevent runaway tool-calling loops, especially with complex tool chains.
Use the on_step callback for debugging and monitoring agent behavior in production.
Always validate tool inputs and handle errors gracefully in your tool implementations.

Tool Calling

Learn how to define and use tools with the AI SDK.

Text Generation

Understand the core text generation capabilities.

Streaming

Learn about streaming responses for real-time interactions.

Providers

Explore different language model providers and configurations.