The following state machine defines a collaborative coding agent that loops until automated unit tests pass.
agents/swarm_graph.py (python)
from typing import TypedDict, Annotated, Sequence
import operator
from langgraph.graph import StateGraph, END
from langchain_core.messages import BaseMessage, HumanMessage
class AgentState(TypedDict):
messages: Annotated[Sequence[BaseMessage], operator.add]
code_snippet: str
compiler_errors: list[str]
iteration_count: int
is_approved: bool
def engineer_node(state: AgentState) -> dict:
# Generates or fixes code based on compiler feedback
prompt = f"Fix these errors: {state['compiler_errors']}" if state['compiler_errors'] else "Write code"
# LLM code invocation logic...
return {"code_snippet": "def calculate_tax(rev): return rev * 0.15", "iteration_count": state['iteration_count'] + 1}
def tester_node(state: AgentState) -> dict:
# Runs deterministic AST validation & pytest suite
errors = []
if "0.15" not in state['code_snippet']:
errors.append("Tax rate constant mismatch")
return {"compiler_errors": errors, "is_approved": len(errors) == 0}
def should_continue(state: AgentState) -> str:
if state["is_approved"] or state["iteration_count"] >= 3:
return END
return "engineer"
workflow = StateGraph(AgentState)
workflow.add_node("engineer", engineer_node)
workflow.add_node("tester", tester_node)
workflow.set_entry_point("engineer")
workflow.add_edge("engineer", "tester")
workflow.add_conditional_edges("tester", should_continue)
app = workflow.compile()