langgraph-fundamentals

Khung đồ thị có hướng để xây dựng quy trình tác nhân đa bước, có trạng thái với kiểm soát chi tiết. StateGraph với lược đồ trạng thái được định kiểu, bộ giảm để tích lũy danh sách/giá trị và các nút trả về cập nhật trạng thái một phần. Các cạnh tĩnh cho luồng cố định, cạnh có điều kiện để rẽ nhánh và Command để kết hợp cập nhật trạng thái với định tuyến động. API Send để song song hóa phân luồng đến các nút công nhân với tổng hợp kết quả qua bộ giảm. Invoke cho thực thi đơn lẻ và các chế độ luồng (giá trị, cập nhật,...)

npx skills add https://github.com/langchain-ai/langchain-skills --skill langgraph-fundamentals
LangGraph models agent workflows as **directed graphs**:
  • StateGraph: Main class for building stateful graphs
  • Nodes: Functions that perform work and update state
  • Edges: Define execution order (static or conditional)
  • START/END: Special nodes marking entry and exit points
  • State with Reducers: Control how state updates are merged

Graphs must be compile()d before execution.

Designing a LangGraph application

Follow these 5 steps when building a new graph:

  1. Map out discrete steps — sketch a flowchart of your workflow. Each step becomes a node.
  2. Identify what each step does — categorize nodes: LLM step, data step, action step, or user input step. For each, determine static context (prompt), dynamic context (from state), retry strategy, and desired outcome.
  3. Design your state — state is shared memory for all nodes. Store raw data, format prompts on-demand inside nodes.
  4. Build your nodes — implement each step as a function that takes state and returns partial updates.
  5. Wire it together — connect nodes with edges, add conditional routing, compile with a checkpointer if needed.
Use LangGraph WhenUse Alternatives When
Need fine-grained control over agent orchestrationQuick prototyping → LangChain agents
Building complex workflows with branching/loopsSimple stateless workflows → LangChain direct
Require human-in-the-loop, persistenceBatteries-included features → Deep Agents

State Management

NeedSolutionExample
Overwrite valueNo reducer (default)Simple fields like counters
Append to listReducer (operator.add / concat)Message history, logs
Custom logicCustom reducer functionComplex merging

Nodes

Node functions return partial state updates. Signatures for configuration and runtime access differ by language; use the applicable implementation reference.


Edges

NeedEdge TypeWhen to Use
Always go to same nodeadd_edge()Fixed, deterministic flow
Route based on stateadd_conditional_edges()Dynamic branching
Update state AND routeCommandCombine logic in single node
Fan-out to multiple nodesSendParallel processing with dynamic inputs

Command

Command combines state updates and routing in a single return value. Fields:

  • update: State updates to apply (like returning a dict from a node)
  • goto: Node name(s) to navigate to next
  • resume: Value to resume after interrupt() — see human-in-the-loop skill

Python: Use Command[Literal["node_a", "node_b"]] as the return type annotation to declare valid goto destinations.

TypeScript: Pass { ends: ["node_a", "node_b"] } as the third argument to addNode to declare valid goto destinations.

Warning: Command only adds dynamic edges — static edges defined with add_edge / addEdge still execute. If node_a returns Command(goto="node_c") and you also have graph.add_edge("node_a", "node_b"), both node_b and node_c will run.


Send API

Fan-out with Send: return [Send("worker", {...})] from a conditional edge to spawn parallel workers. Requires a reducer on the results field.


Running Graphs: Invoke and Stream

Call graph.invoke(input, config) to run a graph to completion and return the final state.

ModeWhat it StreamsUse Case
valuesFull state after each stepMonitor complete state
updatesState deltasTrack incremental updates
messagesLLM tokens + metadataChat UIs
customUser-defined dataProgress indicators

Error Handling

Match the error type to the right handler:

Error TypeWho FixesStrategyExample
Transient (network, rate limits)SystemRetryPolicy(max_attempts=3)add_node(..., retry_policy=...)
LLM-recoverable (tool failures)LLMToolNode(tools, handle_tool_errors=True)Error returned as ToolMessage
User-fixable (missing info)Humaninterrupt({"message": ...})Collect missing data (see HITL skill)
UnexpectedDeveloperLet bubble upraise

Core boundaries

  • Return partial state updates from nodes instead of mutating state directly.
  • Route loops through a named node; START is entry-only.
  • Define reducers for accumulated list fields; otherwise, the last write wins.
  • Account for static edges when using Command with goto, because both routes execute.

Implementation references

If writing, modifying, or debugging LangGraph code, determine the project's language from its existing files, then read the applicable reference before implementing:

Read both only when the task covers both languages. For conceptual questions that require no code, do not load either reference.

Thêm skills từ langchain-ai

deepagents-thread-inspector
langchain-ai
Kiểm tra và giải thích các cuộc hội thoại trong kho lưu trữ phiên SQLite cục bộ của Deep Agents Code. Sử dụng như phương án dự phòng khi công cụ theo dõi LangSmith không khả dụng, cho…
deepagents-python-quickstart
langchain-ai
Tạo khung một Deep Agent cục bộ tối thiểu bằng Python bằng cách làm theo hướng dẫn khởi động nhanh chính thức, sử dụng tìm kiếm web gốc của nhà cung cấp thay vì Tavily. Sử dụng khi người dùng muốn…
deepagents-typescript-quickstart
langchain-ai
Tạo khung một Deep Agent tối thiểu cục bộ bằng TypeScript theo hướng dẫn khởi động nhanh chính thức, sử dụng tìm kiếm web gốc của nhà cung cấp thay vì Tavily. Sử dụng khi người dùng…
eval-engineering
langchain-ai
Lặp lại kiểm tra kho lưu trữ agent và các dấu vết do người dùng cung cấp tùy chọn, phỏng vấn người dùng, và tạo, chạy, cũng như kiểm toán các đánh giá Harbor từng cái một. Sử dụng cho…
LangChain RAG Pipeline
langchain-ai
GỌI KỸ NĂNG NÀY khi xây dựng BẤT KỲ hệ thống tạo sinh tăng cường truy xuất (RAG) nào. Bao gồm bộ tải tài liệu, RecursiveCharacterTextSplitter, embeddings (OpenAI),…
LangChain Structured Output & HITL
langchain-ai
langchain-structured-output-&-hitl — một kỹ năng có thể cài đặt cho các tác nhân AI, được xuất bản bởi langchain-ai/langchain-skills.
LangSmith Datasets
langchain-ai
GỌI KỸ NĂNG NÀY khi tạo bộ dữ liệu đánh giá từ trace HOẶC tải bộ dữ liệu lên LangSmith HOẶC truy vấn bộ dữ liệu. Bao gồm các loại bộ dữ liệu (final_response,…
langsmith-evaluator
langchain-ai
GỌI KỸ NĂNG NÀY khi xây dựng pipeline đánh giá cho LangSmith. Bao gồm ba thành phần cốt lõi: (1) Tạo Evaluator - LLM-as-Judge, mã tùy chỉnh; (2)…