LangGraph: Xây Dựng Workflow Multi-Agent Cho AI Agent Phức Tạp

LangGraph: Xây Dựng Workflow Multi-Agent Cho AI Agent Phức Tạp

LangGraph là framework điều phối agent mức thấp (low-level orchestration framework) từ LangChain, cho phép developer xây dựng, quản lý và triển khai các AI agent có trạng thái (stateful), chạy lâu dài (long-running) với kiểm soát chi tiết từng bước. Khác với các abstraction mức cao, LangGraph tập trung vào khả năng kết hợp logic xác định (deterministic) được viết tay với các bước do LLM điều khiển trong một đồ thị (graph) thống nhất.

Sơ đồ quy trình AI Agent: The AI Scientist workflow minh họa các bước research, coding, experiment, paper generation
Sơ đồ quy trình AI Agent: The AI Scientist workflow minh họa các bước research, coding, experiment, paper generation

Tại Sao Cần LangGraph Khi Đã Có LangChain Agents?

LangChain cung cấp các agent kiến trúc sẵn (prebuilt architectures) như ReAct, OpenAI Functions agent cho các vòng lặp tool-calling phổ biến. Tuy nhiên, khi ứng dụng phức tạp hơn — cần persistence (lưu trạng thái qua restart), human-in-the-loop (can thiệp người), memory dài hạn, hoặc fault tolerance — các abstraction này trở nên hạn chế. LangGraph giải quyết bằng cách đưa ra một runtime dựa trên Pregel (model tính toán đồ thị phân tán của Google) cho phép:

  • Durable execution: Agent có thể tạm dừng, resume, retry sau failure mà không mất state.
  • Human-in-the-loop: Dừng graph tại bất kỳ node nào để review, sửa state trước khi tiếp tục.
  • Time travel debugging: Quay lại state trước đó để phân tích, debug — hỗ trợ mạnh cho LangSmith observability.
  • Subgraphs: Lồng graph con vào graph cha, tái sử dụng logic phức tạp.
  • Streaming & interrupts: Hỗ trợ streaming token, interrupt giữa chừng để hỏi user.

Kiến Trúc Cốt Lõi: StateGraph, Nodes, Edges, Checkpointers

Một ứng dụng LangGraph bao gồm ba thành phần chính:

  1. StateGraph: Định nghĩa schema state (thường kế thừa MessagesState hoặc custom TypedDict), quản lý ciclo đời state qua các node.
  2. Nodes: Hàm Python nhận state, trả về state cập nhật. Có thể là LLM call, tool execution, logic xác định, hoặc subgraph.
  3. Edges: Điều khiển luồng: START → node → node → END, có thể conditional edge dựa trên state.

Ví dụ minimal hello-world:

from langgraph.graph import StateGraph, MessagesState, START, END

def mock_llm(state: MessagesState):
    return {"messages": [{"role": "ai", "content": "hello world"}]}

graph = StateGraph(MessagesState)
graph.add_node("llm", mock_llm)
graph.add_edge(START, "llm")
graph.add_edge("llm", END)
app = graph.compile()

app.invoke({"messages": [{"role": "user", "content": "hi!"}]})
Ví dụ code LangGraph: graph.compile() và invocation với state persistence
Ví dụ code LangGraph: graph.compile() và invocation với state persistence

Persistence Với Checkpointers: SQLite, Postgres, Redis

LangGraph tách biệt logic graph khỏi storage qua interface BaseCheckpointSaver. Các implementation sẵn có:

Checkpointer Use Case Đặc Điểm
MemorySaver Dev, test nhanh In-memory, mất data khi restart
SqliteSaver Local dev, single-node File-based, ACID, nhẹ
PostgresSaver Production, multi-instance Scalable, concurrent, advisory locks
RedisSaver High-throughput, low-latency TTL support, cluster-ready

Khi compile graph, truyền checkpointer: graph.compile(checkpointer=SqliteSaver.from_conn_string("sqlite:///checkpoints.db")). Mỗi invocation cần config={"configurable": {"thread_id": "session-123"}} để isolate session.

Human-in-the-Loop: Interrupt Và Resume

Một trong những tính năng mạnh nhất là interrupt() — dừng graph, trả control về caller, cho phép human review/edit state:

from langgraph.types import interrupt

def human_review(state: State):
    decision = interrupt({"question": "Approve this action?", "data": state["draft"]})
    return {"approved": decision["approved"]}

