[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M792BEQCJ7R1Q0PVGYRGFT90":3,"skill-same:01M792BEQCJ7R1Q0PVGYRGFT90":60},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":37,"commitSha":38,"skillDirectory":39,"forksCount":40,"repositoryHtmlUrl":41,"repositoryHomepageUrl":6,"ownerHtmlUrl":42,"ownerBlogUrl":43,"ownerDescription":44,"updatedAt":45,"install":46,"resources":59},"01M792BEQCJ7R1Q0PVGYRGFT90","langchain-langgraph-agents",null,"Build a correct LangGraph 1.0 ReAct agent with `create_react_agent` — typed tools,\nerror propagation, recursion caps, and stop conditions that actually stop. Use when\nwriting your first tool-calling agent, migrating from `AgentExecutor` \u002F `initialize_agent`,\nor diagnosing an agent that loops on vague prompts.\nTrigger with \"langgraph agent\", \"create_react_agent\", \"langgraph tool calling\",\n\"AgentExecutor migration\", \"agent loop cost\".","jukeyman\u002Fjukeyman-skills","jukeyman","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F142960420?v=4","01M78FR4Y3DHMMCBCC0GXXNB3F","RICK JEFFERSON","01M78FR4Z8RVQRAD31Y5J7V6EB",1,"MIT","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--langchain-py-pack--langchain-langgraph-agents\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: langchain-langgraph-agents\ndescription: |\n  Build a correct LangGraph 1.0 ReAct agent with `create_react_agent` — typed tools,\n  error propagation, recursion caps, and stop conditions that actually stop. Use when\n  writing your first tool-calling agent, migrating from `AgentExecutor` \u002F `initialize_agent`,\n  or diagnosing an agent that loops on vague prompts.\n  Trigger with \"langgraph agent\", \"create_react_agent\", \"langgraph tool calling\",\n  \"AgentExecutor migration\", \"agent loop cost\".\nallowed-tools: Read, Write, Edit, Bash(python:*)\nversion: 2.0.0\nlicense: MIT\nauthor: Jeremy Longshore \u003Cjeremy@intentsolutions.io>\ntags: [saas, langchain, langgraph, python, langchain-1.0, agents, tool-calling]\ncompatible-with: claude-code, codex\n---\n\n# LangChain LangGraph Agents (Python)\n\n## Overview\n\nTwo failure modes hit every team writing their first LangGraph 1.0 ReAct agent:\n\n**Loop-to-cap on vague prompts (P10).** `create_react_agent` defaults to\n`recursion_limit=25`. A prompt like \"help me with my account\" never converges —\nthe model calls a retrieval tool, gets irrelevant results, calls another tool,\nand repeats until `GraphRecursionError: Recursion limit of 25 reached without\nhitting a stop condition` fires. Cost dashboards show the damage *after* the\nfact: $5-$15 per runaway loop on Sonnet with a 3-tool agent, assuming no tool\nis itself expensive.\n\n**Silent tool errors on legacy `AgentExecutor` (P09).** The legacy executor\ndefaults `handle_parsing_errors=True` and catches tool exceptions, feeding the\nerror string back as the next observation. When the error serializes to empty\n(e.g., a `ValueError(\"\")` or an HTTP 500 with no body), the loop continues with\nno signal. The agent says \"I couldn't find the answer\" — which was actually a\nsilent crash three tool calls ago.\n\nThis skill walks through defining typed tools with `@tool` + Pydantic; building\nan agent with `create_react_agent(model, tools, checkpointer=MemorySaver())`;\ninvoking with `{\"messages\": [...]}` and a thread-scoped config; setting\n`recursion_limit` per expected agent depth (5-10 interactive, 20-30 planner);\nadding middleware for a per-session token budget; and raise-by-default error\npropagation. Pin: `langgraph >= 1.0, \u003C 2.0`, `langchain-core >= 1.0, \u003C 2.0`.\nPain-catalog anchors: P09, P10, P11, P32, P41, P42, P63.\n\n## Prerequisites\n\n- Python 3.10+\n- `langgraph >= 1.0, \u003C 2.0` and `langchain-core >= 1.0, \u003C 2.0`\n- At least one provider package: `pip install langchain-anthropic` or `langchain-openai`\n- Completed skill: `langchain-langgraph-basics` (L25) — you already know `StateGraph`,\n  `MessagesState`, and checkpointers\n- Provider API key: `ANTHROPIC_API_KEY` or `OPENAI_API_KEY`\n\n## Instructions\n\n### Step 1 — Define tools with typed schemas and short docstrings\n\n```python\nfrom typing import Annotated\nfrom pydantic import BaseModel, Field\nfrom langchain_core.tools import tool\n\nclass LookupAccountArgs(BaseModel):\n    account_id: str = Field(..., description=\"Account UUID. No email addresses.\")\n\n@tool(\"lookup_account\", args_schema=LookupAccountArgs)\ndef lookup_account(account_id: str) -> dict:\n    \"\"\"Fetch an account record by UUID. Returns status, plan, and owner email.\"\"\"\n    if not account_id:\n        raise ValueError(\"account_id is required\")  # raised → agent sees real error\n    return {\"id\": account_id, \"status\": \"active\", \"plan\": \"pro\", \"owner\": \"a@b.co\"}\n```\n\nTwo rules that catch teams off-guard:\n\n1. **Docstring is the tool description the provider sees.** Keep it under\n   **1024 chars** (P11). Anthropic truncates at ~1024; OpenAI's effective cap is\n   softer but still bites on tool descriptions over ~2KB. Long docstrings with\n   examples should move into a system prompt, not the tool description.\n2. **Raise real exceptions.** Unlike the legacy `AgentExecutor`, LangGraph's\n   `create_react_agent` does not silently swallow tool errors — the exception\n   propagates and surfaces in your observability layer. See Step 6.\n\nFor async tools, use `@tool` on an `async def` — LangGraph invokes it via\n`await`. For structured return types, annotate the return with a Pydantic model.\n\nSee [Tool Definition Patterns](references\u002Ftool-definition-patterns.md) for the\n`@tool` vs `tool()` decision, async tools, and the `args_schema` vs\nauto-inferred trade-off.\n\n### Step 2 — Build the agent with `create_react_agent`\n\n```python\nfrom langgraph.prebuilt import create_react_agent\nfrom langgraph.checkpoint.memory import MemorySaver\nfrom langchain_anthropic import ChatAnthropic\n\nmodel = ChatAnthropic(\n    model=\"claude-sonnet-4-6\",\n    temperature=0,\n    timeout=30,\n    max_retries=2,\n)\n\nagent = create_react_agent(\n    model=model,\n    tools=[lookup_account],\n    checkpointer=MemorySaver(),  # required for stateful invocations\n)\n```\n\n`create_react_agent` is the LangGraph 1.0 replacement for the removed\n`initialize_agent` factory (P41). Under the hood it builds a `StateGraph` with\na `model` node and a `ToolNode`, plus a conditional edge that routes to\n`END` when the model emits no tool calls. The `checkpointer` persists state\nper-thread — required for multi-turn conversations and for resuming after\ninterruption.\n\n### Step 3 — Invoke with a thread-scoped config\n\n```python\nconfig = {\"configurable\": {\"thread_id\": \"user-42\"}}\nresult = agent.invoke(\n    {\"messages\": [{\"role\": \"user\", \"content\": \"look up account uuid-abc\"}]},\n    config=config,\n)\nprint(result[\"messages\"][-1].content)\n```\n\nKey contracts:\n\n- **Input** is `{\"messages\": [...]}` — a list of message dicts or LangChain\n  `HumanMessage` \u002F `SystemMessage` objects. You append to this list across turns.\n- **`thread_id`** scopes the checkpointer. Reusing it resumes the conversation.\n- **Output** is the full updated state. `result[\"messages\"]` is the complete\n  message list; the final assistant message is at index `-1`.\n\n### Step 4 — Set `recursion_limit` to your expected agent depth\n\n`create_react_agent` defaults to `recursion_limit=25`. In LangGraph one\n\"recursion step\" is one node visit, and each tool round-trip is two visits\n(model node + tool node), so 25 means ~12 tool calls. For most workloads this\nis too generous and hides bugs:\n\n| Agent kind | Suggested `recursion_limit` | Rationale |\n|---|---|---|\n| Interactive chat with 1-3 tools | 5-10 | One tool call + one final answer is 3 visits. Cap low to expose loops. |\n| Task-completion (e.g., booking flow) | 10-15 | 3-5 tool calls + final answer. |\n| Planner \u002F research agent | 20-30 | Expect multiple retrieval + synthesis rounds. |\n| Multi-agent supervisor | 40+ | Coordinator + worker rounds. Budget tokens separately. |\n\nApply it on invocation, not at construction time:\n\n```python\nresult = agent.invoke(\n    {\"messages\": [...]},\n    config={\"configurable\": {\"thread_id\": \"user-42\"}, \"recursion_limit\": 10},\n)\n```\n\nWhen the limit fires, LangGraph raises `GraphRecursionError` — catch it and\nsurface a user-facing message; do not retry without a cost guard.\n\n### Step 5 — Add a per-session token budget via middleware\n\n`recursion_limit` alone does not bound cost. A single tool call that returns a\nlarge document and triggers a long model response can cost more than 10 cheap\ntool calls. Cap tokens explicitly:\n\n```python\nfrom langchain_core.callbacks import BaseCallbackHandler\n\nclass TokenBudget(BaseCallbackHandler):\n    def __init__(self, max_tokens: int = 50_000):\n        self.used = 0\n        self.max = max_tokens\n\n    def on_llm_end(self, response, **kwargs):\n        usage = getattr(response, \"llm_output\", {}).get(\"token_usage\", {}) or {}\n        self.used += usage.get(\"total_tokens\", 0)\n        if self.used > self.max:\n            raise RuntimeError(f\"Token budget exceeded: {self.used}\u002F{self.max}\")\n\nbudget = TokenBudget(max_tokens=50_000)\nresult = agent.invoke(\n    {\"messages\": [...]},\n    config={\n        \"configurable\": {\"thread_id\": \"user-42\"},\n        \"recursion_limit\": 10,\n        \"callbacks\": [budget],\n    },\n)\n```\n\nA per-session budget of 50K tokens on Sonnet is roughly $0.25 — a safe cap for\ninteractive agents. For background planners raise to 200K-500K. See\n[Loop Caps and Budgets](references\u002Floop-caps-and-budgets.md) for a\nrepeated-tool-call early-stop node and a middleware pattern that terminates on\nthe N-th identical call.\n\n### Step 6 — Propagate tool errors; do not silently swallow\n\nLangGraph's default is to raise. Legacy `AgentExecutor(handle_parsing_errors=True)`\nswallowed everything. The new defaults are safer but different:\n\n```python\n# Tool raises → the exception propagates out of agent.invoke()\ntry:\n    result = agent.invoke({\"messages\": [{\"role\": \"user\", \"content\": \"...\"}]}, config=config)\nexcept ValueError as e:\n    # Your tool's own ValueError — log + user-facing message\n    ...\n```\n\nWhen you *want* tolerant behavior (e.g., the tool is a flaky third-party API\nand you want the model to try a different approach), wrap the tool itself:\n\n```python\nfrom langchain_core.tools import tool\n\n@tool\ndef search_kb(query: str) -> str:\n    \"\"\"Search the internal knowledge base. Returns hits or a 'no results' string.\"\"\"\n    try:\n        return _real_search(query)\n    except HTTPError as e:\n        return f\"search_kb unavailable: {e.response.status_code}. Try a different query.\"\n```\n\nThe key insight: the *tool* decides to degrade gracefully by returning a string\nthe model can reason about. The *agent* never silently drops an error. See\n[Error Propagation](references\u002Ferror-propagation.md) for a custom error-handler\nnode that routes tool failures to a fallback tool.\n\n### Step 7 — Choose `create_react_agent` vs custom `StateGraph` vs legacy\n\n| Decision | Use | Why |\n|---|---|---|\n| Single agent, tool-calling loop | `create_react_agent` | Correct defaults, provider-native tool calling, smallest code surface |\n| Multi-stage pipeline (plan → execute → review) | Custom `StateGraph` | You need named nodes, explicit conditional edges, typed state |\n| Multi-agent supervisor | `create_supervisor` + workers built with `create_react_agent` | Built-in routing, per-worker checkpointing |\n| New code in 2026+ | Never use `AgentExecutor` or `initialize_agent` | Removed \u002F deprecated in 1.0 (P41); shape changes in `intermediate_steps` (P42) |\n\nFor a single forced-tool single-shot (e.g., \"always classify into one of these\nbuckets\"), skip agents entirely: use `model.bind_tools([Schema],\ntool_choice={\"type\": \"tool\", \"name\": \"Schema\"})`. But never loop a forced\n`tool_choice` (P63) — the model cannot emit `stop_reason=\"end_turn\"` under\nforced tool_choice, so the agent never terminates.\n\n## Output\n\n- Agent built with `create_react_agent(model, tools, checkpointer=MemorySaver())`\n- Tools defined with `@tool` + Pydantic `args_schema`, docstrings under 1024 chars\n- Invocations pass `{\"configurable\": {\"thread_id\": ...}, \"recursion_limit\": N}`\n- `TokenBudget` callback enforces per-session cost ceiling\n- Tool errors raise and surface in observability; graceful-degrade patterns are\n  explicit (return-a-string, not silent-swallow)\n- Decision table resolved: `create_react_agent` vs custom `StateGraph` vs\n  supervisor vs legacy\n\n## Error Handling\n\n| Error | Cause | Fix |\n|-------|-------|-----|\n| `GraphRecursionError: Recursion limit of 25 reached without hitting a stop condition` | Vague prompt never converges; default cap too high (P10) | Lower `recursion_limit` to 5-10 interactive; add repeated-tool-call early-stop node |\n| `ImportError: cannot import name 'initialize_agent' from 'langchain.agents'` | Legacy 0.2 agent factory removed (P41) | `from langgraph.prebuilt import create_react_agent` |\n| `AttributeError: 'ToolCall' object has no attribute 'tool'` | Old code accessing `step.tool` on new intermediate step shape (P42) | Use `step.tool_name` (or `step[\"name\"]` on dict form); check `isinstance(step, ToolCall)` |\n| Agent says \"couldn't find answer\" but tool actually raised | Legacy `AgentExecutor` `handle_parsing_errors=True` silently swallowed exception (P09) | Migrate to `create_react_agent`; errors raise by default |\n| Agent loops when `tool_choice={\"type\": \"tool\", \"name\": \"X\"}` is set | Forced tool_choice blocks `stop_reason=\"end_turn\"` (P63) | Use `tool_choice=\"auto\"` for agent loops; reserve forced choice for one-shot calls |\n| Agent hallucinates a tool name like `exec` that is not in `tools=[...]` | Older free-text ReAct parser accepts any string (P32) | Use `create_react_agent` — it relies on provider-native tool calling; the allowlist is wire-enforced |\n| `RuntimeError: Token budget exceeded` | Your `TokenBudget` callback fired | Working as intended; raise the cap or shorten the agent's scope |\n| Tool description truncated, model calls with wrong args | Docstring exceeded 1024-char cap (P11) | Shorten docstring; move examples into system prompt |\n\n## Examples\n\n### Migrating a legacy `AgentExecutor` agent\n\nBefore (LangChain 0.2):\n\n```python\nfrom langchain.agents import initialize_agent, AgentType\nagent = initialize_agent(\n    tools, llm, agent=AgentType.OPENAI_FUNCTIONS,\n    handle_parsing_errors=True, return_intermediate_steps=True,\n)\nresult = agent.invoke({\"input\": \"...\"})\nfor action, observation in result[\"intermediate_steps\"]:\n    print(action.tool, observation)  # .tool attribute\n```\n\nAfter (LangGraph 1.0):\n\n```python\nfrom langgraph.prebuilt import create_react_agent\nfrom langgraph.checkpoint.memory import MemorySaver\nagent = create_react_agent(llm, tools, checkpointer=MemorySaver())\nresult = agent.invoke(\n    {\"messages\": [{\"role\": \"user\", \"content\": \"...\"}]},\n    config={\"configurable\": {\"thread_id\": \"t1\"}, \"recursion_limit\": 10},\n)\n# intermediate steps are now ToolMessage entries in the messages list\nfor m in result[\"messages\"]:\n    if m.type == \"tool\":\n        print(m.name, m.content)  # .name, not .tool\n```\n\nSee [AgentExecutor Migration](references\u002Fagent-executor-migration.md) for the\nfull before\u002Fafter including `handle_parsing_errors`, `return_intermediate_steps`,\nand `max_iterations` translations.\n\n### Interactive agent with a strict cost cap\n\nA customer-support agent with two tools, 10-step recursion cap, and a 30K\ntoken budget. See [Loop Caps and Budgets](references\u002Floop-caps-and-budgets.md)\nfor the full example with a repeated-tool-call early-stop node.\n\n## Resources\n\n- [LangGraph: Agents overview](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Fagents\u002Foverview\u002F)\n- [`create_react_agent` reference](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Freference\u002Fprebuilt\u002F#langgraph.prebuilt.chat_agent_executor.create_react_agent)\n- [LangGraph: Recursion limits](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Fhow-tos\u002Frecursion-limit\u002F)\n- [LangGraph: Tool calling](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Fhow-tos\u002Ftool-calling\u002F)\n- [LangChain: `@tool` decorator](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fhow_to\u002Fcustom_tools\u002F)\n- [LangChain 1.0 release notes](https:\u002F\u002Fblog.langchain.com\u002Flangchain-langgraph-1dot0\u002F)\n- Pack pain catalog: `docs\u002Fpain-catalog.md` (entries P09, P10, P11, P32, P41, P42, P63)\n","# LangChain LangGraph Agents (Python)\n\n## Overview\n\nTwo failure modes hit every team writing their first LangGraph 1.0 ReAct agent:\n\n**Loop-to-cap on vague prompts (P10).** `create_react_agent` defaults to\n`recursion_limit=25`. A prompt like \"help me with my account\" never converges —\nthe model calls a retrieval tool, gets irrelevant results, calls another tool,\nand repeats until `GraphRecursionError: Recursion limit of 25 reached without\nhitting a stop condition` fires. Cost dashboards show the damage *after* the\nfact: $5-$15 per runaway loop on Sonnet with a 3-tool agent, assuming no tool\nis itself expensive.\n\n**Silent tool errors on legacy `AgentExecutor` (P09).** The legacy executor\ndefaults `handle_parsing_errors=True` and catches tool exceptions, feeding the\nerror string back as the next observation. When the error serializes to empty\n(e.g., a `ValueError(\"\")` or an HTTP 500 with no body), the loop continues with\nno signal. The agent says \"I couldn't find the answer\" — which was actually a\nsilent crash three tool calls ago.\n\nThis skill walks through defining typed tools with `@tool` + Pydantic; building\nan agent with `create_react_agent(model, tools, checkpointer=MemorySaver())`;\ninvoking with `{\"messages\": [...]}` and a thread-scoped config; setting\n`recursion_limit` per expected agent depth (5-10 interactive, 20-30 planner);\nadding middleware for a per-session token budget; and raise-by-default error\npropagation. Pin: `langgraph >= 1.0, \u003C 2.0`, `langchain-core >= 1.0, \u003C 2.0`.\nPain-catalog anchors: P09, P10, P11, P32, P41, P42, P63.\n\n## Prerequisites\n\n- Python 3.10+\n- `langgraph >= 1.0, \u003C 2.0` and `langchain-core >= 1.0, \u003C 2.0`\n- At least one provider package: `pip install langchain-anthropic` or `langchain-openai`\n- Completed skill: `langchain-langgraph-basics` (L25) — you already know `StateGraph`,\n  `MessagesState`, and checkpointers\n- Provider API key: `ANTHROPIC_API_KEY` or `OPENAI_API_KEY`\n\n## Instructions\n\n### Step 1 — Define tools with typed schemas and short docstrings\n\n```python\nfrom typing import Annotated\nfrom pydantic import BaseModel, Field\nfrom langchain_core.tools import tool\n\nclass LookupAccountArgs(BaseModel):\n    account_id: str = Field(..., description=\"Account UUID. No email addresses.\")\n\n@tool(\"lookup_account\", args_schema=LookupAccountArgs)\ndef lookup_account(account_id: str) -> dict:\n    \"\"\"Fetch an account record by UUID. Returns status, plan, and owner email.\"\"\"\n    if not account_id:\n        raise ValueError(\"account_id is required\")  # raised → agent sees real error\n    return {\"id\": account_id, \"status\": \"active\", \"plan\": \"pro\", \"owner\": \"a@b.co\"}\n```\n\nTwo rules that catch teams off-guard:\n\n1. **Docstring is the tool description the provider sees.** Keep it under\n   **1024 chars** (P11). Anthropic truncates at ~1024; OpenAI's effective cap is\n   softer but still bites on tool descriptions over ~2KB. Long docstrings with\n   examples should move into a system prompt, not the tool description.\n2. **Raise real exceptions.** Unlike the legacy `AgentExecutor`, LangGraph's\n   `create_react_agent` does not silently swallow tool errors — the exception\n   propagates and surfaces in your observability layer. See Step 6.\n\nFor async tools, use `@tool` on an `async def` — LangGraph invokes it via\n`await`. For structured return types, annotate the return with a Pydantic model.\n\nSee [Tool Definition Patterns](references\u002Ftool-definition-patterns.md) for the\n`@tool` vs `tool()` decision, async tools, and the `args_schema` vs\nauto-inferred trade-off.\n\n### Step 2 — Build the agent with `create_react_agent`\n\n```python\nfrom langgraph.prebuilt import create_react_agent\nfrom langgraph.checkpoint.memory import MemorySaver\nfrom langchain_anthropic import ChatAnthropic\n\nmodel = ChatAnthropic(\n    model=\"claude-sonnet-4-6\",\n    temperature=0,\n    timeout=30,\n    max_retries=2,\n)\n\nagent = create_react_agent(\n    model=model,\n    tools=[lookup_account],\n    checkpointer=MemorySaver(),  # required for stateful invocations\n)\n```\n\n`create_react_agent` is the LangGraph 1.0 replacement for the removed\n`initialize_agent` factory (P41). Under the hood it builds a `StateGraph` with\na `model` node and a `ToolNode`, plus a conditional edge that routes to\n`END` when the model emits no tool calls. The `checkpointer` persists state\nper-thread — required for multi-turn conversations and for resuming after\ninterruption.\n\n### Step 3 — Invoke with a thread-scoped config\n\n```python\nconfig = {\"configurable\": {\"thread_id\": \"user-42\"}}\nresult = agent.invoke(\n    {\"messages\": [{\"role\": \"user\", \"content\": \"look up account uuid-abc\"}]},\n    config=config,\n)\nprint(result[\"messages\"][-1].content)\n```\n\nKey contracts:\n\n- **Input** is `{\"messages\": [...]}` — a list of message dicts or LangChain\n  `HumanMessage` \u002F `SystemMessage` objects. You append to this list across turns.\n- **`thread_id`** scopes the checkpointer. Reusing it resumes the conversation.\n- **Output** is the full updated state. `result[\"messages\"]` is the complete\n  message list; the final assistant message is at index `-1`.\n\n### Step 4 — Set `recursion_limit` to your expected agent depth\n\n`create_react_agent` defaults to `recursion_limit=25`. In LangGraph one\n\"recursion step\" is one node visit, and each tool round-trip is two visits\n(model node + tool node), so 25 means ~12 tool calls. For most workloads this\nis too generous and hides bugs:\n\n| Agent kind | Suggested `recursion_limit` | Rationale |\n|---|---|---|\n| Interactive chat with 1-3 tools | 5-10 | One tool call + one final answer is 3 visits. Cap low to expose loops. |\n| Task-completion (e.g., booking flow) | 10-15 | 3-5 tool calls + final answer. |\n| Planner \u002F research agent | 20-30 | Expect multiple retrieval + synthesis rounds. |\n| Multi-agent supervisor | 40+ | Coordinator + worker rounds. Budget tokens separately. |\n\nApply it on invocation, not at construction time:\n\n```python\nresult = agent.invoke(\n    {\"messages\": [...]},\n    config={\"configurable\": {\"thread_id\": \"user-42\"}, \"recursion_limit\": 10},\n)\n```\n\nWhen the limit fires, LangGraph raises `GraphRecursionError` — catch it and\nsurface a user-facing message; do not retry without a cost guard.\n\n### Step 5 — Add a per-session token budget via middleware\n\n`recursion_limit` alone does not bound cost. A single tool call that returns a\nlarge document and triggers a long model response can cost more than 10 cheap\ntool calls. Cap tokens explicitly:\n\n```python\nfrom langchain_core.callbacks import BaseCallbackHandler\n\nclass TokenBudget(BaseCallbackHandler):\n    def __init__(self, max_tokens: int = 50_000):\n        self.used = 0\n        self.max = max_tokens\n\n    def on_llm_end(self, response, **kwargs):\n        usage = getattr(response, \"llm_output\", {}).get(\"token_usage\", {}) or {}\n        self.used += usage.get(\"total_tokens\", 0)\n        if self.used > self.max:\n            raise RuntimeError(f\"Token budget exceeded: {self.used}\u002F{self.max}\")\n\nbudget = TokenBudget(max_tokens=50_000)\nresult = agent.invoke(\n    {\"messages\": [...]},\n    config={\n        \"configurable\": {\"thread_id\": \"user-42\"},\n        \"recursion_limit\": 10,\n        \"callbacks\": [budget],\n    },\n)\n```\n\nA per-session budget of 50K tokens on Sonnet is roughly $0.25 — a safe cap for\ninteractive agents. For background planners raise to 200K-500K. See\n[Loop Caps and Budgets](references\u002Floop-caps-and-budgets.md) for a\nrepeated-tool-call early-stop node and a middleware pattern that terminates on\nthe N-th identical call.\n\n### Step 6 — Propagate tool errors; do not silently swallow\n\nLangGraph's default is to raise. Legacy `AgentExecutor(handle_parsing_errors=True)`\nswallowed everything. The new defaults are safer but different:\n\n```python\n# Tool raises → the exception propagates out of agent.invoke()\ntry:\n    result = agent.invoke({\"messages\": [{\"role\": \"user\", \"content\": \"...\"}]}, config=config)\nexcept ValueError as e:\n    # Your tool's own ValueError — log + user-facing message\n    ...\n```\n\nWhen you *want* tolerant behavior (e.g., the tool is a flaky third-party API\nand you want the model to try a different approach), wrap the tool itself:\n\n```python\nfrom langchain_core.tools import tool\n\n@tool\ndef search_kb(query: str) -> str:\n    \"\"\"Search the internal knowledge base. Returns hits or a 'no results' string.\"\"\"\n    try:\n        return _real_search(query)\n    except HTTPError as e:\n        return f\"search_kb unavailable: {e.response.status_code}. Try a different query.\"\n```\n\nThe key insight: the *tool* decides to degrade gracefully by returning a string\nthe model can reason about. The *agent* never silently drops an error. See\n[Error Propagation](references\u002Ferror-propagation.md) for a custom error-handler\nnode that routes tool failures to a fallback tool.\n\n### Step 7 — Choose `create_react_agent` vs custom `StateGraph` vs legacy\n\n| Decision | Use | Why |\n|---|---|---|\n| Single agent, tool-calling loop | `create_react_agent` | Correct defaults, provider-native tool calling, smallest code surface |\n| Multi-stage pipeline (plan → execute → review) | Custom `StateGraph` | You need named nodes, explicit conditional edges, typed state |\n| Multi-agent supervisor | `create_supervisor` + workers built with `create_react_agent` | Built-in routing, per-worker checkpointing |\n| New code in 2026+ | Never use `AgentExecutor` or `initialize_agent` | Removed \u002F deprecated in 1.0 (P41); shape changes in `intermediate_steps` (P42) |\n\nFor a single forced-tool single-shot (e.g., \"always classify into one of these\nbuckets\"), skip agents entirely: use `model.bind_tools([Schema],\ntool_choice={\"type\": \"tool\", \"name\": \"Schema\"})`. But never loop a forced\n`tool_choice` (P63) — the model cannot emit `stop_reason=\"end_turn\"` under\nforced tool_choice, so the agent never terminates.\n\n## Output\n\n- Agent built with `create_react_agent(model, tools, checkpointer=MemorySaver())`\n- Tools defined with `@tool` + Pydantic `args_schema`, docstrings under 1024 chars\n- Invocations pass `{\"configurable\": {\"thread_id\": ...}, \"recursion_limit\": N}`\n- `TokenBudget` callback enforces per-session cost ceiling\n- Tool errors raise and surface in observability; graceful-degrade patterns are\n  explicit (return-a-string, not silent-swallow)\n- Decision table resolved: `create_react_agent` vs custom `StateGraph` vs\n  supervisor vs legacy\n\n## Error Handling\n\n| Error | Cause | Fix |\n|-------|-------|-----|\n| `GraphRecursionError: Recursion limit of 25 reached without hitting a stop condition` | Vague prompt never converges; default cap too high (P10) | Lower `recursion_limit` to 5-10 interactive; add repeated-tool-call early-stop node |\n| `ImportError: cannot import name 'initialize_agent' from 'langchain.agents'` | Legacy 0.2 agent factory removed (P41) | `from langgraph.prebuilt import create_react_agent` |\n| `AttributeError: 'ToolCall' object has no attribute 'tool'` | Old code accessing `step.tool` on new intermediate step shape (P42) | Use `step.tool_name` (or `step[\"name\"]` on dict form); check `isinstance(step, ToolCall)` |\n| Agent says \"couldn't find answer\" but tool actually raised | Legacy `AgentExecutor` `handle_parsing_errors=True` silently swallowed exception (P09) | Migrate to `create_react_agent`; errors raise by default |\n| Agent loops when `tool_choice={\"type\": \"tool\", \"name\": \"X\"}` is set | Forced tool_choice blocks `stop_reason=\"end_turn\"` (P63) | Use `tool_choice=\"auto\"` for agent loops; reserve forced choice for one-shot calls |\n| Agent hallucinates a tool name like `exec` that is not in `tools=[...]` | Older free-text ReAct parser accepts any string (P32) | Use `create_react_agent` — it relies on provider-native tool calling; the allowlist is wire-enforced |\n| `RuntimeError: Token budget exceeded` | Your `TokenBudget` callback fired | Working as intended; raise the cap or shorten the agent's scope |\n| Tool description truncated, model calls with wrong args | Docstring exceeded 1024-char cap (P11) | Shorten docstring; move examples into system prompt |\n\n## Examples\n\n### Migrating a legacy `AgentExecutor` agent\n\nBefore (LangChain 0.2):\n\n```python\nfrom langchain.agents import initialize_agent, AgentType\nagent = initialize_agent(\n    tools, llm, agent=AgentType.OPENAI_FUNCTIONS,\n    handle_parsing_errors=True, return_intermediate_steps=True,\n)\nresult = agent.invoke({\"input\": \"...\"})\nfor action, observation in result[\"intermediate_steps\"]:\n    print(action.tool, observation)  # .tool attribute\n```\n\nAfter (LangGraph 1.0):\n\n```python\nfrom langgraph.prebuilt import create_react_agent\nfrom langgraph.checkpoint.memory import MemorySaver\nagent = create_react_agent(llm, tools, checkpointer=MemorySaver())\nresult = agent.invoke(\n    {\"messages\": [{\"role\": \"user\", \"content\": \"...\"}]},\n    config={\"configurable\": {\"thread_id\": \"t1\"}, \"recursion_limit\": 10},\n)\n# intermediate steps are now ToolMessage entries in the messages list\nfor m in result[\"messages\"]:\n    if m.type == \"tool\":\n        print(m.name, m.content)  # .name, not .tool\n```\n\nSee [AgentExecutor Migration](references\u002Fagent-executor-migration.md) for the\nfull before\u002Fafter including `handle_parsing_errors`, `return_intermediate_steps`,\nand `max_iterations` translations.\n\n### Interactive agent with a strict cost cap\n\nA customer-support agent with two tools, 10-step recursion cap, and a 30K\ntoken budget. See [Loop Caps and Budgets](references\u002Floop-caps-and-budgets.md)\nfor the full example with a repeated-tool-call early-stop node.\n\n## Resources\n\n- [LangGraph: Agents overview](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Fagents\u002Foverview\u002F)\n- [`create_react_agent` reference](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Freference\u002Fprebuilt\u002F#langgraph.prebuilt.chat_agent_executor.create_react_agent)\n- [LangGraph: Recursion limits](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Fhow-tos\u002Frecursion-limit\u002F)\n- [LangGraph: Tool calling](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Fhow-tos\u002Ftool-calling\u002F)\n- [LangChain: `@tool` decorator](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fhow_to\u002Fcustom_tools\u002F)\n- [LangChain 1.0 release notes](https:\u002F\u002Fblog.langchain.com\u002Flangchain-langgraph-1dot0\u002F)\n- Pack pain catalog: `docs\u002Fpain-catalog.md` (entries P09, P10, P11, P32, P41, P42, P63)\n",{"name":5,"tags":24,"author":32,"license":15,"version":33,"description":34,"allowed-tools":35,"compatible-with":36},[25,26,27,28,29,30,31],"saas","langchain","langgraph","python","langchain-1.0","agents","tool-calling","Jeremy Longshore \u003Cjeremy@intentsolutions.io>","2.0.0","Build a correct LangGraph 1.0 ReAct agent with `create_react_agent` — typed tools,\nerror propagation, recursion caps, and stop conditions that actually stop. Use when\nwriting your first tool-calling agent, migrating from `AgentExecutor` \u002F `initialize_agent`,\nor diagnosing an agent that loops on vague prompts.\nTrigger with \"langgraph agent\", \"create_react_agent\", \"langgraph tool calling\",\n\"AgentExecutor migration\", \"agent loop cost\".\n","Read, Write, Edit, Bash(python:*)","claude-code, codex","main","99825ad3f3bcc6597ddcc7294a14e6e922f2b67b","skills\u002Fsaas-packs--langchain-py-pack--langchain-langgraph-agents",0,"https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills","https:\u002F\u002Fgithub.com\u002Fjukeyman","https:\u002F\u002FRJBUSINESSSOLUTIONS.ORG","Credit and Finance Expert | Developer\r\n\r\nI'm Rick Jefferson, a seasoned credit and finance expert with over a decade of experience in financial literacy,","2026-07-13 07:03:29",{"source":8,"skillName":5,"commands":47,"prompt":57,"zipAvailable":58},[48,51,54],{"tool":49,"command":50},"npx","npx skills add jukeyman\u002Fjukeyman-skills --skill langchain-langgraph-agents",{"tool":52,"command":53},"bunx","bunx skills add jukeyman\u002Fjukeyman-skills --skill langchain-langgraph-agents",{"tool":55,"command":56},"pnpm","pnpm dlx skills add jukeyman\u002Fjukeyman-skills --skill langchain-langgraph-agents","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--langchain-py-pack--langchain-langgraph-agents\u002FSKILL.md",true,[],[61,68,75,82,89,97],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":19},"01M79ANS2SM329NEP5ZCX106RR","zustand-store-creator","Create zustand store creator operations. Auto-activating skill for Frontend Development.\nTriggers on: zustand store creator, zustand store creator\nPart of the Frontend Development skill category. Use when working with zustand store creator functionality. Trigger with phrases like \"zustand store creator\", \"zustand creator\", \"zustand\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzustand-store-creator\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":19},"01M79AMZKP4YDEZ7EHG1Y7PP74","zero-trust-config-helper","Configure with zero trust config helper operations. Auto-activating skill for Security Advanced.\nTriggers on: zero trust config helper, zero trust config helper\nPart of the Security Advanced skill category. Use when configuring systems or services. Trigger with phrases like \"zero trust config helper\", \"zero helper\", \"zero\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzero-trust-config-helper\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":19},"01M79AMJSBCEJQNBTYNAHYN5HM","zapier-integration-helper","Assist with zapier integration helper operations. Auto-activating skill for Business Automation.\nTriggers on: zapier integration helper, zapier integration helper\nPart of the Business Automation skill category. Use when working with APIs or building integrations. Trigger with phrases like \"zapier integration helper\", \"zapier helper\", \"zapier\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzapier-integration-helper\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M79AHJZGVMARS13VFQYRR1MP","yaml-config-validator","Validate yaml config validator operations. Auto-activating skill for DevOps Basics.\nTriggers on: yaml config validator, yaml config validator\nPart of the DevOps Basics skill category. Use when configuring systems or services. Trigger with phrases like \"yaml config validator\", \"yaml validator\", \"yaml\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fyaml-config-validator\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":93,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":19},"01M79AHGDZRN0020RDQSQDPAM8","xvary-stock-research","Thesis-driven equity analysis from public SEC EDGAR and market data; \u002Fanalyze, \u002Fscore, \u002Fcompare workflows with bundled Python tools (Claude Code, Cursor, Codex).","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FSKILL.md",[],[],{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":19},"01M79AHCYJ9FV9RMHQ24HDRN33","xss-vulnerability-scanner","Scan xss vulnerability scanner operations. Auto-activating skill for Security Fundamentals.\nTriggers on: xss vulnerability scanner, xss vulnerability scanner\nPart of the Security Fundamentals skill category. Use when working with xss vulnerability scanner functionality. Trigger with phrases like \"xss vulnerability scanner\", \"xss scanner\", \"xss\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxss-vulnerability-scanner\u002FSKILL.md",[],[]]