---
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.

## resolve

`Agent.resolve` converts model tool-call parts into executable `ToolCall`
objects. Use it when implementing a custom `Agent.loop`:

```python
class CustomAgent(ai.Agent):
    async def loop(self, context: ai.Context):
        while context.keep_running():
            async with ai.stream(context=context) as stream:
                async for event in stream:
                    yield event
                    if isinstance(event, ai.events.ToolEnd):
                        tool_call = self.resolve(event.tool_call)
                        await tool_call()
```

Resolution performs tool-name lookup and argument validation, and applies
approval gates and cached replay results. Pass a sequence of tool-call parts
to resolve to get a list of executable calls.

## Current execution context

Use these functions when code called by an agent needs information about its
active run or tool call:

```python
class MyAgent(ai.Agent):
    pass


@ai.tool
async def inspect_context() -> str:
    agent = ai.current_agent(type=MyAgent)
    tool_call = ai.current_tool_call()
    return f"{type(agent).__name__}: {tool_call.id}"
```

### current\_agent

`ai.current_agent()` returns the agent whose stream is executing in the current
context. Calling it outside an agent stream raises `LookupError`. Pass an
optional `type=MyAgent` argument to validate the agent at runtime and return
`MyAgent` to type checkers.

### current\_tool\_call

`ai.current_tool_call()` returns the `ToolCall` executing in the current
context. It is available to the tool and code called by the tool. Calling it
outside tool execution raises `LookupError`.

Both methods use task-local context, so concurrent agent runs and tool calls do
not share their current values.

## 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`, `Agent.resolve`, and `Context.add`.

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

`LOOP_BUFFER` is a class variable that sets how many events `loop` may run
ahead of the consumer of `run`. `None` (the default) is unbounded, so the loop
keeps going while the consumer is between reads. `0` runs the loop in lockstep
with the consumer, which loops that sequence side effects against consumer
code depend on.

```python
class DurableAgent(ai.Agent):
    LOOP_BUFFER = 0
```

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)