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
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
Auto-Instrumentation (Recommended)
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:
PromptGuardRunnable described in LangChain.
Protecting Tool Inputs/Outputs
Tools can be vectors for injection. Scan what goes in and what comes out withGuardClient:
Tool-Calling Agent Example
Conversational Agent with Memory
LangChain 1.x keeps conversation history in a LangGraph checkpointer, keyed bythread_id. The callback handler sends that thread_id to PromptGuard as the session id, so turns of one conversation are grouped together.
RAG Agent
Error Handling
Monitoring Agent Security
Subclass the handler to add your own logging. Callsuper() in any method you override, or the scan for that event is skipped.
Best Practices
- Use auto-instrumentation or the callback handler - Both cover every model call, including the agent’s internal reasoning steps
- Scan tool inputs and outputs that touch untrusted data - See Protecting Tool Inputs/Outputs above
- Fail gracefully - Don’t expose error details to users
- Monitor blocked requests - Track attack patterns in the dashboard
- Test with adversarial inputs - Validate protection before production
Next Steps
Python SDK
Full SDK reference
Threat Detection
Detection capabilities