---
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
from collections.abc import AsyncGenerator

import ai


class CustomAgent(ai.Agent):
    async def loop(self, context: ai.Context) -> AsyncGenerator[ai.events.AgentEvent]:
        while context.keep_running():
            async with (
                ai.stream(context=context) as stream,
                ai.ToolRunner() as runner,
                ai.util.merge(stream, runner.events()) as events,
            ):
                async for event in events:
                    yield event
                    if isinstance(event, ai.events.ToolEnd):
                        runner.schedule(self.resolve(event.tool_call))
                context.add(stream.message)
                context.add(runner.get_tool_message())
```

Add the assistant message and the tool results to the context after each
turn. `keep_running()` uses that history to decide whether to call the model
again.

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 functions 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) 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. Omit it for text.
* `params`: optional `ai.InferenceRequestParams`. Defaults to `None`.
* `hook_registry`: optional `ai.agents.hooks.HookRegistry`. Defaults to the
  current registry in a nested run, or a new registry at the top level. Pass
  your own registry to resolve hooks from another task.

## 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`, 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. Read it only after a
  completed run, not when the run is blocked on a hook.
* `stream.hook_registry`: the registry used by this run. Inside the `run`
  context, hook functions use it implicitly. Pass it as `registry=` when
  resolving a hook from another task.
* `stream.blocked`: whether the delivered events show that the run cannot
  proceed until a deferred hook is resolved. It keeps its final value after
  iteration ends.
* `stream.deferred_hooks`: a copy of the unresolved hooks tracked from the
  delivered events. Resolved and cancelled hooks leave this list.

For a request/response flow, call `ai.defer_hook(event.hook)` when you receive
an `ai.events.PendingHookEvent`. This lets iteration end. If `stream.blocked`
is true, persist `stream.messages` and return the pending hook information
instead of reading `stream.output`. On the next request, restore the messages
and register the resolutions before iteration. See
[AI SDK UI approvals](/docs/reference/ai.ui/ai-sdk/approvals) for an example.

## 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 LockstepAgent(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)