AI AgentsLangChain

How do you add guardrails before and after model execution?

Question 323 of 324 · Updated

On this page

Direct answer#

Use LangChain's before_model middleware hook to validate input before a model step, and after_model to validate the resulting model response before normal execution continues. Register both hooks in the middleware list of create_agent.

A guardrail is an application-defined check that accepts, rejects or routes a request or response according to a policy. It should protect an actual execution boundary, not merely tell the model to behave safely.

1. Practical example: classify support tickets#

Imagine a support assistant that assigns incoming tickets to one of three categories: billing, technical or other. It must accept only nonempty text of at most 500 characters and return exactly one approved category.

Loading diagram…

If the input is invalid, the model should not be called. If the output is invalid, the application should not use it to route a ticket.

2. Define deterministic checks#

Separate the policy from the framework so you can test it without paying for model calls.

PYTHON
class GuardrailViolation(ValueError): pass def check_input(text): if not isinstance(text, str) or not text.strip() or len(text) > 500: raise GuardrailViolation('invalid input') def check_output(text): if not isinstance(text, str) or text not in ('billing', 'technical', 'other'): raise GuardrailViolation('invalid category')

The input limit counts Python string characters, not tokens or bytes. The output check uses a strict allowlist: additional prose, unexpected categories and non-string results are rejected.

Local testing: The exact helpers passed 10 executed checks on Python 3.13.5: normal input, exactly 500 characters, oversized input, whitespace-only input, non-string input, all three permitted labels, a label with extra instructions, and a non-string result.

3. Connect the checks to LangChain#

For this narrow, tool-free, text-only classifier, use the last message at each model-stage boundary.

PYTHON
from langchain.agents import create_agent from langchain.agents.middleware import before_model, after_model from langchain_core.messages import HumanMessage, AIMessage @before_model def validate_input(state, runtime): messages = state["messages"] if not messages or not isinstance(messages[-1], HumanMessage): raise GuardrailViolation("unexpected input message") check_input(messages[-1].content) @after_model def validate_output(state, runtime): messages = state["messages"] if (not messages or not isinstance(messages[-1], AIMessage) or messages[-1].tool_calls or messages[-1].invalid_tool_calls): raise GuardrailViolation("unexpected model response") check_output(messages[-1].content) agent = create_agent( model="openai:gpt-4o-mini", tools=[], system_prompt=( "Classify the ticket. Return exactly one lowercase label: " "billing, technical, or other. No additional text." ), middleware=[validate_input, validate_output], )

The example uses exceptions to stop the invalid path. At the host boundary, handle GuardrailViolation as a controlled rejection and expose only an approved error message. Do not treat an unexpected model or provider error as an accepted classification.

The SDK integration is illustrative and unexecuted because langchain, langchain_core and langgraph are not installed locally. Confirm the exact hook signatures and message properties against the pinned release.

In a tool-enabled agent, the last message before a model call might be a ToolMessage rather than a HumanMessage. Adapt the policy to the actual stage, validate tool proposals separately, and preserve the tool-call/result protocol. Do not copy this classifier's message-type restriction into a general-purpose agent.

4. Deterministic versus model-based guardrails#

GuardrailExampleBest use
DeterministicLength check, schema, allowlistObjective rules and hard constraints
Model-basedDetect out-of-scope requests or inappropriate responsesSemantic judgments that are difficult to express as rules
CombinedValidate schema, then assess whether the answer is supported by evidenceTasks requiring both structural and semantic quality

Prefer deterministic checks for conditions that can be specified precisely. A model-based classifier can be useful for nuanced judgments, but its decision may be wrong, and it adds latency and cost. Evaluate it against labeled positive and negative examples, including attempted bypasses.

The example above verifies that a category is allowed, not that it is correct. A technical ticket incorrectly classified as billing would still pass. Evaluate classification accuracy separately.

5. What should happen after rejection?#

Choose an explicit policy: stop with a safe error, request clarification, or perform a bounded correction attempt where appropriate. Compatible middleware versions can also use declared jump_to destinations for controlled routing. A rejected tool proposal requires protocol-aware handling; never fabricate a successful tool result.

Avoid unlimited correction loops. For a security-critical guardrail that cannot complete its check, fail closed rather than treating the unknown result as permission.

6. Practical safeguards#

  • Validate the final effective model input, including any retrieved content or prompt modifications, at the appropriate boundary. A before_model check alone may not cover changes introduced by later wrappers.
  • Keep raw model output private until validation completes. If streaming is enabled, buffer content that must be checked before disclosure.
  • Enforce tool and resource authorization independently. Neither a system prompt nor a model-based guardrail grants access.
  • Test the real SDK with scripted model responses, rejected inputs, invalid output, multiple middleware components and actual delivery behavior. Log rejection categories rather than sensitive raw payloads.

Key takeaway#

Use before_model and after_model for lifecycle-based checks, with additional protection at the actual model, tool and delivery boundaries. Start with small, testable deterministic rules, add semantic validation only where needed, and ensure rejected content never becomes an accepted result.

References

  1. 1.
    LangChain guardrailsdocs.langchain.com
  2. 2.
    LangChain custom middlewaredocs.langchain.com
  3. 3.
    LangChain agentsdocs.langchain.com
  4. 4.
    LangChain API referencereference.langchain.com

Related questions

Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps