# Running Agents (/agents/running-agents)



Run your Agent by calling `Agent.run()` or `Agent.arun()`. The execution flow:

1. The agent builds context to send to the model (system message, user message, chat history, user memories, session state, and other relevant inputs).
2. The agent sends this context to the model.
3. The model responds with either a message or a tool call.
4. If the model makes a tool call, the agent executes it and returns results to the model.
5. The model processes the updated context, repeating this loop until it produces a final message without tool calls.
6. The agent returns the run result to the caller.

Tools, history, memory, and other context sources are included when configured. A run can also pause for human review, be cancelled, stop through a tool’s control flag, or fail before a final answer. Inspect the run status or terminal event when the outcome matters.

## Before you run [#before-you-run]

Create and activate a Python virtual environment, install `agno` and `anthropic`, and export `ANTHROPIC_API_KEY` before running the Claude examples:

```bash
uv pip install -U agno anthropic
export ANTHROPIC_API_KEY="your-anthropic-api-key"
```

On Windows PowerShell, use `$Env:ANTHROPIC_API_KEY="your-anthropic-api-key"`. The structured-output example additionally requires the `openai` package and `OPENAI_API_KEY`. Short fragments below extend the preceding complete example.

## Basic Execution [#basic-execution]

`Agent.run()` returns a `RunOutput` object, or a stream of `RunOutputEvent` objects when `stream=True`:

```python
from agno.agent import Agent, RunOutput
from agno.models.anthropic import Claude
from agno.tools.hackernews import HackerNewsTools
from agno.utils.pprint import pprint_run_response

agent = Agent(
    model=Claude(id="claude-sonnet-4-5"),
    tools=[HackerNewsTools()],
    instructions="Write a report on the topic. Output only the report.",
    markdown=True,
)

# Run agent and return the response as a variable
response: RunOutput = agent.run("Trending startups and products.")

# Print the response in markdown format
pprint_run_response(response, markdown=True)
```

<Tip>
  Run the agent asynchronously using `Agent.arun()`. See this [example](/examples/agents/advanced/concurrent-execution).
</Tip>

## Run Input [#run-input]

The `input` parameter can be a string, list, dictionary, message, Pydantic model, or list of messages:

```python
from agno.agent import Agent, RunOutput
from agno.models.anthropic import Claude
from agno.tools.hackernews import HackerNewsTools
from agno.utils.pprint import pprint_run_response

agent = Agent(
    model=Claude(id="claude-sonnet-4-5"),
    tools=[HackerNewsTools()],
    instructions="Write a report on the topic. Output only the report.",
    markdown=True,
)

# Run agent with input="Trending startups and products."
response: RunOutput = agent.run(input="Trending startups and products.")
# Print the response in markdown format
pprint_run_response(response, markdown=True)
```

<Tip>
  See [Input & Output](/input-output/overview) for structured input and output.
</Tip>

## Run Output [#run-output]

`Agent.run()` returns a `RunOutput` object when not streaming. Core attributes:

* `run_id`: The ID of the run.
* `agent_id`: The ID of the agent.
* `agent_name`: The name of the agent.
* `session_id`: The ID of the session.
* `user_id`: The ID of the user.
* `content`: The response content.
* `content_type`: The type of content. For structured output, this is the class name of the Pydantic model.
* `reasoning_content`: The reasoning content.
* `messages`: Retained messages for the run, including model replies and tool interactions.
* `metrics`: The metrics of the run. See [Metrics](/sessions/metrics/overview).
* `model`: The model used for the run.

See [RunOutput reference](/reference/agents/run-response) for full documentation.

## Streaming [#streaming]

Set `stream=True` to return an iterator of `RunOutputEvent` objects:

```python
from typing import Iterator
from agno.agent import Agent, RunOutputEvent, RunEvent
from agno.models.anthropic import Claude
from agno.tools.hackernews import HackerNewsTools

agent = Agent(
    model=Claude(id="claude-sonnet-4-5"),
    tools=[HackerNewsTools()],
    instructions="Write a report on the topic. Output only the report.",
    markdown=True,
)

# Run agent and return the response as a stream
stream: Iterator[RunOutputEvent] = agent.run("Trending products", stream=True)
for chunk in stream:
    if chunk.event == RunEvent.run_content:
        print(chunk.content)
```

