Tawa docs
Integrations

OpenAI Agents SDK

Input, output and function-tool guardrails using the Agents SDK's own hooks.

The OpenAI Agents SDK 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:

HelperWhere it runsScans with
tawa_input_guardrailBefore the agent startsanalyze()
tawa_output_guardrailOn the agent's final outputanalyze()
tawa_tool_input_guardrailBefore each function tool runsscan_tool_call()
tawa_tool_output_guardrailOn each function tool's resultscan_tool_output()

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.

Install

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.

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.

Add the guardrails

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

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

Checking output too

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

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

Both tawa_input_guardrail() and tawa_output_guardrail() accept:

OptionTypeDefaultDescription
should_blockCallable[[ScanResult], bool]default_should_blockDecide whether a scan result should trip the guardrail
extract_textCallable[..., str]scans the whole input/outputBuild the text handed to analyze()
on_reviewCallable[[ScanResult], None | Awaitable[None]]NoneCalled 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
on_errorCallable[[BaseException], None]NoneReceives an exception raised by on_review and, unless fail_closed is set, a scan error the guardrail absorbed
fail_closedboolFalseRe-raise a gateway or network error instead of skipping the scan. New in 0.3.0
session_idstr | NoneNoneTags the scan so it joins the other scans of the same agent turn. New in 0.3.0
cuid / tenant_id / policy_overrides / language—NoneForwarded straight to analyze() per call
namestr | 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.

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.

Tool guardrails

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.

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:

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:

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

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

on_blockBehaviour
"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.

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

OptionTypeDefaultDescription
scan_tool_outputsboolTruetawa_tool_guardrails and guard_function_tools only. Scan tool results. False returns no output guardrail
scan_tool_callsboolTruetawa_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_blockCallable[[ScanResult], bool]default_should_blockDecide whether a scan result blocks
extract_argumentsCallable[[str], dict]default_extract_tool_argumentsSingle input guardrail only. Turns the model's JSON argument string into the dict scan_tool_call() takes
extract_outputCallable[[Any], str | dict | None]default_extract_tool_outputSingle output guardrail only. Turns the tool's return value into text or a dict. None means nothing to scan
reject_messagestrsee aboveSingle guardrails only. The message the model receives on "reject"
session_id, cuid, tenant_id, policy_overridesNoneForwarded to the scan. The tool endpoints take no language
on_review, on_errorNoneAs for the input and output guardrails
fail_closedboolFalseAs 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

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

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

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.

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 for which setting to pick.

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 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's policy option) — should_block is already a plain callback, so pass your own that also checks result.policy:

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)
    ],
)

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 for why, and the equivalent pattern for the raw SDK and the Vercel AI SDK.

On this page