LangChain và Multi-Agent Systems: Xây Dựng AI Pipeline Sản Xuất
LangChain 2026 là nền tảng xây dựng multi-agent AI systems: orchestration, RAG, tool use và LangGraph cho production-grade AI pipelines.
Tóm tắt nhanh
LangChain 2026 đã tế hoà từ framework thực nghiệm thành nền tảng production cho multi-agent AI systems. Với LangGraph xử lý agent workflows, LangSmith monitor và debug, và ecosystem tools phóng phú, đây là stack được nhiều công ty Việt Nam đang adopt để xây dựng AI-powered applications.
Giới thiệu
Nếu bạn đang xây dựng ứng dụng AI vượt ra ngoài chatbot đơn giản — nếu bạn muốn AI có thể dùng tools, truy vấn database, đọc files, làm việc với nhiều AI agents cùng lúc — bạn cần một framework. Và năm 2026, LangChain là framework đó.
Hiểu đơn giản: LangChain giống như React cho AI apps. React cung cấp components và patterns để xây UI phức tạp. LangChain cung cấp "components" để kết nối LLMs với tools, memory, và các agents khác.
Năm 2026, LangChain đã giải quyết được điểm yếu lớn nhất của mình địa diệ trước đây: overengineering và abstraction quá nhiều. API mới (LangChain v0.3+) ngọn gàng hơn đáng kể.
Khái Niệm Cốt Lõi
LLM Chain — Cơ bản nhất
from langchain_anthropic import ChatAnthropic
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
# Simple chain: prompt → LLM → output
llm = ChatAnthropic(model="claude-opus-4-7")
prompt = ChatPromptTemplate.from_messages([
("system", "Bạn là expert về {domain}. Trả lời súc tích bằng tiếng Việt."),
("user", "{question}")
])
chain = prompt | llm | StrOutputParser()
result = chain.invoke({
"domain": "TypeScript",
"question": "Generic types khác gì union types?"
})
print(result)
RAG — AI Hỏi Đáp Từ Tài Liệu Riêng
RAG (Retrieval-Augmented Generation) là kỹ thuật cho phép AI trả lời dựa trên documents của bạn:
from langchain_anthropic import ChatAnthropic
from langchain_community.vectorstores import Chroma
from langchain_openai import OpenAIEmbeddings
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import DirectoryLoader
from langchain_core.runnables import RunnablePassthrough
# 1. Load documents công ty
loader = DirectoryLoader('company-docs/', glob='*.pdf')
docs = loader.load()
# 2. Chunk documents
splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=200
)
chunks = splitter.split_documents(docs)
# 3. Tạo vector store
vectorstore = Chroma.from_documents(
chunks,
OpenAIEmbeddings()
)
retriever = vectorstore.as_retriever(search_kwargs={"k": 5})
# 4. RAG chain
llm = ChatAnthropic(model="claude-opus-4-7")
prompt = ChatPromptTemplate.from_template("""
Dựa vào các tài liệu sau: {context}
Hãy trả lời: {question}
Nếu không tìm thấy thông tin, hãy nói rõ là không có dữ liệu.
""")
rag_chain = (
{"context": retriever, "question": RunnablePassthrough()}
| prompt
| llm
| StrOutputParser()
)
# Hỏi về tài liệu nội bộ
answer = rag_chain.invoke("Quy trình onboarding nhân viận mới là gì?")
LangGraph — Multi-Agent Workflows
LangGraph là thư viện xử lý complex agent workflows như state machine:
from langgraph.graph import StateGraph, END
from typing import TypedDict, Annotated
import operator
class AgentState(TypedDict):
messages: Annotated[list, operator.add]
current_task: str
result: str
# Định nghĩa các nodes (agents)
def researcher_agent(state: AgentState):
"""Research thông tin"""
llm = ChatAnthropic(model="claude-opus-4-7")
result = llm.invoke(f"Research về: {state['current_task']}")
return {"messages": [result.content], "result": result.content}
def reviewer_agent(state: AgentState):
"""Review và cải thiện kết quả"""
llm = ChatAnthropic(model="claude-sonnet-4-6")
review = llm.invoke(f"Review và cải thiện: {state['result']}")
return {"result": review.content}
def should_continue(state: AgentState):
"""Quyết định tiếp tục hay dừng"""
if "insufficient" in state["result"].lower():
return "researcher" # Lặp lại
return END
# Xây dựng graph
workflow = StateGraph(AgentState)
workflow.add_node("researcher", researcher_agent)
workflow.add_node("reviewer", reviewer_agent)
workflow.set_entry_point("researcher")
workflow.add_edge("researcher", "reviewer")
workflow.add_conditional_edges("reviewer", should_continue)
app = workflow.compile()
# Chạy
result = app.invoke({
"current_task": "Tổng hợp xu hướng AI tháng 5/2026",
"messages": []
})
Tool Use — AI Dùng Công Cụ
from langchain.tools import tool
from langchain_anthropic import ChatAnthropic
from langgraph.prebuilt import create_react_agent
@tool
def search_database(query: str) -> str:
"""Tìm kiếm thông tin trong database sản phẩm.
Args:
query: câu truy vấn tìm kiếm
"""
# Query thật sự vào database của bạn
results = db.search(query)
return f"Tìm thấy {len(results)} kết quả: {results[:3]}"
@tool
def calculate_price(product_id: str, quantity: int) -> str:
"""Tính giá sản phẩm bao gồm thuế và giảm giá.
Args:
product_id: ID sản phẩm
quantity: số lượng
"""
price = get_product_price(product_id, quantity)
return f"Tổng: {price:,.0f} VNĐ"
# Tạo agent có thể dùng các tools này
llm = ChatAnthropic(model="claude-opus-4-7")
tools = [search_database, calculate_price]
agent = create_react_agent(llm, tools)
# Agent tự quyết định dùng tool nào
response = agent.invoke({
"messages": [("user", "Tìm sản phẩm laptop gaming và tính giá 2 cái")]
})
LangSmith — Observability cho AI Pipeline
from langsmith import Client
import os
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_API_KEY"] = "your-key"
os.environ["LANGCHAIN_PROJECT"] = "production-chatbot"
# Từ đây, mọi LangChain call sẽ được trace tự động
# Bạn thấy:
# - Latency của từng step
# - Token usage và chi phí
# - Input/output của từng agent
# - Error traces khi có lỗi
Use Cases Thực Tế
| Use Case | Components | Bộ Kết hợp |
|---|---|---|
| Customer support bot | RAG + Tools | LangChain + Chroma + Claude |
| Code review automation | Agent + Tools | LangGraph + GitHub API |
| Document analyzer | RAG + Summary | LangChain + Supabase pgvector |
| Data pipeline AI | Multi-agent | LangGraph + DuckDB + Claude |
| Internal Q&A | RAG | LangChain + Ollama (local) |
Ưu / Nhược điểm
Ưu điểm:
- Ecosystem phắp phủ — integrations sẵn cho mọi vector DB, LLM, tool
- LangGraph mạnh cho workflows phức tạp
- LangSmith observability rất tốt
- Community lớn, nhiều examples
Nhược điểm:
- Learning curve đối với LangGraph
- Đôi khi over-abstracted cho simple tasks
- Versioning thay đổi nhanh, docs cũ hay bị outdated
- Performance overhead so với direct API calls
Khi nào KHÔNG cần LangChain:
- Simple one-shot LLM calls (dùng Anthropic SDK trực tiếp)
- Khi team nhỏ, đơn giản hóa vẫn là ưu tiên
Xu hướng & Tương lai
Năm 2026-2027, multi-agent systems sẽ trở thành chuẩn cho:
- AI-powered SaaS: Mọi product có AI agent xử lý workflow phức tạp
- Internal automation: Thay thế nhiều manual processes
- Code intelligence: AI hiểu toàn bộ codebase và suggest improvements
LangChain đang push mạnh vào enterprise market, với LangChain for Enterprise (on-premise deployment, SOC 2 compliance). Đây là tin vui cho các công ty Việt Nam có requirements về data residency.
Kết luận
5 điểm nhớ về LangChain + Multi-Agent:
- LangChain = glue code tốt nhất cho LLM + tools + memory
- RAG = cách để AI biết về dữ liệu riêng của bạn
- LangGraph = orchestrate multiple agents phức tạp
- LangSmith = observability bắt buộc trong production
- Start simple: LCEL chain đơn giản trước, thêm agents khi cần
Nếu bạn chưa bắt đầu với AI development, hãy bắt đầu với một RAG system đơn giản — load documents của team, build Q&A bot. Đó là con đường nhanh nhất từ 0 đến "AI-powered product".
Bạn đang dùng công nghệ nào trong bài? Chia sẻ kinh nghiệm trong phần bình luận!