Khám Phá Agentic Frameworks

So sánh Vercel AI SDK, LangChain.js, LangGraph và CrewAI — chọn framework phù hợp

Agentic Frameworks Là Gì?

Agentic Frameworks là nền tảng phần mềm giúp đơn giản hoá việc tạo, triển khai và quản lý AI agents. Chúng cung cấp building blocks có sẵn để bạn tập trung vào logic nghiệp vụ thay vì xây dựng từ đầu.

Tại Sao Cần Framework?

AI Agent frameworks khác AI frameworks thông thường ở chỗ:

  • Agent Collaboration: Cho phép nhiều agents làm việc cùng nhau
  • Task Automation: Tự động hoá workflows phức tạp, nhiều bước
  • Contextual Understanding: Agents hiểu ngữ cảnh, thích ứng với môi trường thay đổi

So Sánh 4 Frameworks Chính

1. Vercel AI SDK

SDK mạnh mẽ cho TypeScript, tích hợp sẵn với React/Next.js. Focus vào streaming, structured output và tool calling.

import { generateText, tool } from "ai";
import { openai } from "@ai-sdk/openai";
import { z } from "zod";

const result = await generateText({
  model: openai("gpt-4o-mini"),
  tools: {
    weather: tool({
      description: "Lấy thông tin thời tiết",
      parameters: z.object({
        city: z.string().describe("Tên thành phố")
      }),
      execute: async ({ city }) => {
        // Gọi weather API
        return { city, temp: "25°C", condition: "Sunny" };
      }
    })
  },
  maxSteps: 5, // Agent có thể tự gọi tools tối đa 5 lần
  prompt: "Thời tiết ở Hà Nội hôm nay thế nào?"
});

Ưu điểm:

  • TypeScript-first, type-safe
  • Streaming UI components tuyệt vời
  • Tích hợp sẵn với Next.js/React
  • Multi-provider (OpenAI, Anthropic, Google, v.v.)

Phù hợp: Web apps, real-time chat, streaming UI

2. LangChain.js

Framework phổ biến nhất cho LLM applications. Có hệ sinh thái lớn với chains, agents, memory và integrations.

import { ChatOpenAI } from "@langchain/openai";
import { AgentExecutor, createOpenAIFunctionsAgent } from "langchain/agents";
import { DynamicTool } from "@langchain/core/tools";

const model = new ChatOpenAI({ modelName: "gpt-4o-mini" });

const tools = [
  new DynamicTool({
    name: "search",
    description: "Tìm kiếm thông tin trên internet",
    func: async (query: string) => {
      // Tìm kiếm logic
      return `Kết quả cho: ${query}`;
    }
  })
];

const agent = await createOpenAIFunctionsAgent({
  llm: model,
  tools,
  prompt: "Bạn là trợ lý hữu ích. Sử dụng tools để trả lời câu hỏi."
});

const executor = new AgentExecutor({ agent, tools });
const result = await executor.invoke({
  input: "Tìm giá vé máy bay đi Tokyo"
});

Ưu điểm:

  • Hệ sinh thái khổng lồ (100+ integrations)
  • Chains cho workflows phức tạp
  • RAG pipeline có sẵn
  • Community lớn, nhiều ví dụ

Phù hợp: Complex pipelines, RAG, data processing

3. LangGraph

Framework graph-based từ team LangChain. Sức mạnh nằm ở branching (rẽ nhánh), loops (vòng lặp) và state management — khác hoàn toàn pipeline tuyến tính.

Flow thực tế của LangGraph:

          ┌─────────┐
          │  Start   │
          └────┬─────┘

          ┌────▼─────┐
     ┌────│ Research  │────┐
     │    └──────────┘     │
     │                     │
┌────▼─────┐        ┌─────▼────┐
│ Web Search│        │ DB Query │   ← Parallel branches
└────┬─────┘        └─────┬────┘
     │                     │
     └──────┬──────────────┘

       ┌────▼─────┐
       │ Evaluate  │◄─────────┐
       └────┬─────┘           │
            │                 │
      ┌─────▼──────┐         │
      │ Good enough?│         │  ← Loop: retry nếu chưa đủ tốt
      └──┬──────┬──┘         │
    Yes  │      │  No         │
         │      └─────────────┘
    ┌────▼─────┐
    │ Generate  │
    │  Report   │
    └──────────┘
import { StateGraph, Annotation, END } from "@langchain/langgraph";
import { ChatOpenAI } from "@langchain/openai";

const AgentState = Annotation.Root({
  messages: Annotation<BaseMessage[]>({ reducer: (a, b) => [...a, ...b] }),
  searchResults: Annotation<string[]>({ reducer: (a, b) => [...a, ...b] }),
  quality: Annotation<number>(),
  retryCount: Annotation<number>()
});

