Independent Editorial Notice: Meta Muse (metamuse.in) is an independent publication and research laboratory. We are not owned by, operated by, affiliated with, or endorsed by Meta Platforms, Inc. All technologies evaluated here are analyzed strictly for educational, engineering, and architectural research purposes.
How to Build a Custom Multi-Agent System with LangGraph and Python: Complete Walkthrough
Publication Metadata: Meta Muse Practical Tutorial | Category: AI Tutorials / Workflow Engineering | Status: Production Draft | Difficulty: Intermediate
Tutorial Objective & What We Are Building
In this hands-on tutorial, you will build a production-ready, multi-agent software engineering team using LangGraph and Python.
The architecture consists of:
- Developer Agent: Writes Python code according to user specifications.
- Security Auditor Agent: Reviews the code for vulnerabilities and syntax errors.
- Supervisor Conditional Edge: Evaluates audit results and either cycles back to the developer with corrective feedback or routes to the output node.
- State Persistence: Uses
SqliteSaverto maintain persistent checkpoints across sessions.
Step 1: Install Dependencies
pip install --upgrade langgraph langchain-openai langchain-core pydantic
Ensure your OPENAI_API_KEY is exported in your environment:
export OPENAI_API_KEY="your-actual-api-key" Step 2: Complete Working Python Implementation
Create multi_agent_system.py:
import operator
import os
from typing import Annotated, Sequence, TypedDict
from langchain_core.messages import BaseMessage, HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI
from langgraph.checkpoint.memory import MemorySaver
from langgraph.graph import END, StateGraph
# 1. Define the Global Agent State
class AgentState(TypedDict):
messages: Annotated[Sequence[BaseMessage], operator.add]
code_solution: str
audit_feedback: str
is_approved: bool
iteration_count: int
# 2. Initialize Frontier LLM
llm = ChatOpenAI(model="gpt-4o", temperature=0)
# 3. Node 1: Developer Agent
def developer_node(state: AgentState):
iteration = state.get("iteration_count", 0) + 1
feedback = state.get("audit_feedback", "None")
prompt = [
SystemMessage(content=(
"You are a Senior Python Engineer. Write robust, typed Python code.\n"
f"Previous Audit Feedback: {feedback}"
)),
*state["messages"]
]
response = llm.invoke(prompt)
return {
"messages": [response],
"code_solution": response.content,
"iteration_count": iteration
}
# 4. Node 2: Security Auditor Agent
def auditor_node(state: AgentState):
code = state["code_solution"]
prompt = [
SystemMessage(content=(
"You are an Application Security Auditor. Inspect the provided Python code for:\n"
"- SQL injection or shell execution vulnerabilities\n"
"- Missing error handling or unvalidated inputs\n"
"If the code is secure and correct, start your response with 'STATUS: APPROVED'.\n"
"Otherwise, detail the exact vulnerabilities and required fixes."
)),
HumanMessage(content=f"Code to evaluate:\n\n{code}")
]
response = llm.invoke(prompt)
approved = "STATUS: APPROVED" in response.content.upper()
return {
"messages": [response],
"audit_feedback": response.content,
"is_approved": approved
}
# 5. Conditional Routing Logic
def route_audit_decision(state: AgentState):
if state["is_approved"]:
print(">>> [Supervisor] Code passed security audit. Terminating.")
return END
if state["iteration_count"] >= 3:
print(">>> [Supervisor] Maximum revision iterations reached. Halting.")
return END
print(">>> [Supervisor] Vulnerabilities identified. Returning to Developer.")
return "developer"
# 6. Assemble the Execution Graph
workflow = StateGraph(AgentState)
workflow.add_node("developer", developer_node)
workflow.add_node("auditor", auditor_node)
workflow.set_entry_point("developer")
workflow.add_edge("developer", "auditor")
workflow.add_conditional_edges("auditor", route_audit_decision, {
END: END,
"developer": "developer"
})
# Compile with In-Memory Checkpointer
checkpointer = MemorySaver()
app = workflow.compile(checkpointer=checkpointer)
# 7. Execute with Sample Task
if __name__ == "__main__":
config = {"configurable": {"thread_id": "session_001"}}
input_message = HumanMessage(content="Write a Python FastAPI endpoint that accepts a user_id and queries a SQLite database for their profile.")
for event in app.stream({"messages": [input_message]}, config=config):
for node_name, state_update in event.items():
print(f"\n--- Executed Node: {node_name} ---")
if "code_solution" in state_update:
print("Code generated by developer.")
if "is_approved" in state_update:
print(f"Audit Approved: {state_update['is_approved']}")
Testing & Verifying Output
Execute the script:
python multi_agent_system.py Expected Terminal Flow: - Developer generates initial endpoint code.
- Auditor checks for parameterized SQL queries vs string concatenation.
- If unparameterized string formatting was used, the auditor rejects, loops back, and the developer rewrites the endpoint with SQLAlchemy or parameterized statements.
- Second audit passes and the graph terminates cleanly.
8. Advanced Patterns: Incorporating Human-in-the-Loop Interventions
In mission-critical enterprise workflows, an autonomous agent should not commit code to production without human authorization. LangGraph provides native support for Human-in-the-Loop (HITL) via the interrupt() mechanism:
from langgraph.graph import StateGraph
def human_review_node(state: AgentState):
print("=== PENDING HUMAN REVIEW ===")
print(f"Code proposed:\n{state['code_solution']}")
# When compiled with interrupt_before, graph halts execution here
# Resumes only after human administrator delivers confirmation
return state
# Add human checkpoint node to workflow graph
workflow.add_node("human_gate", human_review_node)
workflow.add_edge("developer", "human_gate")
workflow.add_edge("human_gate", "auditor")
# Compile with interrupt flag
app = workflow.compile(
checkpointer=checkpointer,
interrupt_before=["human_gate"]
)
Resuming an Interrupted Graph Run
# Administrator inspects pending state and resumes execution
current_state = app.get_state(config)
print("Pending state:", current_state.next)
# Resume execution with human approval
app.invoke(None, config=config)
Frequently Asked Questions (RankMath Verified FAQ)
-
What is the difference between LangChain LCEL and LangGraph?
LangChain Expression Language (LCEL) is designed for linear, directed acyclic chains (A → B → C). **LangGraph** introduces cyclical state management, branching conditions, persistent memory checkpoints, and human intervention gates necessary for autonomous agents.
## Production State Management & Checkpointing with Postgres
In production environments, agent execution states cannot remain in volatile memory. If a server process restarts during a long-running multi-agent workflow, the session must resume from its last completed checkpoint.
-
When should I choose LangGraph over CrewAI?
Choose LangGraph when your multi-agent architecture requires deterministic state machines, cyclic graph topologies, fine-grained human-in-the-loop pause/resume states, and complex conditional branching. Choose CrewAI when you want rapid scaffolding of role-playing autonomous agents using predefined persona definitions.
-
How do I handle tool execution errors in LangGraph without crashing the entire graph?
Wrap tool calls in a fallback node using LangChain’s `tool.with_fallbacks()` or catch exceptions inside the tool execution logic, returning a formatted `ToolMessage` containing the error message. This allows the model to see what failed and generate a corrected parameter attempt.
-
How do I get started with this implementation?
Clone the example repository, install the verified dependencies listed in the technical specifications table, configure environment variables, and run the automated test suite.