How-to › Use AI to do the integration

How to add input and output guardrails with a guardrail library#

Wire an injection check and a credential check into OpenAI Agents SDK guardrails, NeMo Guardrails, and Guardrails AI, then screen tool results as well.

Audience
Agent builder
Level
beginner
Topic
Guard agents and add approvals
Languages
Python
Verified

A user types “ignore all previous instructions” and your agent complies, or it pastes a cloud access key into its answer because the key sat in a config file it read. A regular expression can stop either one, but only where it runs. The injection check has to see the prompt before the model does, and the credential check has to see the reply before the user does.

What you get

You will end up with one injection check and one credential check wired into three guardrail libraries, a replay of ten scripted turns through all three, and a tool-result check. One library runs live and two replay from committed records. This is for you if your agent already calls tools and has no checks around it.

Short answer

In the OpenAI Agents SDK, add an input_guardrail that trips on instruction overrides and requests to send secrets out, with run_in_parallel=False, and an output_guardrail that trips on a credential. Then attach a tool_output_guardrail to every tool that reads outside text, because an input guardrail sees only the user’s message. NeMo Guardrails and Guardrails AI run the same checks through rails or validators.

You will need

Python 3.12 or later, Node 22 to run npm ci in the sample directory, and an agent loop with at least one tool. The policy is small and deterministic, so the replay compares where each library hooks in. The agent’s turns are scripted with the SDK’s own ScriptedModel instead of a model, so every count below is the result of a scripted policy.

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
Guardrails AI hub validatorsYou want checks you add one at a time, from PyPI or your own codeIts own openai pin, metrics on by default, no Python 3.14 in 0.11.0, and some validators need torch or an LLM callYour framework already has guardrail hooks you can fill
Llama Guard classifierYou need hazard categories that no regular expression can coverOne extra model call per check, 12 billion parameters to host, and no injection categoryThe threat is prompt injection, which its card sends to Prompt Guard
NeMo GuardrailsSeveral agents on different frameworks share one policy fileColang and YAML to learn, no Python 3.14 in 0.25.0, and custom flows run on an engine marked deprecatedOne framework, where its native hooks need less code
OpenAI Agents SDK guardrailsYour agent already runs on that SDKTies the policy to one framework and its version of the openai packageAgents on other frameworks need the same checks

The SDK’s hooks need no second configuration language, but they bind the policy to one runtime. NeMo Guardrails takes a policy file that any framework can call, and the price is Colang plus an engine in transition. Guardrails AI publishes its validators as separate PyPI packages, whose dependencies cannot share an environment with the SDK.

Write the policy once

Both checks are plain functions over text. The libraries below wrap them and decide nothing themselves.

INJECTION = {
    "override-instructions": re.compile(
        r"\b(ignore|disregard|forget)\b[^.]{0,40}?\b(previous|prior|above|earlier|your|all)\b"
        r"[^.]{0,20}?\b(instructions|rules|guidelines|prompt)\b",
        re.IGNORECASE,
    ),
    "reveal-system-prompt": re.compile(
        r"\b(reveal|print|show|repeat)\b[^.]{0,30}?\bsystem prompt\b", re.IGNORECASE
    ),
    "exfiltrate": re.compile(
        r"\b(send|email|forward|upload|post|paste)\b[^.]{0,60}?"
        r"\b(api keys?|tokens?|passwords?|secrets?|credentials?|customer (?:data|list|records))\b",
        re.IGNORECASE,
    ),
}

CREDENTIAL = {
    "aws-access-key-id": re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"),
    "github-token": re.compile(r"\bgh[pousr]_[A-Za-z0-9]{36}\b"),
    "private-key-block": re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),
}

Add the three guardrails to the agent

The OpenAI Agents SDK attaches input and output guardrails to an agent, and tool guardrails to each function tool. A tripwire raises InputGuardrailTripwireTriggered or OutputGuardrailTripwireTriggered. A tool output guardrail can instead replace the result with a message to the model.