# Khi invoke, graph dừng tại node này, trả Interrupt info
# Caller lấy interrupt, hỏi user, resume với Command(resume={"approved": True})

Điều này cho phép xây dựng approval workflow, content moderation, hoặc bất kỳ quy trình nào cần xác nhận người.

Memory: Short-Term Và Long-Term

LangGraph phân biệt hai loại memory:

  • Short-term (working memory): State trong thread_id hiện tại — tự động quản lý bởi checkpointer.
  • Long-term (cross-session): Sử dụng Store interface (InMemoryStore, RedisStore, PostgresStore) để lưu facts, preferences, summaries xuyên session. Store truy cập được trong node qua store.get(("user", user_id), "profile").

Triển Khai Production: LangSmith Observability Và Deployment

LangGraph tích hợp chặt chẽ với LangSmith cho tracing, evaluation, monitoring. Set env LANGSMITH_TRACING=true và LANGSMITH_API_KEY để tự động trace mọi graph run — visualize execution path, state transitions, token usage, latency. LangSmith Engine (mới) tự động detect issues (hallucination, loops, high latency) và đề xuất fix.

Để deploy, LangGraph Platform cung cấp managed infrastructure: horizontal scaling, load balancing, health checks, rolling updates cho stateful agents. Hoặc self-host với Docker/K8s dùng langgraph-api server.

So Sánh: LangGraph vs Các Framework Agent Khác

Framework Abstraction Level Stateful Human-in-loop Persistence Production Ready
LangGraph Low-level (graph-based) ✓ Native ✓ Interrupt API ✓ Pluggable checkpointers ✓ LangGraph Platform
LangChain Agents High-level (prebuilt) ✗ Limited ✗ Manual ✗ Manual △ Cần tự build infra
AutoGen Multi-agent conversation △ GroupChat △ UserProxyAgent △ Manual △
CrewAI Role-based crews △ Task memory △ Manual △ Manual △
OpenAI Assistants Managed API ✓ Threads △ Run steps ✓ Managed ✓ Fully managed

Khi Nào Nên Dùng LangGraph?

  • Cần kiểm soát chi tiết luồng agent: mixing deterministic + LLM steps.
  • Yêu cầu persistence, fault tolerance, long-running workflows (hours/days).
  • Cần human-in-the-loop cho approval, review, correction.
  • Cần time-travel debugging, observability sâu.
  • Xây dựng multi-agent system phức tạp với subgraphs, shared state.

Nếu chỉ cần simple tool-calling loop, LangChain Agents hoặc OpenAI Assistants API nhanh hơn. Nhưng cho production-grade agent system, LangGraph là lựa chọn chuẩn công nghiệp hiện nay — được dùng bởi Klarna, Uber, J.P. Morgan.

Tham khảo thêm: LangGraph Documentation | LangGraph GitHub | LangSmith Observability

Tôi là một lập trình viên IOS. Code chính là IOS nhưng thỉnnh thoảng vẫn đá sang Android hoặc web. Mặc dù không quá thông thạo nhưng tôi sẽ chia sẻ những kiến thức mà mình đã tìm hiểu, áp dụng qua.

Bài viết liên quan

Phi-3.5 Mini: Mô hình AI nhỏ 3.8B vượt trội từ Microsoft

Phi-3.5 Mini: Mô hình AI nhỏ 3.8B vượt trội từ Microsoft Phi-3.5 Mini là mô hình ngôn ngữ nhỏ (SLM) mới nhất từ Microsoft Research, sở hữu 3,8 tỷ tham…

Xem thêm
Giao diện Cursor AI Editor hiển thị chat sidebar và code editor

Cursor AI Editor là gì? Tác nhân AI code révolutionizes phát triển phần mềm

Cursor AI Editor là gì? Cursor AI Editor là trình soạn thảo mã nguồn mở được xây dựng trên nền tảng VS Code, tích hợp sâu các mô hình ngôn…

Xem thêm

AI Agent Orchestration: CrewAI vs AutoGen vs LangGraph So Sánh Chi Tiết

AI Agent Orchestration: CrewAI vs AutoGen vs LangGraph So Sánh Chi Tiết AI Agent Orchestration đang trở thành xu hướng phát triển mạnh mẽ nhất trong hệ sinh thái AI…

Xem thêm
0 0 đánh giá
Article Rating
Theo dõi
Thông báo của
guest
0 Comments
Cũ nhất
Mới nhất Được bỏ phiếu nhiều nhất