> ## Documentation Index
> Fetch the complete documentation index at: https://docs.definable.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Running Agents

> Execute agents synchronously, asynchronously, or with streaming.

Agents support four execution modes. Choose based on your application's needs.

## Synchronous

The simplest way to run an agent. Blocks until the full response is ready.

```python theme={null}
from definable.agent import Agent
from definable.model import OpenAIChat

agent = Agent(
    model=OpenAIChat(id="gpt-4o"),
    instructions="You are a helpful assistant.",
)

output = agent.run("What is the capital of France?")
print(output.content)  # "The capital of France is Paris."
```

## Asynchronous

Use `arun()` in async contexts such as web servers or async pipelines:

```python theme={null}
output = await agent.arun("What is the capital of France?")
print(output.content)
```

## Streaming (Sync)

Stream events in real time. Each event represents a step in the agent's execution:

```python theme={null}
for event in agent.run_stream("Write a short story about a robot."):
    if event.event == "RunContent":
        print(event.content, end="", flush=True)
    elif event.event == "ToolCallStarted":
        print(f"\n→ Calling {event.tool.tool_name}...")
    elif event.event == "ToolCallCompleted":
        print(f"  Done: {event.content[:100]}")
    elif event.event == "RunCompleted":
        print(f"\n\nTokens used: {event.metrics.total_tokens}")
```

## Streaming (Async)

```python theme={null}
async for event in agent.arun_stream("Write a short story about a robot."):
    if event.event == "RunContent":
        print(event.content, end="", flush=True)
```

## Run Parameters

All four methods accept the same parameters:

<ParamField path="instruction" type="str" required>
  The user's message or instruction to the agent.
</ParamField>

<ParamField path="messages" type="List[Message]">
  Existing conversation history. The instruction is appended as the latest user message.
</ParamField>

<ParamField path="session_id" type="str">
  Session identifier for grouping related runs together.
</ParamField>

<ParamField path="run_id" type="str">
  Unique identifier for this run. Auto-generated if not provided.
</ParamField>

<ParamField path="user_id" type="str">
  User identifier for memory scoping. When set, memory recall and storage are scoped to this user.
</ParamField>

<ParamField path="images" type="List[Image]">
  Images to include with the user message.
</ParamField>

<ParamField path="videos" type="List[Video]">
  Videos to include with the user message.
</ParamField>

<ParamField path="audio" type="List[Audio]">
  Audio files to include with the user message.
</ParamField>

<ParamField path="files" type="List[File]">
  Files to include with the user message. When [readers](/readers/overview) are enabled, file content is automatically extracted and injected into the prompt.
</ParamField>

<ParamField path="output_schema" type="Type[BaseModel]">
  Pydantic model for structured output from the final response.
</ParamField>

## The RunOutput Object

Every non-streaming run returns a `RunOutput` with the full results:

```python theme={null}
output = agent.run("Hello!")

# Content
print(output.content)           # The agent's text response
print(output.content_type)      # "text", "json", etc.

# Metadata
print(output.run_id)            # Unique run identifier
print(output.agent_id)          # Agent that produced this output
print(output.model)             # Model used
print(output.status)            # RunStatus.COMPLETED

# Metrics
print(output.metrics.total_tokens)
print(output.metrics.cost)
print(output.metrics.duration)

# Messages (full conversation history)
print(len(output.messages))

# Media outputs
print(output.images)
print(output.audio)
```

## Stream Event Types

Streaming runs yield `RunOutputEvent` objects. Key event types:

| Event                         | Description                                             |
| ----------------------------- | ------------------------------------------------------- |
| `RunStarted`                  | Agent execution has begun                               |
| `RunContent`                  | A chunk of the agent's text response                    |
| `RunContentCompleted`         | Full content generation is done                         |
| `ToolCallStarted`             | A tool call is about to execute                         |
| `ToolCallCompleted`           | A tool call finished successfully                       |
| `ToolCallError`               | A tool call failed                                      |
| `ReasoningStarted`            | The [thinking](/agents/thinking) phase began            |
| `ReasoningContentDelta`       | A chunk of thinking content (for streaming)             |
| `ReasoningStep`               | A reasoning step from the thinking phase                |
| `ReasoningCompleted`          | The thinking phase finished                             |
| `KnowledgeRetrievalStarted`   | Knowledge retrieval began                               |
| `KnowledgeRetrievalCompleted` | Knowledge retrieval finished                            |
| `MemoryRecallStarted`         | Memory recall began                                     |
| `MemoryRecallCompleted`       | Memory recall finished                                  |
| `MemoryUpdateStarted`         | Memory storage began                                    |
| `MemoryUpdateCompleted`       | Memory storage finished                                 |
| `FileReadStarted`             | File reading began                                      |
| `FileReadCompleted`           | File reading finished                                   |
| `RunCompleted`                | The entire run is finished (includes final `RunOutput`) |
| `RunError`                    | The run failed with an error                            |

<Tip>
  The `RunCompleted` event contains the full `RunOutput` object in `event.output`, giving you access to aggregated metrics and the complete message history even when streaming.
</Tip>

## Deploying with serve()

Use `agent.serve()` to start the full agent runtime — messaging interfaces, HTTP endpoints, webhooks, and cron jobs in a single call:

```python theme={null}
agent.serve(telegram_interface, discord_interface, port=8000)
```

<ParamField path="*interfaces" type="BaseInterface">
  Interface instances (Telegram, Discord) to run concurrently.
</ParamField>

<ParamField path="host" type="str" default="0.0.0.0">
  HTTP server bind address.
</ParamField>

<ParamField path="port" type="int" default="8000">
  HTTP server port.
</ParamField>

<ParamField path="enable_server" type="bool" default="None">
  Force HTTP server on/off. Auto-detects from registered webhooks when `None`.
</ParamField>

<ParamField path="dev" type="bool" default="false">
  Enable hot-reload dev mode.
</ParamField>

`agent.serve()` is a blocking sync call. Use `agent.aserve()` for async contexts.

When webhooks or cron triggers are registered via `@agent.on(...)`, they run alongside interfaces automatically. Set `agent.auth` to protect HTTP endpoints with API key or JWT authentication.

See [Agent Runtime](/agents/runtime) for full details on webhooks, cron, event triggers, lifecycle hooks, and the HTTP server.