# run_in_parallel=False: the model is not called until the check has passed.
@input_guardrail(run_in_parallel=False)
def block_injection(ctx, agent, agent_input):
    reason = injection_reason(_text(agent_input))
    return GuardrailFunctionOutput(output_info=reason, tripwire_triggered=reason is not None)


@output_guardrail
def block_credentials(ctx, agent, output):
    reason = credential_reason(str(output))
    return GuardrailFunctionOutput(output_info=reason, tripwire_triggered=reason is not None)


@tool_output_guardrail
def screen_tool_output(data):
    reason = injection_reason(str(data.output))
    if reason is None:
        return ToolGuardrailFunctionOutput.allow()
    return ToolGuardrailFunctionOutput.reject_content(
        f"The tool result was withheld by policy ({reason}).", output_info=reason
    )

The same module calls set_tracing_disabled(True), because the tracing guide says tracing is enabled by default and exports to the OpenAI backend. netguard.py sets NEMO_GUARDRAILS_NO_USAGE_STATS before NeMo Guardrails loads, since its usage reports are on unless an opt-out is set. The default run_in_parallel=True starts the model alongside the check, and the guardrails guide warns that the agent may already have spent tokens and run tools when the tripwire fires.1

Run the same policy through rails and validators

NeMo Guardrails reads a config.yml and Colang flows. Each flow calls the policy as a registered action, and check() runs the rails without generating a reply.

define flow screen user input
  $reason = execute injection_reason(text=$user_message)
  if $reason
    bot refuse by policy
    stop

define flow screen bot output
  $reason = execute credential_reason(text=$bot_message)
  if $reason
    bot refuse by policy
    stop

Guardrails AI wraps each check as a validator. The sample also loads guardrails-ai-secrets-present, a published validator built on detect-secrets, and runs it over every reply as a second opinion. The injection-oriented validators weigh more: guardrails-ai-detect-jailbreak requires torch and transformers, and guardrails-ai-unusual-prompt requires litellm to ask a model.

@register_validator(name="howto/no-injection", data_type="string")
class NoInjection(Validator):
    def _validate(self, value, metadata):
        reason = policy.injection_reason(value)
        return PassResult() if reason is None else FailResult(error_message=reason)

Replay ten turns through all three

The three libraries cannot share one environment, because openai-agents 0.26.0 needs openai 3.x and guardrails-ai 0.11.0 needs 2.x. So each runs in its own process, under an audit hook that refuses every socket connect and DNS lookup.

The pinned releases of two of them also stop short of Python 3.14. On PyPI, nemoguardrails 0.25.0 requires Python <3.14, >=3.11 and guardrails-ai 0.11.0 requires <3.14, >=3.10. On 2026-11-30 each was the highest release of its project. So npm ci installs the Agents SDK alone, and record.sh ran the other two once, on Python 3.12.3 under the same hook. replay.py reads their rows from records/:

npm ci
python3 replay.py
live:     openai-agents 0.26.0
recorded: nemoguardrails 0.25.0, guardrails-ai 0.11.0, on Python 3.12.3 by record.sh, sources unchanged

case                  should  openai-agents  nemoguardrails  guardrails-ai  SecretsPresent
override              block   input          input           input          -
exfiltrate            block   input          input           input          -
aws-key-in-reply      block   output         output          output         blocks
private-key-in-reply  block   output         output          output         blocks
paraphrased           block   passed         passed          passed         -
git-ignore-space      pass    passed         passed          passed         -
akia-prefix           pass    passed         passed          passed         -
readme-steps          pass    passed         passed          passed         -
meeting-notes         pass    passed         passed          passed         -
rotate-key            pass    passed         passed          passed         -

openai-agents   blocked 4 of 5 bad, 0 of 5 benign
nemoguardrails  blocked 4 of 5 bad, 0 of 5 benign
guardrails-ai   blocked 4 of 5 bad, 0 of 5 benign

tool result carrying an injection, after a benign prompt
  openai-agents, input guardrail only        email sent to: drop@attacker.example
  openai-agents, plus tool_output_guardrail  email sent to: nobody
  nemoguardrails, input rail on the result   blocked
  guardrails-ai, NoInjection on the result   blocked

