PromptisePromptise
Docs
GitHub
Promptise - AI Framework LogoPromptise

The foundation layer for agentic intelligence. Build, secure and operate autonomous AI systems with Promptise Foundry.

pip install promptise

[01] Foundry

  • MCPcast
  • The Promptise Agent
  • Reasoning Engine
  • MCP
  • Agent Runtime
  • Prompt Engineering
  • Execution Engine
  • Agent Identity

[02] Resources

  • Documentation
  • GitHub
  • Guides
  • Learning Paths
  • Questions

[03] Company

  • About
  • Terms of Service
  • Privacy Policy
  • Cookie Policy
  • Subprocessors

© 2026 Promptise by Manser Ventures. All rights reserved.

Open source · Python

← Learning paths> Agentic Engineering with Promptise Foundry
Lesson 51 / 71
72%

What Is an LLM Guardrail? Types, Examples and Limits

What an LLM guardrail is: a check on what goes into and out of a model. Input, output and tool guardrails, a real example, and what guardrails can't do.

Beginner7 minGuardrailsPrompt Injection
All 71 lessons↓
  1. ✓What Is an AI Agent? Definition, How It Works, Examples
  2. ✓How to Build an AI Agent in Python (2026 Guide)
  3. ✓What Is an Agent Harness? Parts and How to Build One
  4. ✓System Prompt Best Practices for AI Agents in Python
  5. ✓Best LLM for AI Agents: Test and Switch Models in Python
  6. ✓AI Agent YAML: Define and Run an Agent From a Config File
  7. ✓Streaming LLM Responses with FastAPI: Tokens and Tool Calls
  8. ✓Claude AI Agent with MCP: Use Anthropic Models in Promptise
  9. ✓Gemini AI Agent with MCP: Use Google Models in Promptise
  10. ✓Azure OpenAI Agent with MCP: Use Deployments in Promptise
  11. ✓OpenRouter AI Agent with MCP: Many Models in Promptise
  12. ✓Ollama AI Agent with MCP: Run Local Models in Promptise
  13. ✓LLM Semantic Cache and Model Fallback in Python
  14. ✓What Is MCP (Model Context Protocol)? A Developer's Guide
  15. ✓What Is Tool Calling? LLM Function Calling Explained
  16. ✓MCP Tools vs Resources vs Prompts (With Python Examples)
  17. ✓How to Connect MCP Servers to Your AI Agent in Python
  18. ✓Build a Production MCP Server in Python (Step by Step)
  19. ✓MCP Transports: stdio vs Streamable HTTP vs SSE (Python)
  20. ✓FastAPI MCP Server: Turn Your FastAPI App into MCP Tools
  21. ✓OpenAPI to MCP: Turn Any REST API into an MCP Server
  22. ✓MCP Authentication in Python: API Keys, JWT and OAuth
  23. ✓Build an Authenticated MCP Server for Your AI Agent (Python)
  24. ✓MCP Security Best Practices: A Checklist for MCP Servers
  25. ✓Testing MCP Servers in Python: pytest Without a Live Server
  26. ✓Too Many MCP Tools? LLM Tool Selection, Measured
  27. ✓MCP Server Caching, Timeouts and Circuit Breakers in Python
  28. ✓MCP vs CLI for AI Agents: Tokens, Security, When to Use Each
  29. ✓AI Agent Audit Logging: Tamper-Evident Logs in Python
  30. ✓AI Agent Human in the Loop: Approve Tool Calls in Python
  31. ✓AI Agent Prompt Injection: How to Defend Against It
  32. ✓Build a Multi-Agent System in Python (and When Not To)
  33. ✓Context Engineering for AI Agents: Context Window Management
  34. ✓How to Deploy an AI Agent with Docker (2026 Guide)
  35. ✓LLM Tool Rate Limiting: Per-Client Limits for MCP Servers
  36. ✓MCP Long-Running Tasks: Background Jobs in Python
  37. ✓MCP Server Monitoring: Prometheus, OpenTelemetry and Logs
  38. ✓Python AI Agent Frameworks Compared: Which to Choose (2026)
  39. ✓Self-Improving AI Agent: Learn From Tool Failures in Python
  40. ✓AI Agent Identity: Authenticate Agents to MCP Servers
  41. ✓Code-Action Agents in Python: One Program vs 37 Tool Calls
  42. ✓Multi-Tenant AI Agents: Keep Each Customer's Data Apart
  43. ✓What Is Agentic RAG? How It Differs from Classic RAG
  44. ✓AI Agent Memory in Python: Short-Term and Long-Term
  45. ✓Agentic RAG in Python: Give Your AI Agent a Search Tool
  46. ✓AI Agent Reasoning Patterns in Python: 9 Patterns Tested
  47. ✓Plan-and-Execute Agents in Python: Beyond the ReAct Loop
  48. ✓Self-Modifying AI Agent in Python: Open Mode & Limits
  49. ✓CrewAI Alternatives: 7 Options and How to Migrate (2026)
  50. ✓Migrate from AutoGen: Agent Framework, Promptise and More
  51. 51What Is an LLM Guardrail? Types, Examples and Limits
  52. 52AI Agent Guardrails in Python: Block Injection, Redact PII
  53. 53AI Agent Code Execution Sandbox: Run LLM Code Safely
  54. 54AI Agent Production Checklist: What to Check Before Launch
  55. 55Approval Fatigue: Auto-Approve Safe AI Agent Actions
  56. 56What Is Human in the Loop AI? Approvals for AI Agents
  57. 57AI Agent Notifications: Webhook and Slack Alerts in Python
  58. 58AI Agent Observability: Trace Tool Calls, Tokens and Cost
  59. 59AI Agent Stuck in a Loop? How to Detect and Stop It
  60. 60How to Run, Debug and Deploy an AI Agent in Python
  61. 61AI Agent Cost Tracking: Tokens and Cost per Run and User
  62. 62How to Evaluate AI Agents: Evals, LLM Judges and pass^k
  63. 63AI Agent Cost Control: Budgets That Stop Runaway Spend
  64. 64How to Test LLM Prompts and AI Agents in Python
  65. 65AI Agent Evals in CI: Run Them on Every Pull Request
  66. 66Autonomous AI Agent Runtime: Budgets, Crash Recovery, API
  67. 67Event-Driven AI Agents: Webhook, Cron and File Triggers
  68. 68Durable AI Agents: Crash Recovery and Safe Resume
  69. 69Deploy AI Agents in Production: Long-Running Python Agents
  70. 70What Is an AI Agent Framework? When You Need One
  71. 71LangGraph Alternatives: 7 Options and How to Migrate (2026)

