Phase 4: Agent Orchestration in Client Environments · 60 min · Python · LangGraph · LangSmith
The Concept
StateGraphs with LangGraph
from langgraph.graph import StateGraph, END
from typing import TypedDict, Annotated, List
from langgraph.graph.message import add_messages
from langchain_core.messages import HumanMessage, AIMessage
import operator
# Step 1: Define the State — the single source of truth for the agent
class AgentState(TypedDict):
messages: Annotated[List, add_messages] # Conversation history
user_id: str # Thread-level state
retrieved_context: List[str] # RAG context
pending_approval: bool # Human-in-the-loop gate
tool_calls_made: int # Step budget tracking
max_steps: int # Step budget limit
# Step 2: Define nodes — each node is a function that takes state, returns state updates
def retrieve_context(state: AgentState) -> dict:
"""RAG retrieval node: fetch relevant context for the user's query."""
query = state["messages"][-1].content
# In practice: call your vector DB here
context = rag_system.retrieve(query, top_k=5)
return {"retrieved_context": [c["content"] for c in context]}
def generate_answer(state: AgentState) -> dict:
"""Generation node: produce an answer using retrieved context."""
context = "\n\n".join(state["retrieved_context"])
query = state["messages"][-1].content
prompt = f"""Answer the question based on the context. If the context doesn't contain the answer, say "I don't have that information."
Context:
{context}
Question: {query}"""
response = llm.invoke([HumanMessage(content=prompt)])
return {"messages": [response], "tool_calls_made": state["tool_calls_made"] + 1}
def check_safety(state: AgentState) -> str:
"""Conditional routing: decide whether to gate the action for human review."""
last_message = state["messages"][-1].content.lower()
# Gate actions that are irreversible or high-cost
dangerous_keywords = ["delete", "transfer", "approve", "send email", "execute"]
if any(kw in last_message for kw in dangerous_keywords):
return "request_approval"
return "generate_answer"
def request_approval(state: AgentState) -> dict:
"""Human-in-the-loop gate: pause execution and wait for approval."""
return {"pending_approval": True}
# Step 3: Build the StateGraph
workflow = StateGraph(AgentState)
# Add nodes
workflow.add_node("retrieve", retrieve_context)
workflow.add_node("generate", generate_answer)
workflow.add_node("approval_gate", request_approval)
# Set entry point
workflow.set_entry_point("retrieve")
# Add edges with conditional routing
workflow.add_conditional_edges(
"retrieve",
check_safety,
{
"request_approval": "approval_gate",
"generate_answer": "generate",
}
)
# After approval gate, go to generate (if approved) or END (if rejected)
workflow.add_conditional_edges(
"approval_gate",
lambda state: "generate" if not state.get("pending_approval") else END,
)
# After generation, end
workflow.add_edge("generate", END)
# Step 4: Compile with checkpointing for crash recovery
from langgraph.checkpoint.memory import MemorySaver
checkpointer = MemorySaver()
app = workflow.compile(checkpointer=checkpointer)
# Step 5: Run with thread-level state (each user session gets its own thread)
config = {"configurable": {"thread_id": "user_123_session_1"}}
result = app.invoke(
{
"messages": [HumanMessage(content="What is our Q3 revenue?")],
"user_id": "user_123",
"tool_calls_made": 0,
"max_steps": 10,
},
config=config,
)
print(result["messages"][-1].content)
# → "Q3 2025 revenue was $12.5M, up 15% YoY based on the retrieved financial report."
Managing enterprise state
# Thread-level state: each user session gets isolated state
# Checkpointing: state is persisted after every node, enabling crash recovery
from langgraph.checkpoint.postgres import PostgresSaver
from psycopg_pool import ConnectionPool
# Production: use Postgres-backed checkpointing (not in-memory)
pool = ConnectionPool("postgresql://.../agent_state")
checkpointer = PostgresSaver(pool)
app = workflow.compile(checkpointer=checkpointer)
# Thread 1: User A's session
config_a = {"configurable": {"thread_id": "user_A_session_1"}}
app.invoke({"messages": [HumanMessage(content="What is our revenue?")]}, config=config_a)
# Thread 2: User B's session (completely isolated)
config_b = {"configurable": {"thread_id": "user_B_session_1"}}
app.invoke({"messages": [HumanMessage(content="What is our headcount?")]}, config=config_b)
# Resume Thread 1 after crash — state is restored from Postgres
result = app.invoke(
{"messages": [HumanMessage(content="And how does that compare to Q2?")]},
config=config_a, # Same thread_id → state is restored
)
# The agent remembers the Q3 revenue context from the previous turn
# Inspect checkpointed state for debugging
state = app.get_state(config_a)
print(state.values) # Full state at the latest checkpoint
print(state.next) # Which node executes next
Agent workflow patterns
# Pattern 1: Linear (simple Q&A)
linear_graph = StateGraph(AgentState)
linear_graph.add_node("retrieve", retrieve_context)
linear_graph.add_node("generate", generate_answer)
linear_graph.set_entry_point("retrieve")
linear_graph.add_edge("retrieve", "generate")
linear_graph.add_edge("generate", END)
# Pattern 2: Cyclic (agent loops until task is complete)
def should_continue(state: AgentState) -> str:
"""Loop until the task is done or step budget is exceeded."""
if state["tool_calls_made"] >= state["max_steps"]:
return END # Step budget exhausted — prevent infinite loops
if "TASK_COMPLETE" in state["messages"][-1].content:
return END
return "tools" # Continue executing tools
cyclic_graph = StateGraph(AgentState)
cyclic_graph.add_node("agent", agent_reasoning)
cyclic_graph.add_node("tools", execute_tools)
cyclic_graph.set_entry_point("agent")
cyclic_graph.add_conditional_edges("agent", should_continue, {"tools": "tools", END: END})
cyclic_graph.add_edge("tools", "agent") # Loop back to agent after tool execution
# Pattern 3: Dynamic routing (supervisor delegates to specialist sub-agents)
def route_to_specialist(state: AgentState) -> str:
"""Supervisor decides which sub-agent handles the query."""
query = state["messages"][-1].content.lower()
if "revenue" in query or "financial" in query:
return "finance_agent"
elif "customer" in query or "crm" in query:
return "crm_agent"
elif "ticket" in query or "incident" in query:
return "support_agent"
return "general_agent"
supervisor_graph = StateGraph(AgentState)
supervisor_graph.add_node("supervisor", supervisor_reasoning)
supervisor_graph.add_node("finance_agent", finance_agent_node)
supervisor_graph.add_node("crm_agent", crm_agent_node)
supervisor_graph.add_node("support_agent", support_agent_node)
supervisor_graph.set_entry_point("supervisor")
supervisor_graph.add_conditional_edges(
"supervisor",
route_to_specialist,
{
"finance_agent": "finance_agent",
"crm_agent": "crm_agent",
"support_agent": "support_agent",
"general_agent": END,
}
)
# All sub-agents return to supervisor for aggregation
for agent in ["finance_agent", "crm_agent", "support_agent"]:
supervisor_graph.add_edge(agent, "supervisor")
Defining tools with structured schemas
from langchain_core.tools import tool
from pydantic import BaseModel, Field
class QuerySalesforceInput(BaseModel):
"""Structured schema for Salesforce query tool."""
object_type: str = Field(description="Salesforce object: Account, Contact, Opportunity, Lead")
fields: List[str] = Field(description="Fields to retrieve")
where_clause: str = Field(description="SOQL WHERE clause, e.g. \"Industry = 'Technology'\"")
limit: int = Field(default=10, description="Max records to return")
@tool(args_schema=QuerySalesforceInput)
def query_salesforce(object_type: str, fields: List[str], where_clause: str, limit: int = 10) -> str:
"""Query Salesforce records using SOQL-like syntax.
Use this tool when you need to retrieve customer data from Salesforce.
Requires: object_type, fields, where_clause.
"""
try:
soql = f"SELECT {','.join(fields)} FROM {object_type} WHERE {where_clause} LIMIT {limit}"
result = sf_client.query(soql)
if not result["records"]:
return "No records found matching the criteria."
return str(result["records"])
except Exception as e:
return f"Tool error: {type(e).__name__}: {str(e)}" # Never crash — return error as string
@tool
def send_email(to: str, subject: str, body: str) -> str:
"""Send an email through the enterprise SMTP server.
WARNING: This is an irreversible action. Requires human approval.
"""
# In practice: this would be gated by a human-in-the-loop approval
return f"Email sent to {to} with subject '{subject}'"
# Tools are automatically converted to structured schemas for the LLM
tools = [query_salesforce, send_email]
Agent server runtime
# Agent Server architecture: API servers handle requests, queue workers execute agents
# This separation enables independent scaling and prevents long-running agents from blocking API responses
# API Server (fast, stateless): receives requests, enqueues tasks, returns task_id
# Queue Worker (slow, stateful): processes agent execution, updates status
# Conceptual architecture:
"""
┌─────────────┐ ┌───────────┐ ┌──────────────┐
│ API Server │────▶│ Task Queue│───▶│ Queue Worker │
│ (FastAPI) │ │ (Redis) │ │ (LangGraph) │
│ │◀───│ │◀───│ │
└─────────────┘ └───────────┘ └──────────────┘
│ │
│ ┌──────────────┐ │
└────────▶│ State Store │◀────────────┘
│ (Postgres) │
└──────────────┘
"""
# API server endpoint
from fastapi import FastAPI
from celery import Celery
app = FastAPI()
celery = Celery("agent_worker", broker="redis://localhost:6379")
@app.post("/agent/run")
async def run_agent(query: str, user_id: str):
"""Enqueue agent task and return task_id immediately."""
task = celery.send_task("execute_agent", args=[query, user_id])
return {"task_id": task.id, "status": "queued"}
@app.get("/agent/status/{task_id}")
async def get_status(task_id: str):
"""Check agent task status."""
result = celery.AsyncResult(task_id)
return {"status": result.status, "result": result.result if result.ready() else None}
# Queue worker (separate process, scales independently)
@celery.task
def execute_agent(query: str, user_id: str):
"""Execute the LangGraph agent — runs in queue worker, not API server."""
config = {"configurable": {"thread_id": f"{user_id}_{task_id}"}}
result = langgraph_app.invoke(
{"messages": [HumanMessage(content=query)], "user_id": user_id, "tool_calls_made": 0, "max_steps": 10},
config=config,
)
return result["messages"][-1].content
Build
Practical application
In the lab, you'll build a stateful LangGraph agent with conditional routing, Postgres-backed checkpointing, structured tool schemas, and an Agent Server runtime with FastAPI + Celery. You'll test crash recovery by killing the worker mid-execution and verifying state restoration.
Your LangGraph agent crashes mid-execution after calling a Salesforce tool. The user's request was "Update the opportunity stage for Acme Corp to Closed Won." When you restart the worker, the agent has no memory of the previous steps. What did you forget to implement, and how do you fix it?
The problem is state persistence, not error handling or timeouts. In-memory checkpointers (MemorySaver) store state in RAM — when the worker process crashes, all state is lost. Postgres-backed checkpointing (PostgresSaver) writes state to the database after every node execution, so when the worker restarts, it reads the last checkpoint from Postgres and resumes from there. The fix: replace MemorySaver() with PostgresSaver(pool), compile the graph with this checkpointer, and use a consistent thread_id (e.g., user_123_session_1) so the agent can find and restore its state. After the fix, the agent will resume after the Salesforce tool call, see that the opportunity was already updated, and proceed to the next step without re-executing the tool. Error handling and timeouts are good practices but don't solve the state loss problem.
Step 1: Set up the lab folder
In an empty folder:
npx deventure start fde-lab-04-01
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install langgraph pydantic fastapi celery
Step 2: Build it
Build a LangGraph stateful agent with StateGraph, conditional routing, checkpointing for crash recovery, and structured tool definitions.
You produce:
It should have:
- A StateGraph with at least 4 nodes and conditional routing between them
- Thread-level state management for user sessions
- Checkpointing configuration for crash recovery
- 2+ structured tool definitions with error handling and output validation
The lesson's sections "StateGraphs with LangGraph", "Managing enterprise state", "Agent workflow patterns" explain how.
Step 3: Run it
python langgraph_agents.py
It has to finish without an error. Read the output before moving on: does it show what the objective asks for?
Step 4: Check it
npx deventure verify
It checks that:
langgraph_agents.py exists, is not empty, is valid Pythonpython langgraph_agents.py finishes without an error
The first time, connect the tool to your account with a token from Settings → Command line access. When every check passes, the lab is recorded as complete.