<Tip>
  For asynchronous streaming, see this [example](/examples/agents/advanced/basic-agent-events).
</Tip>

## Streaming Events [#streaming-events]

With `stream_events=False`, normal output streams contain content events. A pause, cancellation, or error can still emit its control or error event; do not assume every item contains text.

To stream all events (tool calls, reasoning, memory updates, etc.), set `stream_events=True`:

```python
response_stream: Iterator[RunOutputEvent] = agent.run(
    "Trending products",
    stream=True,
    stream_events=True
)
```

## Handling Events [#handling-events]

Process events as they arrive:

```python
from agno.agent import Agent, RunEvent
from agno.models.anthropic import Claude
from agno.tools.hackernews import HackerNewsTools

agent = Agent(
    model=Claude(id="claude-sonnet-4-5"),
    tools=[HackerNewsTools()],
    instructions="Write a report on the topic. Output only the report.",
    markdown=True,
)

stream = agent.run("Trending products", stream=True, stream_events=True)

for chunk in stream:
    if chunk.event == RunEvent.run_content:
        print(f"Content: {chunk.content}")
    elif chunk.event == RunEvent.tool_call_started:
        print(f"Tool call started: {chunk.tool.tool_name}")
    elif chunk.event == RunEvent.reasoning_step:
        print(f"Reasoning step: {chunk.reasoning_content}")
```

<Check>
  Run events expose each step of the run as it happens. Use them for live UI updates and debugging.
</Check>

## Event Types [#event-types]

Events yielded by `Agent.run()` and `Agent.arun()`, depending on agent configuration:

### Core Events [#core-events]

| Event Type               | Description                                                                                                                                     |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `RunStarted`             | Indicates the start of a run                                                                                                                    |
| `RunContent`             | Contains the model's response text as individual chunks                                                                                         |
| `RunContentCompleted`    | Signals completion of content streaming                                                                                                         |
| `RunIntermediateContent` | Contains the model's intermediate response text as individual chunks. Used when `output_model` is set.                                          |
| `RunCompleted`           | Terminal completion event. Cancellation also emits it after `RunCancelled`; check status and cancellation events before treating it as success. |
| `RunError`               | Indicates an error occurred during the run                                                                                                      |
| `RunCancelled`           | Signals that the run was cancelled                                                                                                              |

### Control Flow Events [#control-flow-events]

| Event Type     | Description                                  |
| -------------- | -------------------------------------------- |
| `RunPaused`    | Indicates the run has been paused            |
| `RunContinued` | Signals that a paused run has been continued |

### Tool Events [#tool-events]

| Event Type          | Description                                                    |
| ------------------- | -------------------------------------------------------------- |
| `ToolCallStarted`   | Indicates the start of a tool call                             |
| `ToolCallCompleted` | Signals completion of a tool call, including tool call results |
| `ToolCallError`     | Indicates a tool call failed, including the error              |

### Reasoning Events [#reasoning-events]

| Event Type              | Description                                          |
| ----------------------- | ---------------------------------------------------- |
| `ReasoningStarted`      | Indicates the start of the agent's reasoning process |
| `ReasoningStep`         | Contains a single step in the reasoning process      |
| `ReasoningContentDelta` | Contains a chunk of streamed reasoning content       |
| `ReasoningCompleted`    | Signals completion of the reasoning process          |

### Memory Events [#memory-events]

| Event Type              | Description                                     |
| ----------------------- | ----------------------------------------------- |
| `MemoryUpdateStarted`   | Indicates that the agent is updating its memory |
| `MemoryUpdateCompleted` | Signals completion of a memory update           |

### Session Summary Events [#session-summary-events]

| Event Type                | Description                                       |
| ------------------------- | ------------------------------------------------- |
| `SessionSummaryStarted`   | Indicates the start of session summary generation |
| `SessionSummaryCompleted` | Signals completion of session summary generation  |

### Pre-Hook Events [#pre-hook-events]

| Event Type         | Description                                    |
| ------------------ | ---------------------------------------------- |
| `PreHookStarted`   | Indicates the start of a pre-run hook          |
| `PreHookCompleted` | Signals completion of a pre-run hook execution |

### Post-Hook Events [#post-hook-events]

| Event Type          | Description                                     |
| ------------------- | ----------------------------------------------- |
| `PostHookStarted`   | Indicates the start of a post-run hook          |
| `PostHookCompleted` | Signals completion of a post-run hook execution |

