Index of every page on this site: llms.txt
All skills
kaushik-holla avatar

/langgraph-patterns

@cb7c214
Run it yourself

Canonical LangGraph 1.x patterns for typed State and reducers, conditional routers, bounded loops, interrupt/resume with Command, checkpointers (InMemory, SQLite, Postgres), runtime context for dependency injection, structured outputs, tool and MCP wiring, create_agent with middleware, subgraphs, Send fan-out, v2 streaming, retries, and LangSmith tracing, plus a common-mistakes catalog and testing patterns. Use when designing, implementing, debugging, or upgrading any LangGraph node, router, or graph, or when migrating off deprecated APIs such as create_react_agent. Reference; not a runbook.

  • 4 files
  • 34.9 KB
  • MIT
  • Updated 4 days ago
  • GitHub
Use this Skill: https://skilld.dev/gh/kaushik-holla/agent-skills/langgraph-patterns

Nothing lands on disk. Nothing to clean up.

Fork this Skill

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

referencestesting.md

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

Testing LangGraph Graphs

Loaded on demand from the langgraph-patterns skill. Pair with the python-quality skill's references/testing-patterns.md for general pytest setup.

1. Mock the LLM at the boundary

Mock the chat model (the provider client), not your own node functions. Tests stay decoupled from your code.

from unittest.mock import MagicMock


def make_fake_clarity_model(decision: ClarityDecision) -> MagicMock:
    m = MagicMock()
    m.invoke.return_value = decision
    return m


def test_clarity_node_routes_to_research_when_clear(monkeypatch):
    fake = make_fake_clarity_model(ClarityDecision(status="clear", reason="..."))
    monkeypatch.setattr("myapp.agents.clarity.clarity_model", fake)
    out = clarity_node({"messages": [HumanMessage(content="Tell me about Acme")]})
    assert out["clarity_status"] == "clear"

For nodes that call a model directly (not structured output), GenericFakeChatModel from langchain_core.language_models.fake_chat_models gives you a real chat model that replays scripted messages, including streaming.

2. Inject fakes through runtime context

Because providers come in via context= (see SKILL.md section 11), tests need no monkeypatching:

TEST_CONTEXT = Context(search=MockSearchProvider({"Acme": {"ceo": "Jane Doe"}}), user_id="test")


def test_research_node_uses_injected_provider():
    g = build_graph()
    cfg = {"configurable": {"thread_id": "t-ctx"}}
    out = g.invoke(
        {"messages": [HumanMessage("Acme CEO?")]}, cfg, context=TEST_CONTEXT, version="v2"
    )
    assert out.value["research_findings"]["company"] == "Acme"

3. Replay a checkpointed thread

For multi-turn tests, exercise the same thread_id twice:

def test_followup_question_uses_previous_context():
    g = build_graph()
    cfg = {"configurable": {"thread_id": "test-1"}}
    g.invoke({"messages": [HumanMessage("Acme recent news?")]}, cfg, context=TEST_CONTEXT)
    out = g.invoke(
        {"messages": [HumanMessage("What about competitors?")]},
        cfg,
        context=TEST_CONTEXT,
        version="v2",
    )
    # The second turn sees the first turn's messages
    assert len(out.value["messages"]) > 2

4. Test interrupt + resume

def test_interrupt_resume_round_trip():
    g = build_graph()
    cfg = {"configurable": {"thread_id": "test-2"}}
    out = g.invoke(
        {"messages": [HumanMessage("Tell me about stocks")]},
        cfg,
        context=TEST_CONTEXT,
        version="v2",
    )
    assert out.interrupts, "graph should pause for clarification"
    assert "question" in out.interrupts[0].value
    final = g.invoke(Command(resume="Acme Corp"), cfg, context=TEST_CONTEXT, version="v2")
    assert final.value["clarity_status"] == "clear"

5. Test routers as pure functions

Routers are the cheapest, highest-value tests in a graph:

import pytest


@pytest.mark.parametrize(
    ("validation", "attempts", "expected"),
    [
        ("sufficient", 1, "synthesis"),
        ("insufficient", 1, "research"),
        ("insufficient", 3, "synthesis"),
    ],
)
def test_route_after_validator(validation, attempts, expected):
    state = {"validation_result": validation, "attempts": attempts}
    assert route_after_validator(state) == expected

6. Assert the loop is bounded

def test_validator_loop_stops_at_max_attempts(monkeypatch):
    monkeypatch.setattr("myapp.agents.validator.judge", lambda *_: "insufficient")
    g = build_graph()
    out = g.invoke(
        {"messages": [HumanMessage("Acme?")]},
        {"configurable": {"thread_id": "t-loop"}, "recursion_limit": 25},
        context=TEST_CONTEXT,
        version="v2",
    )
    assert out.value["attempts"] == MAX_ATTEMPTS

7. Determinism

  • Pin LLM temperature=0 for tests that compare structured fields.
  • For tests asserting text content, mock the LLM. Don't depend on real model output.
  • Fix seeds for any RNG in your own code (random, numpy.random).

8. Markers

Use pytest markers to separate fast/deterministic tests from slow/live ones:

@pytest.mark.live_llm
def test_real_research_returns_a_finding(): ...


@pytest.mark.eval
def test_synthesis_quality_meets_rubric(): ...

Default pytest skips these unless -m live_llm or -m eval is passed. Build the eval side with the llm-evals skill.

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 third-party reports yet.

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

Last checked against GitHub 2 days ago.

Activeupdated 4 days ago
metadata
{
  "author": "kaushik-holla",
  "version": "2.0",
  "langgraph": ">=1.2,<2"
}

README badge

README badge for kaushik-holla/agent-skills/langgraph-patterns