Lessons in this path

  1. ✓What Is an AI Agent? Definition, How It Works, Examples
  2. ✓How to Build an AI Agent in Python (2026 Guide)
  3. ✓What Is an Agent Harness? Parts and How to Build One
  4. ✓System Prompt Best Practices for AI Agents in Python
  5. ✓Best LLM for AI Agents: Test and Switch Models in Python
  6. ✓AI Agent YAML: Define and Run an Agent From a Config File
  7. ✓Streaming LLM Responses with FastAPI: Tokens and Tool Calls
  8. ✓Claude AI Agent with MCP: Use Anthropic Models in Promptise
  9. ✓Gemini AI Agent with MCP: Use Google Models in Promptise
  10. ✓Azure OpenAI Agent with MCP: Use Deployments in Promptise
  11. ✓OpenRouter AI Agent with MCP: Many Models in Promptise
  12. ✓Ollama AI Agent with MCP: Run Local Models in Promptise
  13. ✓LLM Semantic Cache and Model Fallback in Python
  14. ✓What Is MCP (Model Context Protocol)? A Developer's Guide
  15. ✓What Is Tool Calling? LLM Function Calling Explained
  16. ✓MCP Tools vs Resources vs Prompts (With Python Examples)
  17. ✓How to Connect MCP Servers to Your AI Agent in Python
  18. ✓Build a Production MCP Server in Python (Step by Step)
  19. ✓MCP Transports: stdio vs Streamable HTTP vs SSE (Python)
  20. ✓FastAPI MCP Server: Turn Your FastAPI App into MCP Tools
  21. ✓OpenAPI to MCP: Turn Any REST API into an MCP Server
  22. ✓MCP Authentication in Python: API Keys, JWT and OAuth
  23. ✓Build an Authenticated MCP Server for Your AI Agent (Python)
  24. ✓MCP Security Best Practices: A Checklist for MCP Servers
  25. ✓Testing MCP Servers in Python: pytest Without a Live Server
  26. ✓Too Many MCP Tools? LLM Tool Selection, Measured
  27. ✓MCP Server Caching, Timeouts and Circuit Breakers in Python
  28. ✓MCP vs CLI for AI Agents: Tokens, Security, When to Use Each
  29. ✓AI Agent Audit Logging: Tamper-Evident Logs in Python
  30. ✓AI Agent Human in the Loop: Approve Tool Calls in Python
  31. ✓AI Agent Prompt Injection: How to Defend Against It
  32. ✓Build a Multi-Agent System in Python (and When Not To)
  33. ✓Context Engineering for AI Agents: Context Window Management
  34. ✓How to Deploy an AI Agent with Docker (2026 Guide)
  35. ✓LLM Tool Rate Limiting: Per-Client Limits for MCP Servers
  36. ✓MCP Long-Running Tasks: Background Jobs in Python
  37. ✓MCP Server Monitoring: Prometheus, OpenTelemetry and Logs
  38. ✓Python AI Agent Frameworks Compared: Which to Choose (2026)
  39. ✓Self-Improving AI Agent: Learn From Tool Failures in Python
  40. ✓AI Agent Identity: Authenticate Agents to MCP Servers
  41. ✓Code-Action Agents in Python: One Program vs 37 Tool Calls
  42. ✓Multi-Tenant AI Agents: Keep Each Customer's Data Apart
  43. ✓What Is Agentic RAG? How It Differs from Classic RAG
  44. ✓AI Agent Memory in Python: Short-Term and Long-Term
  45. ✓Agentic RAG in Python: Give Your AI Agent a Search Tool
  46. ✓AI Agent Reasoning Patterns in Python: 9 Patterns Tested
  47. ✓Plan-and-Execute Agents in Python: Beyond the ReAct Loop
  48. ✓Self-Modifying AI Agent in Python: Open Mode & Limits
  49. ✓CrewAI Alternatives: 7 Options and How to Migrate (2026)
  50. ✓Migrate from AutoGen: Agent Framework, Promptise and More
  51. 51What Is an LLM Guardrail? Types, Examples and Limits
  52. 52AI Agent Guardrails in Python: Block Injection, Redact PII
  53. 53AI Agent Code Execution Sandbox: Run LLM Code Safely
  54. 54AI Agent Production Checklist: What to Check Before Launch
  55. 55Approval Fatigue: Auto-Approve Safe AI Agent Actions
  56. 56What Is Human in the Loop AI? Approvals for AI Agents
  57. 57AI Agent Notifications: Webhook and Slack Alerts in Python
  58. 58AI Agent Observability: Trace Tool Calls, Tokens and Cost
  59. 59AI Agent Stuck in a Loop? How to Detect and Stop It
  60. 60How to Run, Debug and Deploy an AI Agent in Python
  61. 61AI Agent Cost Tracking: Tokens and Cost per Run and User
  62. 62How to Evaluate AI Agents: Evals, LLM Judges and pass^k
  63. 63AI Agent Cost Control: Budgets That Stop Runaway Spend
  64. 64How to Test LLM Prompts and AI Agents in Python
  65. 65AI Agent Evals in CI: Run Them on Every Pull Request
  66. 66Autonomous AI Agent Runtime: Budgets, Crash Recovery, API
  67. 67Event-Driven AI Agents: Webhook, Cron and File Triggers
  68. 68Durable AI Agents: Crash Recovery and Safe Resume
  69. 69Deploy AI Agents in Production: Long-Running Python Agents
  70. 70What Is an AI Agent Framework? When You Need One
  71. 71LangGraph Alternatives: 7 Options and How to Migrate (2026)