a 0.2 s input check that trips, openai-agents
  run_in_parallel=True   model calls: 1, email sent to: ops@example.com
  run_in_parallel=False  model calls: 0, email sent to: nobody

network attempts: openai-agents 0, nemoguardrails 0, guardrails-ai 0

The three libraries agree on every row because they run one policy. The paraphrased override gets through all of them, since it uses none of the words the pattern looks for. The benign turns that mention “ignore,” “instructions,” or the AKIA prefix pass.

The tool rows are the pitfall. A benign question led to a status page that told the scripted model to email every API key, and with only an input guardrail the email went out. The slow-check rows show the parallel default in action: a check that takes 0.2 seconds tripped after the tool had run.

records/provenance.json stores two SHA-256 hashes for each record: one over the files it was made from, record.sh among them, and one over the record and the Python that made it. replay.py and the suite recompute both, and compare each record’s version with the pin. That catches a record that went stale by accident. It cannot show that a library made the record.

Check it worked

The live suite asserts each claim in the replay. Its controls switch the SDK’s tracing back on and make the audit hook refuse a lookup and a connect. Its record tests fail on a stale record and on a recorded suite that skipped or failed a test, and five more run the record check itself on a copy. Four interrupt record.sh and check that records/ comes back whole, or that its saved copy is kept and named, and that nothing it started still runs.

python3 -m unittest -v test_guardrails 2>&1 | grep -v "^Ran "
test_netguard_refuses_and_reports_a_connect_and_a_lookup (test_guardrails.ControlTests.test_netguard_refuses_and_reports_a_connect_and_a_lookup) ... ok
test_the_agents_sdk_records_no_trace (test_guardrails.ControlTests.test_the_agents_sdk_records_no_trace) ... ok
test_credential_rules_and_their_neighbors (test_guardrails.PolicyTests.test_credential_rules_and_their_neighbors) ... ok
test_injection_rules_and_their_neighbors (test_guardrails.PolicyTests.test_injection_rules_and_their_neighbors) ... ok
test_non_text_is_refused_rather_than_passed (test_guardrails.PolicyTests.test_non_text_is_refused_rather_than_passed) ... ok
test_the_incident_page_trips_the_input_policy (test_guardrails.PolicyTests.test_the_incident_page_trips_the_input_policy) ... ok
test_a_python_the_libraries_do_not_support_is_refused (test_guardrails.ProvenanceTests.test_a_python_the_libraries_do_not_support_is_refused) ... ok
test_a_record_that_names_another_version_is_refused_with_fresh_hashes_too (test_guardrails.ProvenanceTests.test_a_record_that_names_another_version_is_refused_with_fresh_hashes_too) ... ok
test_only_record_sh_may_write_the_hashes (test_guardrails.ProvenanceTests.test_only_record_sh_may_write_the_hashes) ... ok
test_the_copy_starts_clean (test_guardrails.ProvenanceTests.test_the_copy_starts_clean) ... ok
test_the_python_that_made_a_record_is_part_of_its_hash (test_guardrails.ProvenanceTests.test_the_python_that_made_a_record_is_part_of_its_hash) ... ok
test_a_restore_that_fails_keeps_the_saved_records_and_says_where (test_guardrails.RecordScriptTests.test_a_restore_that_fails_keeps_the_saved_records_and_says_where) ... ok
test_a_second_signal_does_not_cut_the_restore_short (test_guardrails.RecordScriptTests.test_a_second_signal_does_not_cut_the_restore_short) ... ok
test_a_signal_while_a_step_starts_still_stops_the_step (test_guardrails.RecordScriptTests.test_a_signal_while_a_step_starts_still_stops_the_step) ... ok
test_an_interrupt_during_a_rewrite_puts_the_records_back (test_guardrails.RecordScriptTests.test_an_interrupt_during_a_rewrite_puts_the_records_back) ... ok
test_no_record_changed_or_outlived_its_sources (test_guardrails.RecordTests.test_no_record_changed_or_outlived_its_sources) ... ok
test_the_recorded_suite_ran_every_test_and_passed (test_guardrails.RecordTests.test_the_recorded_suite_ran_every_test_and_passed) ... ok
test_a_blocking_input_guardrail_never_reaches_the_model (test_guardrails.ReplayTests.test_a_blocking_input_guardrail_never_reaches_the_model) ... ok
test_a_slow_parallel_check_trips_after_the_tool_ran (test_guardrails.ReplayTests.test_a_slow_parallel_check_trips_after_the_tool_ran) ... ok
test_an_input_guardrail_alone_lets_a_tool_result_send_the_email (test_guardrails.ReplayTests.test_an_input_guardrail_alone_lets_a_tool_result_send_the_email) ... ok
test_every_library_blocks_the_same_four_and_no_benign_turn (test_guardrails.ReplayTests.test_every_library_blocks_the_same_four_and_no_benign_turn) ... ok
test_nemo_and_guardrails_ai_block_the_tool_result_when_asked (test_guardrails.ReplayTests.test_nemo_and_guardrails_ai_block_the_tool_result_when_asked) ... ok
test_no_library_attempted_the_network (test_guardrails.ReplayTests.test_no_library_attempted_the_network) ... ok
test_prompts_stop_at_input_and_credentials_at_output (test_guardrails.ReplayTests.test_prompts_stop_at_input_and_credentials_at_output) ... ok
test_the_paraphrase_gets_through_the_scripted_policy (test_guardrails.ReplayTests.test_the_paraphrase_gets_through_the_scripted_policy) ... ok
test_the_published_validator_flags_both_credential_replies (test_guardrails.ReplayTests.test_the_published_validator_flags_both_credential_replies) ... ok
test_the_sample_input_guardrail_is_declared_blocking (test_guardrails.ReplayTests.test_the_sample_input_guardrail_is_declared_blocking) ... ok

