> ## Documentation Index
> Fetch the complete documentation index at: https://agno-v2.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Background Hooks

> Run agent hooks as non-blocking background tasks in AgentOS

When serving agents or teams through AgentOS, you can configure pre-hooks and post-hooks to run as background tasks. This means the API response is returned immediately to the user while the hooks continue executing in the background.

## Why Use Background Hooks?

By default, hooks used by agents and teams in your AgentOS are in the execution path and block the response:

![Background tasks not enabled](https://mintcdn.com/agno-v2/I_OqdwByK40CFkbk/images/background-tasks-notenabled-light.png?fit=max\&auto=format\&n=I_OqdwByK40CFkbk\&q=85\&s=615b75c6fd7b2bc946dd12cb853f41b6)

With background hooks enabled, your hooks won't block the response, increasing response speed:

![Background tasks enabled](https://mintcdn.com/agno-v2/I_OqdwByK40CFkbk/images/background-tasks-enabled-light.png?fit=max\&auto=format\&n=I_OqdwByK40CFkbk\&q=85\&s=b274e516d035f89d422e312945a29aaa)

This is useful for:

* **Agent Evaluation**: Evaluate the agent's responses without affecting the responses themselves
* **Analytics and logging**: Track usage patterns without affecting response time
* **Notifications**: Send emails, Slack messages, or webhook calls
* **External API calls**: Sync data with third-party services
* **Non-critical data processing**: Tasks that don't affect the response

## Enabling Background Tasks

There are two ways to enable background execution for hooks:

### Option 1: Global Setting via AgentOS

Enable background execution for **all** hooks across all agents and teams (even as part of a workflow):

```python theme={null}
from agno.os import AgentOS

agent_os = AgentOS(
    agents=[agent],
    teams=[team],
    workflows=[workflow],
    run_hooks_in_background=True,  # All hooks run in background
)
```

When enabled, this setting automatically propagates to:

* All agents registered with AgentOS
* All teams and their member agents (including nested teams)
* All workflows and the agents/teams within their steps

See [Global Background Hooks Example](https://agno-v2.mintlify.site/agent-os/usage/background-hooks-global.md) for an example.

> [!NOTE]
>
> Note that pre-hooks are typically used for validation or modification of the input of a run. If you use them as background tasks, they will execute after the run has already been initiated.
>
> If you have hooks that should not run as background tasks, you should use the second option and mark only the specific hooks to run in background.

### Option 2: Per-Hook Setting via Decorator

Mark specific hooks to run in background using the `@hook` decorator:

```python theme={null}
from agno.hooks import hook

@hook(run_in_background=True)
async def send_notification(run_output, agent):
    """Only this hook runs in the background."""
    await send_slack_message(run_output.content)
```

This approach gives you fine-grained control: critical hooks are executed during the run while non-critical hooks run in the background.

See [Per-Hook Background Example](https://agno-v2.mintlify.site/agent-os/usage/background-hooks-decorator.md) for an example.

> [!TIP]
>
> **Background scheduling requires AgentOS.** Direct `arun()` calls await async hooks in the run path. Direct `run()` calls require synchronous hooks and raise `ValueError` when given an async hook.

## How It Works

AgentOS uses FastAPI's [BackgroundTasks](https://fastapi.tiangolo.com/tutorial/background-tasks/) to schedule hooks for execution after the response is sent.

Background tasks execute **sequentially** after the response is sent. If you have multiple background hooks, they run one after another.

> [!WARNING]
>
> **Pre- and post-hooks in background mode cannot modify the request or response.** Any modifications to `run_input` or `run_output` won't affect the agent's processing. Only use background mode for pre- and post-hooks that perform logging or monitoring. Guardrails are an exception: they always run synchronously, even when `run_hooks_in_background=True`, so their checks can still block the run.

### Data Isolation

When hooks run in the background, AgentOS attempts to create deep copies of:

* `run_input` - The input to the agent run
* `run_context` - The current run context
* `run_output` - The output from the agent
* `session_state` - The current session state
* `dependencies` - The dependencies passed to the run
* `metadata` - The run metadata

If a value cannot be copied, AgentOS logs a warning and passes the original reference to the hook. Use immutable values or independently created dependencies when a background hook might mutate them.

### Error Handling

Errors in background tasks don't affect the API response (since it's already been sent). Make sure to implement proper error handling and logging in your background hooks:

```python theme={null}
@hook(run_in_background=True)
async def safe_background_hook(run_output, agent):
    try:
        await external_api_call(run_output)
    except Exception as e:
        logger.error(f"Background hook failed: {e}")
```

## Examples

> **[Global Background Hooks](https://agno-v2.mintlify.site/agent-os/usage/background-hooks-global.md)**
>
> Enable background hooks globally for all agents

> **[Per-Hook Background](https://agno-v2.mintlify.site/agent-os/usage/background-hooks-decorator.md)**
>
> Mix synchronous and background hooks

> **[Output Evaluation](https://agno-v2.mintlify.site/agent-os/usage/background-output-evaluation.md)**
>
> Use an agent-as-judge to evaluate responses

## Developer Resources

* [@hook Decorator Reference](https://agno-v2.mintlify.site/reference/hooks/hook-decorator.md)
* [Hooks Overview](https://agno-v2.mintlify.site/hooks/overview.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.