LangGraph Agent Orchestration
Learn how to build sophisticated, stateful agents using RecoAgent's LangGraph integration. This tutorial covers the complete agent workflow from retrieval to answering with error handling and escalation.
What You'll Learn
- How to create a stateful agent with LangGraph
- Building multi-step workflows with conditional logic
- Implementing error handling and retry mechanisms
- Using tools and escalation in agent workflows
- Monitoring agent execution with observability
Prerequisites
- Basic understanding of LangGraph concepts
- Python 3.8+ installed
- RecoAgent installed:
pip install recoagent
LangGraph Architecture Overview
Step 1: Understanding the Agent State
RecoAgent uses a comprehensive state machine that tracks the entire conversation flow:
from packages.agents import AgentState, AgentConfig
from typing import Dict, Any
# The AgentState tracks everything during execution
state_example = {
"messages": [], # Chat history
"query": "How do I deploy to production?",
"retrieved_docs": [], # Documents from retrieval
"reranked_docs": [], # Reranked results
"plan": "I need to find deployment documentation", # Agent's plan
"action": "retrieve_docs", # Current action
"answer": None, # Final answer
"error": None, # Any errors
"metadata": {}, # Additional context
"step_count": 0, # Execution steps
"max_steps": 5, # Maximum allowed steps
"cost_tracker": {}, # Cost monitoring
"latency_tracker": {} # Performance tracking
}
Visual State Transitions
Let's see how state evolves through a real query:
Key Insight: Each node reads from and writes to the shared state, creating a traceable execution history!
Step 2: Creating Your First Agent
Let's build a simple RAG agent that can retrieve information and answer questions:
import os
from packages.agents import RAGAgentGraph, AgentConfig, ToolRegistry
from packages.rag import HybridRetriever, VectorRetriever, BM25Retriever
from packages.rag.stores import OpenSearchStore
# Configure the agent
config = AgentConfig(
model_name="gpt-4",
temperature=0.1,
max_tokens=1000,
max_steps=5,
cost_limit=0.10,
safety_enabled=True
)
# Set up vector store
vector_store = OpenSearchStore(
endpoint="http://localhost:9200",
index_name="knowledge_base"
)
# Create retrievers
vector_retriever = VectorRetriever(vector_store=vector_store)
bm25_retriever = BM25Retriever(vector_store=vector_store)
hybrid_retriever = HybridRetriever(
vector_retriever=vector_retriever,
bm25_retriever=bm25_retriever,
alpha=0.7 # 70% vector, 30% BM25
)
# Create tool registry
tool_registry = ToolRegistry()
tool_registry.register_retrieval_tool(hybrid_retriever)
# Create the agent
agent = RAGAgentGraph(
config=config,
tool_registry=tool_registry
)
print("Agent created successfully!")
Step 3: Running the Agent
Now let's run the agent with a sample query:
# Run the agent
query = "What are the best practices for deploying RecoAgent to production?"
result = await agent.run(query, user_id="tutorial_user")
print(f"Query: {result['query']}")
print(f"Answer: {result['answer']}")
print(f"Cost: ${result['cost']:.4f}")
print(f"Latency: {result['latency_ms']:.0f}ms")
print(f"Steps taken: {result['metadata']['step_count']}")
Step 4: Understanding the Workflow
The agent follows this state machine flow:
Real-World Scenario: Multi-Step Research Query
Let's trace a complex query through the entire agent lifecycle:
Query: "What are the security best practices for deploying RecoAgent with sensitive healthcare data?"