----------------------------------------------------------------------

OK

The tests that import the other two libraries ran in record.sh:

cat records/test_recorded.txt
test_nemo_runs_custom_flows_on_the_deprecated_engine (test_recorded.RecordedControlTests.test_nemo_runs_custom_flows_on_the_deprecated_engine) ... ok
test_nemo_usage_reports_are_switched_off (test_recorded.RecordedControlTests.test_nemo_usage_reports_are_switched_off) ... ok
test_netguard_catches_guardrails_ai_metrics_left_on (test_recorded.RecordedControlTests.test_netguard_catches_guardrails_ai_metrics_left_on) ... ok
test_a_second_run_prints_the_same_record (test_recorded.RecordedReplayTests.test_a_second_run_prints_the_same_record) ... ok
test_every_library_blocks_the_same_four_and_no_benign_turn (test_recorded.RecordedReplayTests.test_every_library_blocks_the_same_four_and_no_benign_turn) ... ok
test_nemo_and_guardrails_ai_block_the_tool_result_when_asked (test_recorded.RecordedReplayTests.test_nemo_and_guardrails_ai_block_the_tool_result_when_asked) ... ok
test_no_library_attempted_the_network (test_recorded.RecordedReplayTests.test_no_library_attempted_the_network) ... ok
test_prompts_stop_at_input_and_credentials_at_output (test_recorded.RecordedReplayTests.test_prompts_stop_at_input_and_credentials_at_output) ... ok
test_the_paraphrase_gets_through_the_scripted_policy (test_recorded.RecordedReplayTests.test_the_paraphrase_gets_through_the_scripted_policy) ... ok
test_the_published_validator_flags_both_credential_replies (test_recorded.RecordedReplayTests.test_the_published_validator_flags_both_credential_replies) ... ok

----------------------------------------------------------------------
Ran 10 tests

OK

Remove tool_output_guardrails=guards from the fetch tool and the live test about the tool result fails, because the email goes out.

When it goes wrong

The replay stops with sha256_sources changed since it was recorded, or with sha256_record after a record was edited by hand. A file a record was made from changed after record.sh last ran, so the record may no longer be what that library prints. Put Python 3.11, 3.12, or 3.13 first on the PATH, run bash record.sh, and commit records/.