async function research(state: typeof AgentState.State) {
  // Gọi nhiều sources song song bên trong node
  const [webResults, dbResults] = await Promise.all([
    searchWeb(state.messages), queryDB(state.messages)
  ]);
  return { searchResults: [...webResults, ...dbResults] };
}

async function evaluate(state: typeof AgentState.State) {
  const model = new ChatOpenAI({ modelName: "gpt-4o" });
  const score = await model.invoke(`Đánh giá quality 1-10: ${state.searchResults}`);
  return { quality: Number(score), retryCount: state.retryCount + 1 };
}

// ROUTING: đây là điểm khác biệt — conditional branching + loop
function decideNext(state: typeof AgentState.State) {
  if (state.quality >= 7) return "generate";     // ✅ Đủ tốt → generate
  if (state.retryCount >= 3) return "generate";   // ⚠️ Max retries → generate anyway
  return "research";                               // 🔄 Loop lại research
}

const workflow = new StateGraph(AgentState)
  .addNode("research", research)
  .addNode("evaluate", evaluate)
  .addNode("generate", generateReport)
  .addEdge("__start__", "research")
  .addEdge("research", "evaluate")
  // Conditional edges: rẽ nhánh dựa trên state
  .addConditionalEdges("evaluate", decideNext, {
    research: "research",    // Loop ngược lại
    generate: "generate"     // Đi tiếp
  })
  .addEdge("generate", END);

const app = workflow.compile();
const result = await app.invoke({
  messages: ["Nghiên cứu AI trends 2025"],
  retryCount: 0
});

Ưu điểm:

  • Branching: Rẽ nhánh dựa trên kết quả — không phải đường thẳng
  • Loops: Tự retry cho đến khi chất lượng đủ tốt
  • Stateful: Mọi node đọc/ghi shared state (quality, retryCount…)
  • Persistence: Checkpoint state, resume sau khi crash
  • Human-in-the-loop: Chèn human approval node vào bất kỳ đâu trong graph

Phù hợp: Agent workflows cần conditional logic, loops, và error recovery

4. CrewAI (Python)

Framework chuyên biệt cho multi-agent systems. Mỗi agent có role, goal và backstory riêng.

from crewai import Agent, Task, Crew

# Tạo agents với vai trò cụ thể
researcher = Agent(
    role="Senior Researcher",
    goal="Tìm thông tin chính xác về AI trends",
    backstory="Bạn là nhà nghiên cứu AI hàng đầu...",
    tools=[search_tool],
    llm="gpt-4o-mini"
)

writer = Agent(
    role="Content Writer",
    goal="Viết bài blog hấp dẫn từ research",
    backstory="Bạn là tech writer giỏi...",
    llm="gpt-4o-mini"
)

# Tạo tasks
research_task = Task(
    description="Nghiên cứu top 5 AI Agent trends 2025",
    agent=researcher,
    expected_output="Báo cáo chi tiết về 5 trends"
)

write_task = Task(
    description="Viết blog post từ research",
    agent=writer,
    expected_output="Blog post 500 từ"
)

# Crew = team of agents
crew = Crew(
    agents=[researcher, writer],
    tasks=[research_task, write_task],
    verbose=True
)

result = crew.kickoff()

Ưu điểm:

  • Multi-agent collaboration mạnh mẽ
  • Role-based agent design
  • Process orchestration (sequential, hierarchical)
  • Dễ hiểu cho beginners

Phù hợp: Multi-agent workflows, content pipelines, research automation

Bảng So Sánh

Tiêu chíVercel AI SDKLangChain.jsLangGraphCrewAI
Ngôn ngữTypeScriptTypeScript/PythonTypeScript/PythonPython
FocusStreaming UI + ToolsChains + AgentsStateful GraphsMulti-Agent
Learning curveThấpTrung bìnhCaoThấp
Multi-agentCơ bảnCó (graph nodes)Chuyên biệt
StreamingXuất sắcTốtTốtKhông
State managementCơ bảnCơ bảnXuất sắcCơ bản
EcosystemVercel/Next.jsRất lớnLangChainĐang phát triển
Production-ready⚠️

Chọn Framework Nào?

Cần streaming UI + Next.js?          → Vercel AI SDK
Cần RAG pipeline phổ biến?           → LangChain.js
Cần state machine, loops, branching? → LangGraph
Cần nhiều agents hợp tác?            → CrewAI
Prototype nhanh?                     → Vercel AI SDK
Enterprise, complex control flow?    → LangGraph

Tổng Kết

  • Vercel AI SDK là lựa chọn tốt nhất cho TypeScript developers xây dựng web apps
  • LangChain.js phù hợp khi cần nhiều integrations và complex pipelines
  • LangGraph mạnh nhất cho stateful agents với conditional logic và loops
  • CrewAI xuất sắc cho multi-agent collaboration
  • Trong series này, chúng ta sẽ chủ yếu dùng Vercel AI SDK (TypeScript) và CrewAI (Python)