Skip to main content
This example shows how to protect LangChain agents, chains, and tool calls from prompt injection and other attacks. The samples use the LangChain 1.x agent API (create_agent) and were run against the versions pinned below.

Overview

LangChain agents are powerful but vulnerable to prompt injection through:
  • User inputs that manipulate agent behavior
  • Malicious content in retrieved documents
  • Tool outputs that contain injection payloads
PromptGuard can scan every model call the agent makes, and you can scan tool inputs and outputs yourself.

Setup

promptguard-sdk 2.4.0 is the first release whose callback handler runs under LangChain’s callback manager. The RAG example also needs langchain-chroma.

Basic Protection

The simplest approach - one line protects all LLM calls:

Callback Handler

PromptGuardCallbackHandler scans each model call’s prompt and, by default, its response. Pass it at invocation time so it sees every model call in the run:
A callback observes content but cannot rewrite it, so in enforce mode a redact decision blocks. To pass redacted text on instead, use the inline PromptGuardRunnable described in LangChain.

Protecting Tool Inputs/Outputs

Tools can be vectors for injection. Scan what goes in and what comes out with GuardClient:

Tool-Calling Agent Example

Conversational Agent with Memory

LangChain 1.x keeps conversation history in a LangGraph checkpointer, keyed by thread_id. The callback handler sends that thread_id to PromptGuard as the session id, so turns of one conversation are grouped together.

RAG Agent

Retrieved documents reach the model as tool results inside the next model call, so the input scan of that call covers them. To scan documents before they reach the agent at all, see RAG PII redaction.

Error Handling

Monitoring Agent Security

Subclass the handler to add your own logging. Call super() in any method you override, or the scan for that event is skipped.

Best Practices

  1. Use auto-instrumentation or the callback handler - Both cover every model call, including the agent’s internal reasoning steps
  2. Scan tool inputs and outputs that touch untrusted data - See Protecting Tool Inputs/Outputs above
  3. Fail gracefully - Don’t expose error details to users
  4. Monitor blocked requests - Track attack patterns in the dashboard
  5. Test with adversarial inputs - Validate protection before production

Next Steps

Python SDK

Full SDK reference

Threat Detection

Detection capabilities
Last modified on November 13, 2026