Chuyển đến nội dung chính

Bài 9: LangChain & LangGraph — Stateful Agent Workflows

Từ LangChain chains đến LangGraph graphs: nodes, edges, conditional routing, state management. Xây research agent với human-in-the-loop approval flow.

🧠 AI & ML — Bài 8 Bài 9: LangChain & LangGraph — Stateful Agent Workflows

Build AI Agents: Từ Zero đến Production

Phần 4: Agentic Frameworks

xdev.asia

Giới thiệu

Xây agent từ đầu rất tốt để hiểu concept, nhưng production cần framework. LangGraph (bởi LangChain team) là framework mạnh nhất hiện tại cho stateful, graph-based agent workflows.


1. LangChain vs LangGraph

LangChainLangGraph
ParadigmChains (linear)Graphs (cyclic)
StateStatelessStateful
Best forSimple pipelines, RAGComplex agents, multi-step
Control flowSequentialConditional routing

2. LangGraph Fundamentals

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

def call_llm(state: MessagesState):
    response = model.invoke(state["messages"])
    return {"messages": [response]}

def use_tools(state: MessagesState):
    # Execute tool calls
    ...

# Build graph
graph = StateGraph(MessagesState)
graph.add_node("llm", call_llm)
graph.add_node("tools", use_tools)
graph.add_edge(START, "llm")
graph.add_conditional_edges("llm", should_use_tools, {"yes": "tools", "no": END})
graph.add_edge("tools", "llm")

agent = graph.compile()

Tóm tắt

  • LangGraph = state machine cho agent workflows
  • Nodes = functions, Edges = transitions, State = shared data
  • Conditional routing cho complex decision trees
  • Human-in-the-loop built-in support
  • Persistence cho long-running workflows

Bài tập

  1. Implement research agent với LangGraph
  2. Thêm human-in-the-loop approval step
  3. Implement retry logic khi tool fails
  4. Xây agent với 3+ conditional branches