> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agno.com/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:

<img className="block dark:hidden" src="https://mintcdn.com/agno-v2/I_OqdwByK40CFkbk/images/background-tasks-notenabled-light.png?fit=max&auto=format&n=I_OqdwByK40CFkbk&q=85&s=615b75c6fd7b2bc946dd12cb853f41b6" alt="Background tasks not enabled" width="2895" height="906" data-path="images/background-tasks-notenabled-light.png" />

<img className="hidden dark:block" src="https://mintcdn.com/agno-v2/I_OqdwByK40CFkbk/images/background-tasks-notenabled-dark.png?fit=max&auto=format&n=I_OqdwByK40CFkbk&q=85&s=510be4326e46562ee9d0e527a76feb33" alt="Background tasks not enabled" width="2895" height="906" data-path="images/background-tasks-notenabled-dark.png" />

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

<img className="block dark:hidden" src="https://mintcdn.com/agno-v2/I_OqdwByK40CFkbk/images/background-tasks-enabled-light.png?fit=max&auto=format&n=I_OqdwByK40CFkbk&q=85&s=b274e516d035f89d422e312945a29aaa" alt="Background tasks enabled" width="2271" height="906" data-path="images/background-tasks-enabled-light.png" />

<img className="hidden dark:block" src="https://mintcdn.com/agno-v2/I_OqdwByK40CFkbk/images/background-tasks-enabled-dark.png?fit=max&auto=format&n=I_OqdwByK40CFkbk&q=85&s=dddbd20dd6bccab04949979587e67042" alt="Background tasks enabled" width="2271" height="906" data-path="images/background-tasks-enabled-dark.png" />

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](/agent-os/usage/background-hooks-global) 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.
</Note>

### 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](/agent-os/usage/background-hooks-decorator) for an example.

<Check>
  **Background tasks require AgentOS.** When running agents directly (not through AgentOS), the `@hook(run_in_background=True)` decorator has no effect - hooks will run synchronously.
</Check>

## 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. This means background mode is not suitable for Guardrails.
</Warning>

### Data Isolation

When hooks run in the background, AgentOS automatically creates deep copies of:

* `run_input` - The input to the agent run
* `run_context` - The current run context
* `run_output` - The output from the agent

This prevents race conditions where background hooks might accidentally modify data that's being used elsewhere.

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

<CardGroup cols={3}>
  <Card title="Global Background Hooks" icon="gear" href="/agent-os/usage/background-hooks-global">
    Enable background hooks globally for all agents
  </Card>

  <Card title="Per-Hook Background" icon="code" href="/agent-os/usage/background-hooks-decorator">
    Mix synchronous and background hooks
  </Card>

  <Card title="Output Evaluation" icon="clipboard-check" href="/agent-os/usage/background-output-evaluation">
    Use an agent-as-judge to evaluate responses
  </Card>
</CardGroup>

## Developer Resources

* [@hook Decorator Reference](/reference/hooks/hook-decorator)
* [Hooks Overview](/hooks/overview)