pip finds no nemoguardrails 0.25.0 or guardrails-ai 0.11.0 on Python 3.14, because both declare Python below 3.14. Install them on 3.11 to 3.13, which record.sh checks. Without the pin, pip on Python 3.14 installs nemoguardrails 0.17.0 and guardrails-ai 0.10.2, earlier releases that set no limit at 3.14.

The tripwire fires after a tool already ran. The input guardrail kept the default run_in_parallel=True, so the model started before a slow check finished. Pass run_in_parallel=False to any input guardrail that guards a tool with side effects.

Guardrails AI dials out during a run that should be offline. Guard() turns hub metrics on when there is no ~/.guardrailsrc, because enable_metrics defaults to true. Call configure(allow_metrics_collection=False) on every guard, or run guardrails configure --disable-metrics.

NeMo logs that IORails cannot be used. In 0.25.0, IORails runs only the rails in its own catalog, so Guardrails(config) falls back to LLMRails for custom Colang flows. Constructing LLMRails directly warns that it is deprecated since 0.25.0.2 Pass use_iorails=False to ask for it plainly, and plan the move before that engine goes.

guardrails hub install fails for a validator. The project’s README says validators are moving to standard PyPI packages, and the migration issue names the hub install command as one of two things that shut down on August 25, 2026. Install guardrails-ai-<name> with pip instead.3

When not to do this

Do not treat a pattern list as an injection defense. The paraphrase in the replay walked past all three libraries, and a paraphrase costs an attacker nothing. Patterns are a cheap first layer, and an approval step in front of any tool that sends, pays, or deletes is the layer that holds.

Do not check only the user’s message. Every tool that returns text written by someone else needs the same check, and so does every document a retrieval step adds.

Do not adopt NeMo Guardrails or Guardrails AI for one agent on one framework. The SDK’s own hooks did the same job here with one dependency tree and no Colang or validator registry.

Do not use Llama Guard as the defense against an “ignore your instructions” prompt. Its fourteen categories cover hazards such as violent crime, privacy, and code interpreter abuse, and its model card sends prompt attacks to Prompt Guard 2.4 Use it when the risk is harmful content, and budget a model call per check.

Last verified

Verified 2026-11-30. The live commands ran with openai-agents 0.26.0 on Python 3.12.3, 3.13.18, and 3.14.6. record.sh made the NeMo Guardrails and Guardrails AI records on Python 3.12.3, with nemoguardrails 0.25.0, guardrails-ai 0.11.0, guardrails-ai-secrets-present 0.1.0, and detect-secrets 1.5.0. Every output block is what the command preceding it printed, with the model scripted. Llama Guard was not run: its row and its notes come from the Llama Guard 4 model card, read the same day.

Footnotes

  1. The guardrails guide lists the trade-off under execution modes. Parallel execution “provides the best latency since both start at the same time,” the guide says. When the tripwire triggers under that mode, “the agent may have already consumed tokens and executed tools before being cancelled,” it warns. The 0.2 second check in the replay is that sentence, run with a scripted model. ↩︎ Back to text

  2. The release keeps the schedule in two constants, DEPRECATED_SINCE and REMOVAL_RELEASE, set to 0.25.0 and 0.27.0. The comment over the second explains that the removal criteria are not agreed yet, so the release is a lower bound, not a date. ↩︎ Back to text

  3. The README dates the notice July 6, 2026 and gives a planned cutoff of August 25, 2026. The issue it links carries the title “SUNSET REMOTE INFERENCING AND HUB on 8/25” in capitals. Its section on hosted inference says those servers “are shut down on August 6, 2026,” and points back to a cutoff the same issue gives as August 25. ↩︎ Back to text

  4. The model card describes a safety classifier with 12 billion parameters that reads images as well as text. Its fourteenth category, Code Interpreter Abuse, carries the qualifier “text only.” Prompt attacks go elsewhere, in one line under Limitations that points to Llama Prompt Guard 2. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.