### Parser Model Events [#parser-model-events]

| Event Type                     | Description                                      |
| ------------------------------ | ------------------------------------------------ |
| `ParserModelResponseStarted`   | Indicates the start of the parser model response |
| `ParserModelResponseCompleted` | Signals completion of the parser model response  |

### Output Model Events [#output-model-events]

| Event Type                     | Description                                      |
| ------------------------------ | ------------------------------------------------ |
| `OutputModelResponseStarted`   | Indicates the start of the output model response |
| `OutputModelResponseCompleted` | Signals completion of the output model response  |

### Model Request Events [#model-request-events]

| Event Type              | Description                                                    |
| ----------------------- | -------------------------------------------------------------- |
| `ModelRequestStarted`   | Indicates the start of a model request                         |
| `ModelRequestCompleted` | Signals completion of a model request, including token metrics |

### Compression Events [#compression-events]

| Event Type             | Description                                    |
| ---------------------- | ---------------------------------------------- |
| `CompressionStarted`   | Indicates the start of tool result compression |
| `CompressionCompleted` | Signals completion of tool result compression  |

### Followup Events [#followup-events]

| Event Type           | Description                                                          |
| -------------------- | -------------------------------------------------------------------- |
| `FollowupsStarted`   | Indicates the start of followup suggestion generation                |
| `FollowupsCompleted` | Signals completion of followup generation, including the suggestions |

### Custom Events [#custom-events]

Create custom events by extending `CustomEvent`:

```python
from dataclasses import dataclass
from agno.run.agent import CustomEvent
from typing import Optional

@dataclass
class CustomerProfileEvent(CustomEvent):
    """CustomEvent for customer profile."""

    customer_name: Optional[str] = None
    customer_email: Optional[str] = None
    customer_phone: Optional[str] = None
```

Yield custom events from your tool:

```python
from agno.tools import tool

@tool()
async def get_customer_profile():
    """Example custom tool that simply yields a custom event."""

    yield CustomerProfileEvent(
        customer_name="John Doe",
        customer_email="john.doe@example.com",
        customer_phone="1234567890",
    )
```

## Specify Run User and Session [#specify-run-user-and-session]

Pass `user_id` and `session_id` to associate a run with a specific user and session:

```python
agent.run("Tell me a 5 second short story about a robot", user_id="john@example.com", session_id="session_123")
```

See [Agent Sessions](/sessions/overview) for more details.

## Passing Images / Audio / Video / Files [#passing-images--audio--video--files]

Pass media via `images`, `audio`, `videos`, or `files` parameters:

```python
from agno.media import Image

agent.run("Tell me a 5 second short story about this image", images=[Image(url="https://example.com/image.jpg")])
```

See [Multimodal Agents](/multimodal/overview) for more details.

## Passing Output Schema [#passing-output-schema]

Pass an output schema for structured output:

```python
from pydantic import BaseModel
from agno.agent import Agent
from agno.models.openai import OpenAIResponses

class TVShow(BaseModel):
    title: str
    episodes: int

agent = Agent(model=OpenAIResponses(id="gpt-5.2"))
agent.run("Create a TV show", output_schema=TVShow)
```

See [Input & Output](/input-output/overview) for more details.

## Pausing and Continuing a Run [#pausing-and-continuing-a-run]

An agent run can be paused for human-in-the-loop flows. Continue execution with `Agent.continue_run()`.

See [Human-in-the-Loop](/hitl/overview) for more details.

## Cancelling a Run [#cancelling-a-run]

Cancel a run with `Agent.cancel_run()`.

See [Cancelling a Run](/run-cancellation/overview) for more details.

## Background Execution [#background-execution]

Background execution requires a configured database. With `Agent.arun(background=True)`, the run continues in a task in the current process when the client disconnects. That task does not survive process termination by itself.

AgentOS exposes polling and resumable SSE endpoints for background runs; `stream=True` enables background streaming. Configure the [durable queue](/agent-os/background-execution/durable-queue) when accepted jobs must be reclaimed after a process restart.

See [Background Execution](/background-execution/overview) for polling, resumable streaming, and the `/resume` endpoint.

## Developer Resources [#developer-resources]

* [Agent reference](/reference/agents/agent)
* [RunOutput schema](/reference/agents/run-response)