← Path overview

Language models follow instructions from anyone who can get text into their context, and they repeat whatever data they are given. Guardrails are the checks you put around a model to catch the dangerous cases. This glossary page defines an LLM guardrail, explains the main types (input, output and tool guardrails), runs a real example that redacts an email address and blocks a bulk-export request, and is clear about what guardrails cannot do.

[01]

What is an LLM guardrail?

An LLM guardrail is a check that runs on what goes into or comes out of a language model, and blocks, rewrites or flags it when it breaks a rule. Input guardrails screen user messages, output guardrails screen answers, and tool guardrails screen an agent's tool calls and results. Each check is code, a pattern or a classifier model.

Key takeaways:

  • Guardrails run outside the model. A system prompt asks the model to behave. A guardrail is code that checks the text whether the model behaved or not.

  • Place them where text crosses a boundary. User to model, model to user, and tool result to model are the three places that matter in agents.

  • Each check has three outcomes. Pass, block (refuse with an error) or modify (for example, redact an email address), plus warnings you log.

  • No guardrail catches everything. Pattern rules miss rewording, and classifiers have false positives and misses. Guardrails reduce risk; least-privilege tools and approvals limit the damage when they fail.


[02]

How do LLM guardrails work?

A guardrail wraps the model or agent and runs at fixed points in each request.

