# OpenAI Agents SDK (/docs/python/integrations/openai-agents-sdk)



The [OpenAI Agents SDK](https://openai.github.io/openai-agents-python/) ships
purpose-built `input_guardrail`/`output_guardrail` hooks: input guardrails
validate a message before it reaches the agent, output guardrails validate
the agent's response before it reaches the user, and a tripwire raises a
stoppable exception. `tawaguard.agents_sdk` wraps `TawaGuard.analyze()` as
guardrails shaped exactly like that, so the Agents SDK runs the check itself
— no manual block check before or after the agent call.

`tawaguard.agents_sdk` adds Tawa Guard at four points:

| Helper                       | Where it runs                  | Scans with           |
| ---------------------------- | ------------------------------ | -------------------- |
| `tawa_input_guardrail`       | Before the agent starts        | `analyze()`          |
| `tawa_output_guardrail`      | On the agent's final output    | `analyze()`          |
| `tawa_tool_input_guardrail`  | Before each function tool runs | `scan_tool_call()`   |
| `tawa_tool_output_guardrail` | On each function tool's result | `scan_tool_output()` |

<Callout type="warn" title="Changed in 0.3.0: scan errors fail open by default">
  From 0.3.0 every guardrail **fails open** on a gateway or network error.
  The error goes to `on_error` (if set), the scan is skipped (`output_info`
  is `None`) and the run continues. In 0.2.x the error propagated and aborted
  the run. This includes the existing input and output guardrails. To restore
  the 0.2.x behaviour, pass `fail_closed=True`. See
  [Gateway and network errors](#gateway-and-network-errors).
</Callout>

## Install [#install]

```bash
pip install "tawaguard-sdk[agents]"
```

`openai-agents` is an optional extra, not a dependency of the base
`tawaguard-sdk` package, so nothing pulls it in unless you import
`tawaguard.agents_sdk`.

<Callout type="info" title="Available from 0.3.0">
  The `agents` extra requires `openai-agents>=0.8.4` (it was `>=0.1.0`). Tool
  guardrails need a release that accepts `tool_input_guardrails` and
  `tool_output_guardrails` on `function_tool`, and the input and output
  guardrails already needed a release that accepts `run_in_parallel`. The
  extra's Python 3.9 pins (`eval_type_backport` and `openai<2.45`) are
  unchanged.
</Callout>

## Add the guardrails [#add-the-guardrails]

```python
from agents import Agent, InputGuardrailTripwireTriggered, Runner
from tawaguard import AsyncTawaGuard
from tawaguard.agents_sdk import tawa_input_guardrail, tawa_output_guardrail

tawa = await AsyncTawaGuard.create("YOUR_API_KEY")

agent = Agent(
    name="Assistant",
    instructions="You are a helpful assistant.",
    input_guardrails=[tawa_input_guardrail(tawa)],
    output_guardrails=[tawa_output_guardrail(tawa)],
)

try:
    result = await Runner.run(agent, user_message)
except InputGuardrailTripwireTriggered as err:
    scan = err.guardrail_result.output.output_info  # the ScanResult that tripped it
    print(f"Blocked ({scan.action}): {scan.rationale}")
```

Both `TawaGuard` (sync) and `AsyncTawaGuard` are accepted — the sync client's
blocking `analyze()` call runs off-thread via `asyncio.to_thread` so it
can't stall the Agents SDK's event loop.

## How tripping works [#how-tripping-works]

You don't raise anything yourself. The guardrail function returns a
`GuardrailFunctionOutput` with `tripwire_triggered` set from the scan
result, and the Agents SDK raises
`InputGuardrailTripwireTriggered`/`OutputGuardrailTripwireTriggered` itself
when that's `True` — halting the agent's execution immediately. The
`ScanResult` that triggered it is always attached at
`err.guardrail_result.output.output_info`, so you can inspect `action`,
`rationale`, `confidence`, etc. from the `except` block.

The default blocking policy (`default_should_block`): always block on
`block`/`hard_block`/`soft_block`, never on `allow`/`ood`, and defer to the
server's own `suggestion` for the genuinely undecided actions
(`ambiguous`/`review`/`sandbox`) — the same policy the
[Vercel AI SDK integration](/docs/typescript/integrations/vercel-ai-sdk) uses.
The gateway already collapses `review` to `allow` or `block` per your app's
setting, so against a current gateway the scan's `action` is `allow` or
`block` and the default policy follows it directly. The undecided branch only
applies to a gateway that predates the [review flag](/docs/python/guides/review-flag).

## Checking output too [#checking-output-too]

`tawa_output_guardrail` scans the agent's final output the same way,
raising `OutputGuardrailTripwireTriggered` instead:

```python
except OutputGuardrailTripwireTriggered as err:
    scan = err.guardrail_result.output.output_info
    print(f"Output blocked ({scan.action}): {scan.rationale}")
```

It accepts either plain text or a structured Pydantic output type — a
structured output is turned into text via `model_dump_json()` before being
scanned.

## Options [#options]

Both `tawa_input_guardrail()` and `tawa_output_guardrail()` accept:

| Option                                                 | Type                                              | Default                                              | Description                                                                                                                                                                                                                                                                                                          |
| ------------------------------------------------------ | ------------------------------------------------- | ---------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `should_block`                                         | `Callable[[ScanResult], bool]`                    | `default_should_block`                               | Decide whether a scan result should trip the guardrail                                                                                                                                                                                                                                                               |
| `extract_text`                                         | `Callable[..., str]`                              | scans the whole input/output                         | Build the text handed to `analyze()`                                                                                                                                                                                                                                                                                 |
| `on_review`                                            | `Callable[[ScanResult], None \| Awaitable[None]]` | `None`                                               | Called once per scan whenever `result.needs_review` is `True`, whether or not the guardrail trips, before the tripwire decision. May be a plain or a coroutine function. Errors raised inside it go to `on_error`, or are dropped when `on_error` is not set. See [The review flag](/docs/python/guides/review-flag) |
| `on_error`                                             | `Callable[[BaseException], None]`                 | `None`                                               | Receives an exception raised by `on_review` and, unless `fail_closed` is set, a scan error the guardrail absorbed                                                                                                                                                                                                    |
| `fail_closed`                                          | `bool`                                            | `False`                                              | Re-raise a gateway or network error instead of skipping the scan. New in 0.3.0                                                                                                                                                                                                                                       |
| `session_id`                                           | `str \| None`                                     | `None`                                               | Tags the scan so it joins the other scans of the same agent turn. New in 0.3.0                                                                                                                                                                                                                                       |
| `cuid` / `tenant_id` / `policy_overrides` / `language` | —                                                 | `None`                                               | Forwarded straight to `analyze()` per call                                                                                                                                                                                                                                                                           |
| `name`                                                 | `str \| None`                                     | `"tawa_input_guardrail"` / `"tawa_output_guardrail"` | Guardrail name, used for tracing                                                                                                                                                                                                                                                                                     |

`tawa_input_guardrail` additionally accepts `run_in_parallel` (default
`True`), matching the Agents SDK's own `InputGuardrail` option — whether the
guardrail runs concurrently with the agent or before it starts.

<Callout type="info">
  Empty input/output (e.g. a tool-only turn with no text content) skips the
  scan entirely rather than sending an empty string — `output_info` is
  `None` and the tripwire never fires in that case.
</Callout>

## Tool guardrails [#tool-guardrails]

<Callout type="info" title="Available from 0.3.0">
  `tawa_tool_input_guardrail`, `tawa_tool_output_guardrail`,
  `tawa_tool_guardrails` and `guard_function_tools` are new in 0.3.0.
</Callout>

A tool result is the usual route for indirect prompt injection: a web page,
document or API response that a tool returns and the model then reads. The
Agents SDK runs a function tool's input guardrails before it calls the
function and its output guardrails on the value the function returned. Tawa's
tool guardrails scan the call arguments with `scan_tool_call()` and the result
with `scan_tool_output()`, tagged with the tool's name.

The quickest way to attach them is `guard_function_tools`, which adds the
guardrails to every `FunctionTool` in a list and keeps any guardrails already
on those tools:

```python
from agents import Agent, function_tool
from tawaguard.agents_sdk import guard_function_tools


@function_tool
def fetch_page(url: str) -> str:
    """Fetch a web page."""
    ...


agent = Agent(
    name="Assistant",
    instructions="You are a helpful assistant.",
    tools=guard_function_tools([fetch_page], tawa),
)
```

To attach them to one tool yourself, build the pair with
`tawa_tool_guardrails` and pass them to `function_tool(...)` or to an MCP
server's constructor:

```python
from tawaguard.agents_sdk import tawa_tool_guardrails

inputs, outputs = tawa_tool_guardrails(tawa, scan_tool_calls=False)  # scan results only


@function_tool(tool_input_guardrails=inputs, tool_output_guardrails=outputs)
def search_docs(query: str) -> str: ...
```

`tawa_tool_input_guardrail` and `tawa_tool_output_guardrail` build a single
guardrail each, for when you want different options per side.

### What a block does [#what-a-block-does]

A blocked call or result is not shown to the model. `on_block` picks what
happens instead:

| `on_block`           | Behaviour                                                                                                                                                                     |
| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `"reject"` (default) | The model receives a short message in place of the tool result and the run continues. For a blocked call the tool is not run. The message does not repeat the blocked content |
| `"raise"`            | The Agents SDK raises `ToolInputGuardrailTripwireTriggered` or `ToolOutputGuardrailTripwireTriggered`                                                                         |

The `ScanResult` is at `output_info` on the guardrail output either way, and
at `err.output.output_info` on a raised error.

```python
from agents.exceptions import ToolOutputGuardrailTripwireTriggered

agent = Agent(
    name="Assistant",
    instructions="You are a helpful assistant.",
    tools=guard_function_tools([fetch_page], tawa, on_block="raise"),
)

try:
    result = await Runner.run(agent, user_message)
except ToolOutputGuardrailTripwireTriggered as err:
    scan = err.output.output_info
    print(f"Tool result blocked ({scan.action}): {scan.rationale}")
```

The default messages are `"This tool call was blocked by Tawa Guard."` and
`"This tool result was withheld by Tawa Guard."`. Change them with
`reject_message` on the single-guardrail builders.

### Tool guardrail options [#tool-guardrail-options]

| Option                                                | Type                                   | Default                          | Description                                                                                                     |
| ----------------------------------------------------- | -------------------------------------- | -------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `scan_tool_outputs`                                   | `bool`                                 | `True`                           | `tawa_tool_guardrails` and `guard_function_tools` only. Scan tool results. `False` returns no output guardrail  |
| `scan_tool_calls`                                     | `bool`                                 | `True`                           | `tawa_tool_guardrails` and `guard_function_tools` only. Scan call arguments. `False` returns no input guardrail |
| `on_block`                                            | `"reject" \| "raise"`                  | `"reject"`                       | What a block does, see above                                                                                    |
| `should_block`                                        | `Callable[[ScanResult], bool]`         | `default_should_block`           | Decide whether a scan result blocks                                                                             |
| `extract_arguments`                                   | `Callable[[str], dict]`                | `default_extract_tool_arguments` | Single input guardrail only. Turns the model's JSON argument string into the dict `scan_tool_call()` takes      |
| `extract_output`                                      | `Callable[[Any], str \| dict \| None]` | `default_extract_tool_output`    | Single output guardrail only. Turns the tool's return value into text or a dict. `None` means nothing to scan   |
| `reject_message`                                      | `str`                                  | see above                        | Single guardrails only. The message the model receives on `"reject"`                                            |
| `session_id`, `cuid`, `tenant_id`, `policy_overrides` |                                        | `None`                           | Forwarded to the scan. The tool endpoints take no `language`                                                    |
| `on_review`, `on_error`                               |                                        | `None`                           | As for the input and output guardrails                                                                          |
| `fail_closed`                                         | `bool`                                 | `False`                          | As for the input and output guardrails                                                                          |

`default_extract_tool_arguments` uses a JSON object as is, wraps any other
JSON value as `{"value": ...}`, and wraps text that is not valid JSON as
`{"raw": text}` so it is still scanned. `default_extract_tool_output` passes
strings and dicts through, serialises Pydantic models and dataclasses to
JSON, and JSON-encodes anything else (falling back to `str()`). A call with no
arguments and an empty result are not scanned.

### Cost [#cost]

Each tool result is one extra scan and each tool call is one more, so an
agent run with many tool calls makes many scans on top of the input and output
scans. Each scan counts toward your usage. Pass `scan_tool_outputs=False`
and/or `scan_tool_calls=False` to turn either side off.

### What is not covered [#what-is-not-covered]

The Agents SDK runs tool guardrails for function tools only, including the
function tools an MCP server exposes to the SDK. These are not function
tools, so their inputs and results are not scanned by the tool guardrails:

* Hosted tools (web search, file search, code interpreter, hosted MCP) and
  other tools the model provider executes.
* Computer, shell and apply-patch tools.
* Handoffs.

`guard_function_tools` leaves tools that are not function tools untouched.
The final-output guardrail still sees whatever the model says about their
results. The tool objects are updated in place, so guard a tool once: a second
call adds a second pair.

## Gateway and network errors [#gateway-and-network-errors]

Every guardrail here fails open by default. If the Tawa Guard request fails
(after the client's retries), the error goes to `on_error(exc)` if you set
one, the scan is skipped (`output_info` is `None`), and the agent run
continues. Pass `fail_closed=True` to re-raise the error instead, which
aborts the run. `on_error` is called only for errors the guardrail absorbed.

```python
inputs, outputs = tawa_tool_guardrails(
    tawa,
    fail_closed=True,  # 0.2.x behaviour: a failed scan aborts the run
    on_error=lambda exc: logger.warning("tawa scan failed: %s", exc),
)
```

See [Scanning tool outputs](/docs/api/best-practices#scanning-tool-outputs)
for which setting to pick.

## Policy Studio integration [#policy-studio-integration]

`default_should_block` only looks at the scan's raw `action`/`suggestion`
— it never reads `result.policy`, the verdict from your org's
[Policy Studio](/docs/python/guides/policy-rules) rules. That verdict is already
computed server-side on *every* scan; by default it's simply not checked.

There's no dedicated option for this yet (unlike the
[Vercel AI SDK integration](/docs/typescript/integrations/vercel-ai-sdk#policy-studio-integration-policy)'s
`policy` option) — `should_block` is already a plain callback, so pass your
own that also checks `result.policy`:

```python
from tawaguard.agents_sdk import default_should_block, tawa_input_guardrail

def policy_aware_should_block(result):
    if result.policy and "block" in result.policy.directives:
        return True
    return default_should_block(result)

agent = Agent(
    name="Assistant",
    instructions="You are a helpful assistant.",
    input_guardrails=[
        tawa_input_guardrail(tawa, should_block=policy_aware_should_block)
    ],
)
```

<Callout type="warn">
  Activating a template in the dashboard's Policy Studio only changes what
  `result.policy` contains on future scans — it never blocks anything by
  itself. See [Enforcing a policy](/docs/python/guides/enforcing-policy) for why,
  and the equivalent pattern for the raw SDK and the Vercel AI SDK.
</Callout>
