import asyncio
from langchain.agents import AgentExecutor
from langchain.tools import Tool
from humancheck.adapters.langchain_hitl import LangChainHITLAdapter
from humancheck.database import init_db
from humancheck.config import get_config
async def create_agent_with_humancheck():
"""Create a LangChain agent with Humancheck integration."""
# Initialize Humancheck
config = get_config()
db = init_db(config.get_database_url())
await db.create_tables()
adapter = LangChainHITLAdapter(db.session)
# Define tools that require approval
tools = [
Tool(
name="execute_sql",
func=lambda query: f"SQL: {query}",
description="Execute SQL query (requires approval)"
),
Tool(
name="send_email",
func=lambda to, subject, body: f"Email sent to {to}",
description="Send email (requires approval)"
),
Tool(
name="read_file",
func=lambda path: f"File content: {path}",
description="Read file (no approval needed)"
),
]
# Wrap tool execution with Humancheck
async def execute_with_review(tool_name, tool_input):
"""Execute tool with human review."""
tool_call = {
"name": tool_name,
"arguments": tool_input,
"description": next(t.desc for t in tools if t.name == tool_name)
}
# Tools requiring approval
approval_required = ["execute_sql", "send_email"]
if tool_name in approval_required:
# Create review
review = await adapter.create_review_from_tool_call(
tool_call,
allowed_decisions=["approve", "edit", "reject"]
)
print(f"Review created (ID: {review.id})")
print(f"View in dashboard: http://localhost:8501")
# Wait for decision
decision = await adapter.handle_blocking(review.id, timeout=300)
if decision["decision_type"] == "approve":
# Execute tool
tool = next(t for t in tools if t.name == tool_name)
return tool.func(**tool_input)
elif decision["decision_type"] == "modify":
# Use modified arguments
modified_input = decision.get("args", tool_input)
tool = next(t for t in tools if t.name == tool_name)
return tool.func(**modified_input)
else:
return {"error": "Tool call rejected by reviewer"}
else:
# No approval needed
tool = next(t for t in tools if t.name == tool_name)
return tool.func(**tool_input)
# Create agent executor
agent = AgentExecutor(
tools=tools,
# ... other agent configuration
)
return agent, execute_with_review
# Usage
async def main():
agent, execute_fn = await create_agent_with_humancheck()
# Run agent
result = await agent.arun("Execute SELECT * FROM users")
print(result)
asyncio.run(main())