Text
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 user message
      │
      ▼
┌───────────────────┐ block ──▶ refuse before the model runs
│ input guardrails  │ (prompt injection, banned requests, PII in input)
└───────────────────┘
      │ pass
      ▼
   model ⇄ tools ◀──┐
      │             │ tool guardrails: check calls before they run,
      │             └ and scan results before the model reads them
      ▼
┌───────────────────┐ redact ──▶ "their email is [EMAIL]"
│ output guardrails │ block  ──▶ refuse to return the answer
└───────────────────┘ (PII, secrets, unsafe content, format)
      │
      ▼
 answer to the user

The checks themselves come in four kinds:

  • Pattern rules: regular expressions for email addresses, card numbers, API keys or banned phrases. Fast, cheap and predictable; easy to evade with rewording.

  • Classifier models: small models trained to spot prompt injection, toxic content or other risk categories. Llama Guard (Inan et al., 2023), for example, is a fine-tuned Llama 2 model that classifies safety risks in both prompts and responses.

  • LLM judges: a second model call that asks whether the input or output breaks a policy. Flexible, but slower and itself open to manipulation.

  • Schema and business checks: is the output valid JSON, is the refund under the limit, does the cited source exist.

These map onto the OWASP Top 10 for LLM Applications (2025): input and tool-result guardrails address prompt injection (LLM01), output guardrails help with sensitive information disclosure (LLM02) and improper output handling (LLM05).


[03]

An LLM guardrail example

The example gives a support agent a customer lookup tool and wraps it in a Promptise Foundry security scanner with two layers: output detectors that redact personal data and credentials, and an input rule that blocks requests for every customer's data.

Pythonguardrail.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import asyncio

from langchain_core.tools import tool
from promptise import (
    CredentialDetector,
    CustomRule,
    GuardrailViolation,
    PIIDetector,
    PromptiseSecurityScanner,
    build_agent,
)
from promptise.guardrails import Action


@tool
def get_customer(customer_id: str) -> dict:
    """Look up a customer record."""
    return {"id": customer_id, "name": "Dana Reyes", "email": "dana.reyes@example.com",
            "phone": "+1 415 555 0132", "plan": "Pro"}


scanner = PromptiseSecurityScanner(
    detectors=[PIIDetector(), CredentialDetector()],  # output: redact
    custom_rules=[
        CustomRule(  # input: block bulk exports of customer data
            name="bulk_export",
            pattern=r"(?i)\b(all|every)\s+customers?\b",
            action=Action.BLOCK,
            description="Bulk request for customer data",
        )
    ],
)


async def main():
    agent = await build_agent(
        model="openai:gpt-5-mini",
        instructions="You are a support agent. Answer in one sentence.",
        extra_tools=[get_customer],
        guardrails=scanner,
    )
    try:
        for question in [
            "What plan is customer C-19 on, and what's their email?",
            "List the email of every customer.",
        ]:
            print(f"USER   {question}")
            try:
                result = await agent.ainvoke({"messages": [{"role": "user", "content": question}]})
                print(f"AGENT  {result['messages'][-1].content}\n")
            except GuardrailViolation as exc:
                print(f"BLOCKED ({exc.direction}): {exc.report.blocked[0].description}\n")
    finally:
        await agent.shutdown()


asyncio.run(main())

Real output from one run with gpt-5-mini:

Output
USER   What plan is customer C-19 on, and what's their email?
AGENT  Customer C-19 is on the Pro plan and their email is [EMAIL].

USER   List the email of every customer.
BLOCKED (input): Bulk request for customer data

