LangChain
Integration
Use Guard.attach_langchain() to automatically connect a LangChain agent instance to AgentGuard. No modifications to the original LangChain SDK code are required.
The LangChain adapter targets the return value of create_agent(), which is a langgraph.graph.state.CompiledGraph instance.
agent = create_agent(...)
guard = Guard(...)
guard.start(...)
guard.attach_langchain(agent) # Attach the guard to the LangChain agent
Full example
Below is a complete code example after integrating the AgentGuard client. Lines marked with π© show where the client is inserted:
from langchain.agents import create_agent
from langchain.tools import tool
# π© Import the AgentGuard client SDK
from agentguard import Guard, Principal
LLM_API_KEY = "<YOUR KEY>" # Fill this manually
LLM_MODEL_NAME = "gpt-5.4-mini"
@tool
def retrieve_doc(id: int) -> str:
"""Retrieve a document by integer id."""
return f"DOC#{id}: This is a mocked document body."
@tool
def send_email_to(doc: str, addr: str) -> str:
"""Send a document to an email address."""
return f"Email has sent to {addr}: {doc}"
def build_llm():
from langchain_openai import ChatOpenAI
return ChatOpenAI(
api_key=LLM_API_KEY,
model=LLM_MODEL_NAME,
temperature=0,
)
def build_agent():
return create_agent(
model=build_llm(),
tools=[retrieve_doc, send_email_to],
system_prompt=(
"You are a zero-shot ReAct style agent. Decide which tool to use, "
"observe tool results, and continue until the user's task is complete."
),
)
def run(agent, prompt):
print("===================================")
print(f"Prompt: {prompt}")
result = agent.invoke(
{
"messages": [
{
"role": "user",
"content": prompt,
}
]
}
)
print(f"Output: {result["messages"][-1].content}")
print("===================================\n")
if __name__ == "__main__":
agent = build_agent()
# π© Load the guard client
guard = Guard(
remote_url="http://<Control Server IP>:38080", # Replace with your control server IP and port
mode="enforce",
fail_open=False,
)
# π© Create a principal for the agent
principal = Principal(
agent_id="langchain-remote-demo",
session_id="langchain-remote-session",
role="default",
trust_level=1,
)
# π© Start a session with the principal
guard.start(principal=principal, goal="langchain remote runnable host demo")
# π© Attach the guard to the LangChain agent
guard.attach_langchain(agent)
try:
run(agent, "Please retrieve document id=0 and send it to admin@example.com.")
run(agent, "Please retrieve document id=0 and send it to alice@example.com.")
finally:
# π© Close the guard
guard.close()
Dependencies
pip install langchain==1.2.18
pip install langchain-openai==1.2.1