LangChain Integration Guide¶
Integrate ACGP with LangChain for automatic governance of chains, tools, and agents.
Overview¶
LangChain is a comprehensive framework for building LLM applications. ACGP integrates via callbacks to provide governance for tool calls and agent actions.
Installation¶
Basic Usage¶
from langchain.agents import initialize_agent, AgentType
from langchain_openai import OpenAI
from acgp_langchain import GovernedChain
from acgp import GovernanceSteward
# Your LangChain agent
llm = OpenAI(temperature=0)
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION)
# Add governance
steward = GovernanceSteward(blueprint_file="blueprint.yaml")
governed_agent = GovernedChain(agent, steward)
# Use normally - governance automatic!
result = governed_agent.run("Process this request")
Features¶
- Automatic trace generation: Extracts reasoning from agent scratchpad
- Tool call interception: Evaluates before tool execution
- ReAct pattern support: Parses Thought/Action/Observation
- Intervention handling: Raises exceptions for blocked actions
- Callback integration: Uses LangChain's callback system
Advanced Features¶
Override Blocked Actions¶
# After human approval
result = governed_agent.run_with_override(
trace_id="blocked_trace_id",
"Previously blocked query"
)
Get Governance Metrics¶
metrics = governed_agent.get_metrics()
print(f"Total interventions: {metrics['total_interventions']}")
Exception Handling¶
from acgp_langchain import InterventionError
try:
result = governed_agent.run("Risky query")
except InterventionError as e:
print(f"Action blocked: {e.message}")
print(f"Trace ID: {e.trace_id}")
Control Intervention Behavior¶
# Don't raise exceptions on interventions
governed_agent = GovernedChain(
agent,
steward,
raise_on_intervention=False # Log instead of raising
)
Using the Callback Directly¶
from acgp_langchain import ACGPCallback
# Use callback directly with any LangChain component
callback = ACGPCallback(steward, raise_on_intervention=True)
result = chain.run("Query", callbacks=[callback])
Examples¶
Example implementations available in the acgp-langchain package:
- Governed Agent: LangChain agent with ACGP governance
- Tool Interception: Automatic tool call evaluation
- ReAct Pattern: Integration with ReAct agent reasoning