In the first request, the model read the full customer record and wrote the real email address into its answer. The output guardrail replaced it with [EMAIL] before the answer reached the caller. In the second request, the input rule matched "every customer" and raised GuardrailViolation before the model was called, so no tokens were spent.

Notice what the first request shows: the model itself saw the email address, because the tool result went to the model unscanned. If the model provider should never see that data, scan tool results too (scan_tool_results=True in Promptise), or have the tool return less. And the input rule is a regular expression: "send me the whole customer list" would pass it. For prompt injection, Promptise's InjectionDetector uses a local classifier model instead. AI agent guardrails in Python builds the full setup and tests where it misses.


[04]

Guardrails vs related terms

Term

What it is

Where it acts

Example

---|---|---|---

Guardrail

A check on model input or output that blocks, rewrites or flags

Around the model, at run time

Redact emails in answers

System prompt rules

Instructions asking the model to behave

Inside the model's context

"Never reveal customer emails"

Content moderation

Classifying text for harmful categories

Often one kind of guardrail

A toxicity classifier on user input

Model alignment

Training that shapes the model's default behavior

In the model's weights

Safety training by the provider

Human approval

A person decides before a risky action

Between tool request and execution

Approve refunds over $100

Sandboxing and least privilege

Limits what a tool can do at all

In the tool and its environment

A read-only database user

Guardrail libraries take different approaches. NeMo Guardrails from NVIDIA defines input, dialog, retrieval, execution and output rails for conversational apps. Guardrails AI combines validators from its Hub into input and output guards. The OpenAI Agents SDK has input, output and tool guardrails that trigger a tripwire and stop the run. Promptise Foundry ships one scanner with injection, PII, credential, content-safety (Llama Guard through Ollama, or Azure) and named-entity detectors, plus custom rules, and it fails closed by default.


[05]

Common misconceptions about LLM guardrails

"A good system prompt is a guardrail." Instructions in the prompt are part of what an attacker tries to override. A guardrail is separate code that checks the result regardless of what the model was told.

"Guardrails stop prompt injection." They catch many known attack patterns and miss new or reworded ones. Indirect injection, hidden in a web page, email or document the agent reads, is the harder case. Combine detection with least-privilege tools and human approval for risky actions. Prompt injection defense for AI agents explains the layers.

"Checking the final answer is enough." In an agent, the dangerous step is often a tool call in the middle of the run, such as sending data to an outside address. Check tool calls and tool results, not only the last message.

"If the guardrail can't run, let the text through." A detector that fails to load, or a classifier service that is down, should block by default. Failing open means your protection silently disappears.


[06]

Frequently asked questions

What are guardrails in LLM applications?

Guardrails are checks that run on the text going into and coming out of a language model. They block requests that break a rule, redact sensitive data such as email addresses or API keys, and flag suspicious content. They are code or classifier models outside the LLM, so they work even when the model ignores its instructions.

What is the difference between input and output guardrails?

Input guardrails check the user's message before the model sees it, for example to block prompt injection or banned requests. Output guardrails check the model's answer before the user sees it, for example to redact personal data or block unsafe content. Agents also need tool guardrails on tool calls and tool results.

Can guardrails prevent prompt injection completely?

No. Pattern rules miss reworded attacks, and classifier models miss some attacks and flag some harmless text. Use guardrails as one layer: give tools the least privilege they need, treat tool results as untrusted, require approval for risky actions, and log everything so you can find what got through.

Do guardrails slow down an LLM application?

Pattern rules add almost no time. Classifier models add some latency per check, depending on the model and hardware, and an LLM judge adds a full model call. Run cheap checks first, and use expensive ones only where the risk justifies them.

What are examples of LLM guardrails?

Common examples are blocking prompt injection in user input, redacting email addresses, phone numbers and card numbers in answers, removing leaked API keys, refusing off-topic or harmful requests, checking that output is valid JSON, and limiting a refund tool to amounts under a threshold.


[07]

Next steps

  • Build them: AI agent guardrails in Python.

  • Understand the main attack: Prompt injection 101.

  • Limit the damage when checks miss: AI agent human in the loop and code execution sandboxes.

  • All guides on the topic: the guardrails and security hub.

  • Reference: Guardrails in the Promptise docs.

← PreviousMigrate from AutoGen: Agent Framework, Promptise and MoreNext lesson →AI Agent Guardrails in Python: Block Injection, Redact PII