OpenAI Agents SDK: schedule input and tool guardrails
Place input, output and tool guardrails in one Agent run, choose when they execute, and handle each rejection exit, including parallel versus blocking mode.
Prepare the input and environment · Mechanism and data flow · Workflow map
At a glance
This article follows the OpenAI Agents SDK guardrails documentation and covers where to attach guardrails for a single Agent run, when they execute, and how to wrap up after a rejection. API behavior comes from that document, and the code is copied from it unchanged. This batch did not install the SDK or call any model, account or tool, so every result described below as expected is something for you to check in your own environment, not something observed.
Runtime and applicability
- Article type
- Engineering practice
- Verified
- Applies to
- OpenAI Agents SDK Documented openai_agents_sdk task and conditions
Execution locations and responsibilities
- Python application definition and caller Define the configuration or request shown here and check its inputs, outputs and failure branches.
When to use
- You have an existing application or request that uses the OpenAI Agents SDK and can create an
Agentand callRunnerin your own environment. The source page does not cover installation or credential setup, so confirm both against the official instructions.
When not to use
- A guardrail's verdict depends entirely on the detection logic you write. The
sk-match and the math homework check in the examples are not complete solutions, and the code does not prove semantic correctness.
Prepare the input and environment
- You have an existing application or request that uses the OpenAI Agents SDK and can create an
Agentand callRunnerin your own environment. The source page does not cover installation or credential setup, so confirm both against the official instructions. - The input excerpt only defines async
main()and needs the application's existing asynchronous entry point and event loop to call it. The tool excerpt callsRunner.run_syncat module level and is a synchronous execution example that needs a configured SDK and model. Editorial recommendation: check access and credentials for the actual model and runtime, keep credentials private and clean them up as needed. The source specifies no universal credential requirement. - You have listed what to check: user input, the final output, or every function-tool call. A guardrail only returns the verdict your detection logic produces, and you still implement and validate that logic yourself.
Mechanism and data flow
Where guardrails sit in a workflow: The documentation describes input and output guardrails and says they do not all run at the same point. Input guardrails run only for the first agent in the chain, and output guardrails run only for the agent that produces the final output. Tool guardrails run on every guarded function-tool invocation, input checks before execution and output checks after, and that includes local MCP tools when their server configures guardrails. If the workflow has managers, handoffs or delegated specialists and you need checks before or after each custom function-tool call, the documentation says to use tool guardrails instead of relying only on agent-level input and output guardrails.
Parallel versus blocking decides which side effects you can avoid: Input guardrails have two execution modes. The default is parallel (run_in_parallel=True): the guardrail and the agent start together, which gives lower latency, but if the tripwire fires the agent may already have consumed tokens and executed tools before it is cancelled. In blocking mode (run_in_parallel=False) the guardrail completes before the agent starts, so a tripwire means the agent never executes, the expensive model does not start, and no tools run. The documentation presents blocking mode as suited to cost control and to avoiding side effects from tool calls. It does not promise that every side effect in your system is avoided. Output guardrails always run after the agent completes, so they do not support run_in_parallel.
Rejection exits and persistence conditions: an agent-level tripwire_triggered result makes the runner raise the corresponding input or output tripwire exception. Tool guardrails can also use reject_content to skip a call or replace its output with a rejection message; this path need not raise. An output tripwire rejects the candidate final output, and the runner asks the session to persist completed tool calls and outputs with reasoning needed for replay, excluding that candidate. A guardrail-function exception gives an unknown verdict, so completed final-turn items are requested for persistence before the exception surfaces. Terminal function-tool handling applies when Agent.tool_use_behavior makes the result the final output and an agent-level output tripwire rejects it. The SDK retains a replaced call/output pair only if validated fields allow replay-valid reconstruction, using "Output withheld by an output guardrail." as the default output. Otherwise it discards the complete current-response suffix when safe sanitization is impossible. Retained call metadata, including function arguments, may still hold sensitive data. Rejection does not remove every related datum. RunConfig.output_guardrail_blocked_message configures a data-free placeholder.
Calls outside the guardrail pipeline: Tool guardrails wrap FunctionTool instances. The documentation states that handoffs run through the SDK's handoff pipeline, so tool guardrails do not apply to the handoff call itself. Hosted tools (WebSearchTool, FileSearchTool, HostedMCPTool, CodeInterpreterTool, ImageGenerationTool) and built-in execution tools (ComputerTool, ShellTool, ApplyPatchTool, LocalShellTool) do not use this pipeline. Agent.as_tool() does not currently expose tool-guardrail options directly. Guardrails therefore do not automatically cover MCP or hosted tools, and any checks for those calls need a separate design.
Workflow map
| Stage | What happens |
|---|---|
| Where guardrails sit in a workflow | The documentation describes input and output guardrails and says they do not all run at the same point. |
| Parallel versus blocking decides which side effects you can avoid | Input guardrails have two execution modes. |
| Rejection exits: tripwire exceptions and tool rejection | A guardrail function returns GuardrailFunctionOutput, and when tripwire_triggered is true the runner raises InputGuardrailTripwireTriggered or OutputGuardrailTripwireTriggered and halts agent execution, so you can respond to the user in the exception handler. |
| Calls outside the guardrail pipeline | Tool guardrails wrap FunctionTool instances. |
Complete the task
Assign each check to a position: Start by placing every check at one position. A check on the original user request goes in an input guardrail, and it applies only to the first agent. A check on the final reply goes in an output guardrail, which applies only to the agent that produces the final output. A check on the arguments or return value of a custom function tool goes in a tool guardrail. Also note which calls are hosted tools, built-in execution tools or handoffs, because the tool guardrail pipeline does not cover them and you need another approach. This step is design work only and runs nothing.
Write the input guardrail and choose a mode: Use the first code excerpt from the documentation. MathHomeworkOutput is the guardrail agent's output type, with is_math_homework and reasoning. guardrail_agent uses it to decide whether the request asks the model to do math homework. math_guardrail, decorated with @input_guardrail, runs that agent through Runner.run and passes is_math_homework as tripwire_triggered. agent attaches it with input_guardrails=[math_guardrail]. The excerpt does not set run_in_parallel, so by the documentation it uses the default parallel mode. The documentation names run_in_parallel=False, but the excerpt does not show where it is set, so check the official API reference before switching to blocking mode instead of guessing the parameter's location.
Add guardrails to a function tool: Use the second code excerpt. block_secrets reads data.context.tool_arguments, parses it as JSON, and returns ToolGuardrailFunctionOutput.reject_content with a message to remove secrets if the arguments contain sk-; otherwise it returns allow(). redact_output converts data.output to text and rejects it if it contains sk-. classify_text is decorated with @tool and wired to both guardrails through tool_input_guardrails and tool_output_guardrails; it returns length: followed by the text length. Agent(name="Classifier", tools=[classify_text]) is then run with Runner.run_sync(agent, "hello world"), and final_output is printed. The sk- test is only the example's detection rule and is not complete secret detection.
Write a handler for every rejection exit: Catch InputGuardrailTripwireTriggered and OutputGuardrailTripwireTriggered for agent guardrails, and the matching tool exceptions for tool guardrails. According to the documentation, an input tripwire's exception.run_data.input_guardrail_results holds every input guardrail result completed before the run stopped, including the one that fired. The output equivalent is exception.run_data.output_guardrail_results, and tool exceptions expose guardrail and output directly. run_data can be None when an exception is raised outside a runner-managed execution path, so test for that before reading it. If you need your own placeholder for rejected output, set RunConfig.output_guardrail_blocked_message and keep sensitive data out of it.
Check branches in your own environment (editorial recommendation): inspect attachment points, run_in_parallel and actual tool coverage, then check detection logic with samples meant to pass or reject. A tripwire sample should reach its corresponding exception. For tool reject_content, check that the call was skipped or the output replaced and that the rejection message is appropriate; normal message-based rejection can pass acceptance. Do not require every rejection to raise. When checking tool guardrails, separately confirm that the model called classify_text and inspect its arguments. Non-empty final_output is a final reply, not proof of the tool's return value or guardrail execution. Record unexpected exceptions, missing expected rejection or uncalled tools as specific incomplete checks. For empty output, inspect the relevant branch. None of these samples was executed here.
Stopping criteria and cleanup: This step is also an editorial recommendation. On an exception, empty output or your own decision to stop, stop sending requests and then clean up, and do so on every exit path. Cleanup means revoking or rotating any credential set up for the test, removing temporary keys from environment variables, and deleting local logs and temporary files that contain request content. The documentation says that calling RunResultStreaming.cancel() on a streaming run while an output guardrail is running cancels the in-flight guardrail and does not start a final-turn session write. This article offers no other cancellation API, so how you stop a run manually depends on your own runtime.
Worked example
The documentation first imagines a support agent on a stronger, slower, more expensive model and discusses potential benefits of a fast, cheap guardrail model. The shown code configures neither model choice and proves no savings. The input excerpt attaches math_guardrail; async main() catches InputGuardrailTripwireTriggered for the homework request and prints the documented message, but the excerpt does not call that function. In default parallel mode the agent may consume tokens or execute tools before cancellation; blocking mode prevents that agent from starting on a tripwire. The tool excerpt sends hello world to Runner.run_sync at module level. Only if the model calls classify_text with that text do the input check, the function result length:11 and the output check pass. The model is not forced to call the tool, and final_output is not the function's return value. Confirm the actual call in your own environment. No excerpt was run here.
from pydantic import BaseModel
from agents import (
Agent,
GuardrailFunctionOutput,
InputGuardrailTripwireTriggered,
RunContextWrapper,
Runner,
TResponseInputItem,
)
from agents.decorators import input_guardrail
class MathHomeworkOutput(BaseModel):
is_math_homework: bool
reasoning: str
guardrail_agent = Agent( # (1)!
name="Guardrail check",
instructions="Check if the user is asking you to do their math homework.",
output_type=MathHomeworkOutput,
)
@input_guardrail
async def math_guardrail( # (2)!
ctx: RunContextWrapper[None], agent: Agent, input: str | list[TResponseInputItem]
) -> GuardrailFunctionOutput:
result = await Runner.run(guardrail_agent, input, context=ctx.context)
return GuardrailFunctionOutput(
output_info=result.final_output, # (3)!
tripwire_triggered=result.final_output.is_math_homework,
)
agent = Agent( # (4)!
name="Customer support agent",
instructions="You are a customer support agent. You help customers with their questions.",
input_guardrails=[math_guardrail],
)
async def main():
# This should trip the guardrail
try:
await Runner.run(agent, "Hello, can you help me solve for x: 2x + 3 = 11?")
print("Guardrail didn't trip - this is unexpected")
except InputGuardrailTripwireTriggered:
print("Math homework guardrail tripped")
import json
from agents import (
Agent,
Runner,
ToolGuardrailFunctionOutput,
)
from agents.decorators import tool, tool_input_guardrail, tool_output_guardrail
@tool_input_guardrail
def block_secrets(data):
args = json.loads(data.context.tool_arguments or "{}")
if "sk-" in json.dumps(args):
return ToolGuardrailFunctionOutput.reject_content(
"Remove secrets before calling this tool."
)
return ToolGuardrailFunctionOutput.allow()
@tool_output_guardrail
def redact_output(data):
text = str(data.output or "")
if "sk-" in text:
return ToolGuardrailFunctionOutput.reject_content("Output contained sensitive data.")
return ToolGuardrailFunctionOutput.allow()
@tool(
tool_input_guardrails=[block_secrets],
tool_output_guardrails=[redact_output],
)
def classify_text(text: str) -> str:
"""Classify text for internal routing."""
return f"length:{len(text)}"
agent = Agent(name="Classifier", tools=[classify_text])
result = Runner.run_sync(agent, "hello world")
print(result.final_output)
Check the result and failure paths
- Success (editorial recommendation): allow, tripwire exceptions and
reject_contentmessage-based rejection each match their intended branch. Confirm actual tool invocation, arguments and return value; a non-empty final reply alone proves no tool or guardrail execution. - Failure (editorial recommendation): a required tripwire does not fire, expected message-based rejection does not occur, an unrelated exception appears, or
run_data=Noneis unhandled. Normalreject_contentwithout an exception is not a failure. - Empty output: treat an empty
final_outputas incomplete, and check whether a guardrail rejected the candidate output or the model never called the tool. Do not record it as a pass. - User stopping: stop further requests, confirm no run is still in progress, and carry out credential and log cleanup.
- Every exit path, whether success, failure, empty output or stopping, finishes with cleanup, and checks you did not run are recorded as not run.
Scope and limits
- Blocking mode guarantees the guardrail finishes before the agent starts, so the agent does not execute on a tripwire, but the documentation does not promise that every side effect in your system is avoided. In parallel mode the agent may already have started.
- Input guardrails cover only the first agent and output guardrails only the final agent. Hosted tools, built-in execution tools and the handoff call itself do not use the tool guardrail pipeline, and
Agent.as_tool()exposes no such option directly. - The input excerpt defines
main()and needs an existing asynchronous entry point. The tool excerpt calls a synchronous run at module level and needs a configured SDK and model. Neither proves batch execution; check access and credentials for the actual environment. - The scope here is a source-based guide, with no execution record behind it.
No product, API, model, account or tool was run in this batch, and the SDK was not installed. API behavior comes from OpenAI's guardrails documentation, while the completion checks, stopping criteria and credential cleanup are editorial recommendations, not official behavior.
Sources
All links are official pages; verification dates are listed per source, and links point to the version checked.
- OpenAI · guardrails
91fb508