Install langgraph, langchain-core, and pydantic to build stateful multi-agent workflows in Python.
Terminal - Install LangGraph & Core Tools
pip install langgraph langchain-core pydantic requests
from langgraph.graph import StateGraph, END
print("LangGraph module successfully loaded.")
Define shared agent state transitions using Python TypedDict and Pydantic validation schemas.
from typing import TypedDict, List, Annotated
import operator
from pydantic import BaseModel
class TaskArtifact(BaseModel):
title: str
code_content: str
verified: bool = False
class AgentState(TypedDict):
task_description: str
messages: Annotated[List[str], operator.add]
current_agent: str
code_artifact: TaskArtifact
next_step: str
Create distinct Python agent functions that inspect state, perform specialized subtasks, and update memory.
def planner_agent_node(state: dict) -> dict:
print("\n[🤖 Planner Agent] Breaking down task instructions...")
return {
"messages": [f"Plan created for: {state['task_description']}"],
"current_agent": "coder",
"next_step": "code_generation"
}
def coder_agent_node(state: dict) -> dict:
print("\n[💻 Coder Agent] Writing production Python implementation...")
generated_code = "def execute_task():\n return 'Task Accomplished'"
return {
"messages": ["Code generation complete."],
"current_agent": "tester",
"next_step": "test_verification"
}
Assemble agent nodes into a directed StateGraph and add conditional branching logic in Python.
from langgraph.graph import StateGraph, END
def build_workflow_graph():
workflow = StateGraph(dict)
workflow.add_node("planner", planner_agent_node)
workflow.add_node("coder", coder_agent_node)
workflow.set_entry_point("planner")
workflow.add_edge("planner", "coder")
return workflow.compile()
Run this complete Python script to execute the multi-agent graph from start to finish.
from agent_graph import build_workflow_graph
def run_agents():
print("=== STARTING AUTONOMOUS MULTI-AGENT WORKFLOW ===")
app = build_workflow_graph()
initial_state = {
"task_description": "Build automated threat log parser in Python",
"messages": [],
"current_agent": "planner"
}
final_state = app.invoke(initial_state)
print("=== MULTI-AGENT EXECUTION COMPLETE ===")
if __name__ == "__main__":
run_agents()
Expected Execution Output
=== STARTING AUTONOMOUS MULTI-AGENT WORKFLOW ===
[🤖 Planner Agent] Breaking down task instructions...
[💻 Coder Agent] Writing production Python implementation...
=== MULTI-AGENT EXECUTION COMPLETE ===