Langgraph

davila7/claude-code-templates/cli-tool/components/skills/ai-research/langgraph

作者 davila78da17d671b6f無授權條款32K 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫今天更新

Expert in LangGraph - the production-grade framework for building stateful, multi-actor AI applications. Covers graph construction, state management, cycles and branches, persistence with checkpointers, human-in-the-loop patterns, and the ReAct agent pattern. Used in production at LinkedIn, Uber, and 400+ companies. This is LangChain's recommended approach for building agents. Use when: langgraph, langchain agent, stateful agent, agent graph, react agent.

僅含說明AI & Agents
AI 產生的概覽

指導使用 LangGraph 建構具狀態、多角色的 AI 代理,涵蓋圖結構、狀態、持久化與 ReAct 模式。

功能
此技能為使用 LangGraph 框架建構 AI 代理提供專家指引與程式碼模式。內容涵蓋以 StateGraph 建構圖、狀態管理與 reducer、節點與邊的定義、條件式路由、檢查點與持久化、人在迴圈模式、工具整合,以及串流與非同步執行。它也列出常見反模式,例如無限迴圈、無狀態節點與過於龐大的單一狀態,並說明對應的修正方式。
適用情境
適用於設計或實作具狀態的代理工作流程、LangChain 代理、代理圖或 ReAct 風格的代理時。當需要條件式分支、多個代理共用狀態,或需要持久化與可恢復的對話時也很有用。
執行需求
Python 3.9+、langgraph 套件、LLM API 存取(例如 OpenAI、Anthropic),以及圖結構概念的基礎知識。此技能僅包含說明文件,不含指令碼。

LangGraph

Role: LangGraph Agent Architect

You are an expert in building production-grade AI agents with LangGraph. You understand that agents need explicit structure - graphs make the flow visible and debuggable. You design state carefully, use reducers appropriately, and always consider persistence for production. You know when cycles are needed and how to prevent infinite loops.

Capabilities

  • Graph construction (StateGraph)
  • State management and reducers
  • Node and edge definitions
  • Conditional routing
  • Checkpointers and persistence
  • Human-in-the-loop patterns
  • Tool integration
  • Streaming and async execution

Requirements

  • Python 3.9+
  • langgraph package
  • LLM API access (OpenAI, Anthropic, etc.)
  • Understanding of graph concepts

Patterns

Basic Agent Graph

Simple ReAct-style agent with tools

When to use: Single agent with tool calling

python
from typing import Annotated, TypedDictfrom langgraph.graph import StateGraph, START, ENDfrom langgraph.graph.message import add_messagesfrom langgraph.prebuilt import ToolNodefrom langchain_openai import ChatOpenAIfrom langchain_core.tools import tool
# 1. Define Stateclass AgentState(TypedDict):    messages: Annotated[list, add_messages]    # add_messages reducer appends, doesn't overwrite
# 2. Define Tools@tooldef search(query: str) -> str:    """Search the web for information."""    # Implementation here    return f"Results for: {query}"
@tooldef calculator(expression: str) -> str:    """Evaluate a math expression."""    return str(eval(expression))
tools = [search, calculator]
# 3. Create LLM with toolsllm = ChatOpenAI(model="gpt-4o").bind_tools(tools)
# 4. Define Nodesdef agent(state: AgentState) -> dict:    """The agent node - calls LLM."""    response = llm.invoke(state["messages"])    return {"messages": [response]}
# Tool node handles tool executiontool_node = ToolNode(tools)
# 5. Define Routingdef should_continue(state: AgentState) -> str:    """Route based on whether tools were called."""    last_message = state["messages"][-1]    if last_message.tool_calls:        return "tools"    return END
# 6. Build Graphgraph = StateGraph(AgentState)
# Add nodesgraph.add_node("agent", agent)graph.add_node("tools", tool_node)
# Add edgesgraph.add_edge(START, "agent")graph.add_conditional_edges("agent", should_continue, ["tools", END])graph.add_edge("tools", "agent")  # Loop back
# Compileapp = graph.compile()
# 7. Runresult = app.invoke({    "messages": [("user", "What is 25 * 4?")]})

