Index of every page on this site: llms.txt
All skills
jeremylongshore avatar

/langchain-langgraph-basics

@0d57af8
Run it yourself

Build a correct LangGraph 1.0 StateGraph — typed TypedDict state with reducers, nodes, edges, compile, and recursion budgets — without hitting the silent-termination and state-replacement traps. Use when writing your first LangGraph StateGraph, diagnosing why a graph halted without reaching END, or picking recursion_limit. Trigger with "langgraph statgraph", "langgraph basics", "GraphRecursionError", "langgraph conditional edges".

Use this Skill: https://skilld.dev/gh/jeremylongshore/tons-of-skills-marketplace/langchain-langgraph-basics

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesconditional-edges.md

≈1.3k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Conditional Edges

add_conditional_edges is where most first-time LangGraph graphs silently break. A router function that returns a value not in path_map halts the graph without reaching END — no exception, no log, just a quiet stop (pain-catalog P56).

Signature

StateGraph.add_conditional_edges(
    source: str,
    path: Callable[[State], str | list[str] | Literal[...]],
    path_map: dict[str, str] | list[str] | None = None,
)

Four usable shapes:

Form path_map When to use
Router returns node names directly None Router returns "node_a" or "node_b" literally — fragile, easy to break on rename
Router returns keys, path_map translates {"key_a": "node_a", "key_b": "node_b"} Recommended — decouples router vocab from graph topology
Router returns a list of names (fan-out) None or dict Parallel branching via Send
Router returns a Literal-typed key {"key": "node", ...} Adds static type safety via mypy

The defensive pattern

from typing import Literal
from langgraph.graph import StateGraph, START, END

def should_continue(state: State) -> Literal["execute", "end", "retry"]:
    if state["failed_attempts"] > 3:
        return "end"
    if state["needs_retry"]:
        return "retry"
    return "execute"

builder.add_conditional_edges(
    "validator",
    should_continue,
    path_map={
        "execute": "executor",
        "retry":   "executor",  # two keys can point to same node
        "end":     END,         # ALWAYS include END as a fallback key
    },
)

Three rules that prevent P56:

  1. Type the router with Literal[...]. Mypy will flag a return "Execute" typo. Runtime errors surface at type-check time, not in production.

  2. Always include END in path_map. Even if your router never intends to return "end," having it as a valid route means unknown returns route to END instead of halting silently. If you detect an unknown return, log loudly.

  3. Assert the router return is a path_map key during dev:

    def should_continue(state: State) -> Literal["execute", "end"]:
        result = "end" if state["done"] else "execute"
        assert result in {"execute", "end"}, f"Unknown route: {result!r}"
        return result

Fan-out with Send

For parallel branching (one planner fan-outs to N executors), the router returns a list of Send objects:

from langgraph.types import Send

def dispatch(state: State) -> list[Send]:
    return [Send("executor", {"task": t}) for t in state["tasks"]]

builder.add_conditional_edges("planner", dispatch, ["executor"])

Each Send becomes one node invocation in the next superstep. This inflates superstep count linearly with fan-out — see Recursion Limits for sizing.

Testing conditional routes

Every branch of the router should have a unit test that asserts the return value is in path_map:

import pytest
from typing import get_args

PATH_MAP = {"execute": "executor", "retry": "executor", "end": END}

@pytest.mark.parametrize("state,expected", [
    ({"failed_attempts": 0, "needs_retry": False}, "execute"),
    ({"failed_attempts": 0, "needs_retry": True},  "retry"),
    ({"failed_attempts": 5, "needs_retry": False}, "end"),
])
def test_router_covers_all_paths(state, expected):
    result = should_continue(state)
    assert result == expected
    assert result in PATH_MAP, f"Router returned {result!r}, not in path_map"

One test per Literal arm. If you add a new return value to the router, the test suite fails until you extend both path_map and the parametrize list.

Common mistakes

Returning a bare string instead of a key

# BAD — "Retry" (capital R) is not in path_map
def router(state): return "Retry"  # P56 triggered

path_map=None with renamed nodes

def router(state): return "executor"  # matches a node name today

builder.add_conditional_edges("planner", router)  # no path_map

# Six months later a teammate renames "executor" to "worker".
# Router still returns "executor" — graph silently halts.

Always use path_map even when router returns match node names. The map is the contract.

Async router missing await

async def router(state): return "end"

# BAD — passing the coroutine, not the value
builder.add_conditional_edges("node", router)  # works, but must not be called as await router()

add_conditional_edges accepts both sync and async routers. Don't add await yourself — the compiled graph handles it.

References

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts2mo3 checks · Risk SAFE
  • Gen Agent Trust Hub2mo

    The skill is a comprehensive educational resource for building LangGraph 1.0 agents. It correctly implements state management, error handling, and persistence best practices without any detected security risks.

  • Socket2mo

    No alerts

  • Snyk2mo

    Risk: LOW · No issues

Signed by skilld at 0d57af8. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub yesterday.

Activeupdated 2 months ago
What it can do
Reads files Edits files Runs commands
version
2.7.0
author
Jeremy Longshore <jeremy@intentsolutions.io>
compatibility
Designed for Claude Code
All 4 allowed tools
ReadWriteEditBash(python:*)
Other metadata
tags
[
  "saas",
  "langchain",
  "langgraph",
  "python",
  "langchain-1.0",
  "statgraph"
]

README badge

README badge for jeremylongshore/tons-of-skills-marketplace/langchain-langgraph-basics