/loxihart-ai:building-langgraph-agentsfrom loxihart-ai
Builds stateful AI agents using LangGraph — the graph-based state machine framework for agents with complex conditional flows, retry loops, error recovery, and built-in HITL checkpoints. Covers when to choose LangGraph over LangChain or CrewAI, core concepts (StateGraph, TypedDict state, nodes, edges, conditional edges, reducers, checkpointers), and implementation patterns for production agent workflows. Use when building agents with complex branching logic, designing agents that need to loop until a condition is met, implementing state machines for agent workflows, adding error recovery to agent loops, building agents that need to pause for human approval at specific graph nodes, or migrating from sequential LangChain agents to stateful LangGraph agents. Also triggers on: LangGraph, StateGraph, stateful agent, conditional agent, agent loop, graph-based agent, agent branching, LangGraph HITL, agent checkpointer.
Ships in loxihart-ai. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
LangGraph is a state machine framework for agents. It's the right choice when your agent needs explicit control over what happens next at each step.
Choose LangGraph over LangChain (sequential) or CrewAI (role-based) when:
The central object. Nodes process state; edges define what runs next.
from langgraph.graph import StateGraph, END
from typing import TypedDict, Annotated
import operator
# 1. Define your state schema
class AgentState(TypedDict):
messages: Annotated[list, operator.add] # reducer: new messages append
task: str
tools_called: Annotated[list, operator.add]
outcome: str | None
error: str | None
retry_count: int
# 2. Create the graph
graph = StateGraph(AgentState)
Functions that take state and return partial state updates.
async def call_model(state: AgentState) -> dict:
response = await llm.ainvoke(state["messages"])
return {"messages": [response]}
async def execute_tool(state: AgentState) -> dict:
# Extract tool call from last message
last_msg = state["messages"][-1]
tool_name = last_msg.tool_calls[0]["name"]
tool_args = last_msg.tool_calls[0]["args"]
try:
result = await tools_map[tool_name].ainvoke(tool_args)
return {
"messages": [ToolMessage(content=str(result), tool_call_id=last_msg.tool_calls[0]["id"])],
"tools_called": [tool_name]
}
except Exception as e:
return {"error": str(e), "messages": [...]}
# Add to graph
graph.add_node("call_model", call_model)
graph.add_node("execute_tool", execute_tool)
The key LangGraph primitive. Route based on state.
def should_continue(state: AgentState) -> str:
last_msg = state["messages"][-1]
# Agent requested a tool call
if hasattr(last_msg, "tool_calls") and last_msg.tool_calls:
return "execute_tool"
# Error needs retry (max 3 attempts)
if state.get("error") and state.get("retry_count", 0) < 3:
return "retry"
# Max retries exceeded
if state.get("retry_count", 0) >= 3:
return "escalate"
# Natural completion
return END
graph.add_conditional_edges("call_model", should_continue, {
"execute_tool": "execute_tool",
"retry": "call_model",
"escalate": "escalate_to_human",
END: END
})
graph.add_edge("execute_tool", "call_model")
graph.set_entry_point("call_model")
LangGraph's checkpointer enables pausing mid-graph for human approval.
from langgraph.checkpoint.sqlite import SqliteSaver
# Create a persistent checkpointer
checkpointer = SqliteSaver.from_conn_string("./agent_state.db")
# For Supabase: use PostgresSaver from langgraph-checkpoint-postgres
# Compile with interrupt
app = graph.compile(
checkpointer=checkpointer,
interrupt_before=["execute_consequential_action"] # pause before this node
)
# Run until the interrupt
config = {"configurable": {"thread_id": "session-123"}}
result = await app.ainvoke(initial_state, config=config)
# At this point: execution is paused, state saved to checkpointer
# Present approval request to human (Slack, email, Base44 panel)
# On human approval: resume
final_result = await app.ainvoke(None, config=config) # None = resume from checkpoint
This integrates directly with designing-hitl-workflows — the checkpoint
persistence gives you a durable pause that survives worker restarts.
LangGraph makes retry logic explicit in the graph structure.
def route_after_error(state: AgentState) -> str:
error = state.get("error", "")
retry_count = state.get("retry_count", 0)
if retry_count >= 3:
return "escalate"
if "rate_limit" in error.lower():
return "wait_and_retry"
if "tool_not_found" in error.lower():
return "rephrase_and_retry"
return "standard_retry"
graph.add_node("handle_error", handle_error)
graph.add_node("wait_and_retry", wait_and_retry)
graph.add_node("escalate", escalate_to_human)
graph.add_conditional_edges("handle_error", route_after_error, {
"standard_retry": "call_model",
"wait_and_retry": "wait_and_retry",
"rephrase_and_retry": "call_model",
"escalate": "escalate"
})
| Pattern | Use when |
|---|---|
| LangGraph | Complex conditional flows, explicit retry/error paths, HITL at specific nodes, loop-until-done patterns |
| LangChain (sequential) | Linear chains of steps, one tool at a time, simple question-answer agents |
| CrewAI | Multiple specialized roles collaborating, each agent handles its domain |
| Raw Claude API | Maximum control, no framework overhead, simple tool-use patterns |
You can mix: use CrewAI for role-based coordination, implement each agent's internal logic as a LangGraph state machine.
managing-agent-context)instrumenting-agent-telemetry)What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub krosebrook/loxihart-skills --plugin loxihart-ai37 skills in this plugin
/ai-agents-workflowBuilds and implements AI agents, automation workflows, and tool integrations — MCP servers (2025 async, OAuth, stateless spec), LangChain and CrewAI agents, multi-LLM orchestration, and no-code platforms. Use when the user mentions: MCP server, build an agent, tool integration, API orchestration, multi-LLM routing, OAuth flow, webhook, connect services, deploy a workflow, integrate external APIs. Not for conceptual architecture overviews (use orchestrating-ai- agents), not for production n8n incident ops (use operating-n8n-production), and not for pure no-code platform wiring (use workflow-automation).
/ai-solution-architectureDesign pre-sales technical architectures for AI/ML solutions targeting B2B enterprise clients. Use when scoping AI implementations, designing reference architectures, mapping integration patterns, estimating infrastructure requirements, or preparing technical proposals. Triggers on solution design, AI architecture, technical scoping, integration mapping, infrastructure sizing, pre-sales engineering for AI projects./applying-adversarial-reviewApplies Kyle's adversarial review methodology to consequential outputs. Forces every recommendation, audit, plan, or claim through three checks before shipping: a CLAIMS / COUNTEREXAMPLE / CONTRADICTIONS footer, [SOURCED] vs [GENERATED] provenance labeling, and an agreement-streak flag at three consecutive consequential agreements. Use when finishing an audit, writing a recommendation, delivering a plan, drafting a decision memo, or producing any high-stakes deliverable. Also triggers when explicitly asked to pressure-test, stress-test, steelman, play devil's advocate, fight an idea, or check for blind spots. Triggers on: adversarial review, anti-sycophancy, claims footer, stress test this, steelman this, pressure test, devil's advocate, am I missing anything, what could go wrong, sourced vs generated, agreement streak, push back on this, where am I wrong, review this PR, pull request review, code review, PR feedback.
Other plugins' skills for the same job