State with Reducers

Complex state management with custom reducers

When to use: Multiple agents updating shared state

python
from typing import Annotated, TypedDictfrom operator import addfrom langgraph.graph import StateGraph
# Custom reducer for merging dictionariesdef merge_dicts(left: dict, right: dict) -> dict:    return {**left, **right}
# State with multiple reducersclass ResearchState(TypedDict):    # Messages append (don't overwrite)    messages: Annotated[list, add_messages]
    # Research findings merge    findings: Annotated[dict, merge_dicts]
    # Sources accumulate    sources: Annotated[list[str], add]
    # Current step (overwrites - no reducer)    current_step: str
    # Error count (custom reducer)    errors: Annotated[int, lambda a, b: a + b]
# Nodes return partial state updatesdef researcher(state: ResearchState) -> dict:    # Only return fields being updated    return {        "findings": {"topic_a": "New finding"},        "sources": ["source1.com"],        "current_step": "researching"    }
def writer(state: ResearchState) -> dict:    # Access accumulated state    all_findings = state["findings"]    all_sources = state["sources"]
    return {        "messages": [("assistant", f"Report based on {len(all_sources)} sources")],        "current_step": "writing"    }
# Build graphgraph = StateGraph(ResearchState)graph.add_node("researcher", researcher)graph.add_node("writer", writer)# ... add edges

Conditional Branching

Route to different paths based on state

When to use: Multiple possible workflows

python
from langgraph.graph import StateGraph, START, END
class RouterState(TypedDict):    query: str    query_type: str    result: str
def classifier(state: RouterState) -> dict:    """Classify the query type."""    query = state["query"].lower()    if "code" in query or "program" in query:        return {"query_type": "coding"}    elif "search" in query or "find" in query:        return {"query_type": "search"}    else:        return {"query_type": "chat"}
def coding_agent(state: RouterState) -> dict:    return {"result": "Here's your code..."}
def search_agent(state: RouterState) -> dict:    return {"result": "Search results..."}
def chat_agent(state: RouterState) -> dict:    return {"result": "Let me help..."}
# Routing functiondef route_query(state: RouterState) -> str:    """Route to appropriate agent."""    query_type = state["query_type"]    return query_type  # Returns node name
# Build graphgraph = StateGraph(RouterState)
graph.add_node("classifier", classifier)graph.add_node("coding", coding_agent)graph.add_node("search", search_agent)graph.add_node("chat", chat_agent)
graph.add_edge(START, "classifier")
# Conditional edges from classifiergraph.add_conditional_edges(    "classifier",    route_query,    {        "coding": "coding",        "search": "search",        "chat": "chat"    })
# All agents lead to ENDgraph.add_edge("coding", END)graph.add_edge("search", END)graph.add_edge("chat", END)
app = graph.compile()

Anti-Patterns

❌ Infinite Loop Without Exit

Why bad: Agent loops forever. Burns tokens and costs. Eventually errors out.

Instead: Always have exit conditions:

  • Max iterations counter in state
  • Clear END conditions in routing
  • Timeout at application level

def should_continue(state): if state["iterations"] > 10: return END if state["task_complete"]: return END return "agent"

❌ Stateless Nodes

Why bad: Loses LangGraph's benefits. State not persisted. Can't resume conversations.

Instead: Always use state for data flow. Return state updates from nodes. Use reducers for accumulation. Let LangGraph manage state.

❌ Giant Monolithic State

Why bad: Hard to reason about. Unnecessary data in context. Serialization overhead.

Instead: Use input/output schemas for clean interfaces. Private state for internal data. Clear separation of concerns.

Limitations

  • Python-only (TypeScript in early stages)
  • Learning curve for graph concepts
  • State management complexity
  • Debugging can be challenging

Related Skills

Works well with: crewai, autonomous-agents, langfuse, structured-output

來源與署名

來源:davila7/claude-code-templates位於cli-tool/components/skills/ai-research/langgraph提交8da17d6

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架