---
title: Agent
description: Run the default agent loop with tools.
type: reference
summary: Reference for ai.Agent.
---

# Agent



`Agent` streams model output, dispatches Python tools, appends tool results to
history, and repeats until the model returns a final assistant message.

```python
agent = ai.Agent(tools=[...])
agent.tools
```

`agent.tools` returns a copy of registered executable tools.

## run

```python
async with agent.run(
    model,
    messages,
    output_type=None,
    params=None,
) as stream:
    async for event in stream:
        ...
```

Arguments:

* `model`: `ai.Model`.
* `messages`: initial list of `ai.messages.Message`.
* `output_type`: optional Pydantic model for final JSON output.
* `params`: optional `ai.InferenceRequestParams`.

## AgentStream

`Agent.run` yields an `AgentStream`. Read the final output after iteration.

```python
stream.context
stream.messages
stream.output
```

* `stream.context`: the run's `ai.Context`, i.e. the live per-run state (model,
  messages, tools, params).
* `stream.messages`: the message history, including messages added during the
  run. Shorthand for `stream.context.messages`.
* `stream.output`: the run's result. By default, the final assistant message's
  text. When `output_type` is set, the text is validated as JSON against that
  Pydantic model and the parsed instance is returned.

## loop

Override `Agent.loop(context)` to customize control flow. The default loop uses
`ai.stream`, `ToolRunner`, `Context.resolve`, and `Context.add`.

```python
class CustomAgent(ai.Agent):
    async def loop(self, context: ai.Context):
        while context.keep_running():
            ...
```

When persisting a run (for durability or serverless execution), save and
restore the message history only. Everything else the loop touches, e.g. streams,
tool runners, hook futures, provider clients, is runtime state that is
recreated on every run and cannot be serialized.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)