CrewAI là framework Python mã nguồn mở giúp bạn xây dựng hệ thống multi-agent AI. Thay vì dùng một AI chatbot duy nhất, bạn tạo ra cả một đội ngũ AI agents, mỗi agent có vai trò riêng, cùng phối hợp hoàn thành công việc. Bài viết này hướng dẫn chi tiết từ cài đặt đến chạy project CrewAI đầu tiên.
CrewAI là gì?

CrewAI là framework Python cho phép tạo và điều phối nhiều AI agents cùng làm việc. Mỗi agent được gán một role (vai trò), goal (mục tiêu) và backstory (bối cảnh). Khi ghép các agents lại thành một crew, chúng tự phối hợp để giải quyết task phức tạp.
Ví dụ thực tế: bạn tạo một agent Researcher chuyên tìm kiếm thông tin, một agent Writer chuyên viết bài. Researcher tìm dữ liệu xong, tự động chuyển cho Writer viết thành báo cáo hoàn chỉnh. Toàn bộ quy trình chạy tự động.
CrewAI do João Moura phát triển từ cuối 2023, hiện đã có hơn 25.000 GitHub stars và cộng đồng phát triển rất nhanh. Phiên bản mới nhất (1.x) hỗ trợ native providers cho OpenAI, Anthropic, Gemini, Bedrock, và nhiều LLM khác.
So sánh nhanh: CrewAI vs LangGraph vs AutoGen
Ba framework phổ biến nhất cho multi-agent AI hiện nay:
- CrewAI: Thiết kế theo role-based, dễ bắt đầu nhất. Phù hợp prototyping nhanh, tạo nội dung, automation workflows. Learning curve thấp.
- LangGraph (LangChain): Graph-based state machine, kiểm soát chi tiết luồng xử lý. Phù hợp production-grade workflows cần traceability và human-in-the-loop phức tạp. Learning curve cao.
- AutoGen (Microsoft): Conversation-driven, agents giao tiếp qua tin nhắn. Mạnh về code execution, phù hợp research và developer tools. Đang trong giai đoạn chuyển đổi sang Microsoft Agent Framework.
Thông tin: CrewAI có hơn 25.000 GitHub stars, MIT license, hỗ trợ Python 3.10-3.13. Framework hoàn toàn miễn phí cho self-hosted. CrewAI cũng cung cấp CrewAI AMP Cloud (dịch vụ managed) cho doanh nghiệp.
Kiến trúc CrewAI: Agent, Task, Tool, Crew

CrewAI xoay quanh 4 khái niệm cốt lõi. Nắm vững 4 thành phần này là bạn hiểu toàn bộ cách CrewAI hoạt động.
Agent
Agent là một thực thể AI có role, goal, backstory. Mỗi agent hoạt động như một thành viên trong team. Ví dụ: agent “Senior Researcher” có mục tiêu tìm kiếm thông tin mới nhất, được cung cấp công cụ tìm kiếm web.
Task
Task là công việc cụ thể giao cho agent. Mỗi task có description (mô tả), expected_output (kết quả mong đợi), và agent phụ trách. Task có thể nhận context từ task trước đó.
Tool
Tool là công cụ mà agent sử dụng để hoàn thành task. CrewAI cung cấp hàng trăm built-in tools: tìm kiếm web, đọc file, scrape website, query database… Bạn cũng có thể tạo custom tools riêng.
Crew
Crew là đội ngũ gồm nhiều agents + tasks. Crew quyết định cách agents phối hợp: chạy tuần tự (sequential) hay phân cấp (hierarchical). Khi gọi crew.kickoff(), toàn bộ workflow bắt đầu thực thi.
Luồng xử lý: Input → Agent nhận Task → Agent dùng Tool xử lý → Output chuyển cho Agent tiếp theo → Crew trả kết quả cuối cùng.
Yêu cầu cài đặt

Trước khi bắt đầu, bạn cần chuẩn bị:
- Python 3.10 đến 3.13: CrewAI chưa hỗ trợ Python 3.14+
- uv: Package manager nhanh, CrewAI CLI dùng uv để quản lý dependencies
- API key của ít nhất một LLM provider: OpenAI, Anthropic, Google Gemini, Groq, hoặc Ollama (chạy local, miễn phí)
- Hệ điều hành: macOS, Linux, hoặc Windows (WSL2 khuyến nghị)
Tip: Nếu bạn chạy CrewAI cho production (lượng request lớn, chạy liên tục), nên deploy trên VPS thay vì máy cá nhân. VPS có uptime cao, bandwidth ổn định, và bạn không phải lo máy tắt giữa chừng. Xem thêm hướng dẫn chọn VPS giá rẻ phù hợp.
Cài đặt CrewAI từng bước

Bên dưới là các bước cài đặt chi tiết. Mình demo trên môi trường Docker (Python 3.12), nhưng bạn có thể làm tương tự trên máy local.
Bước 1: Cài uv
uv là package manager viết bằng Rust, nhanh hơn pip rất nhiều lần. CrewAI CLI cần uv để tạo và quản lý project.
# Trên macOS/Linux
curl -LsSf https://astral.sh/uv/install.sh | sh
# Hoặc cài qua pip
pip install uv
# Kiểm tra
uv --version
# uv 0.11.2
Bước 2: Cài CrewAI CLI
Dùng uv tool install để cài CrewAI CLI global, có thể gọi lệnh crewai từ terminal.
# Cài CrewAI CLI
uv tool install crewai
# Kiểm tra version
crewai version
# crewai version: 1.12.2
Bước 3: Tạo project mới
Lệnh crewai create crew tạo toàn bộ cấu trúc project cho bạn. CLI sẽ hỏi bạn chọn LLM provider và model.
# Tạo project mới tên research_demo
crewai create crew research_demo
# CLI hỏi bạn chọn provider:
# 1. openai
# 2. anthropic
# 3. gemini
# ...
# Chọn provider → chọn model → nhập API key
# Kết quả:
# Created research_demo/pyproject.toml
# Created research_demo/src/research_demo/crew.py
# Created research_demo/src/research_demo/main.py
# Created research_demo/src/research_demo/config/agents.yaml
# Created research_demo/src/research_demo/config/tasks.yaml
# Crew research_demo created successfully!
Bước 4: Cấu hình .env
File .env chứa model và API key. CrewAI tự tạo file này khi bạn chọn provider ở bước trên. Bạn có thể chỉnh lại bất cứ lúc nào.
# .env - Ví dụ dùng Gemini
MODEL=gemini/gemini-2.5-flash-preview-04-17
GEMINI_API_KEY=your-api-key-here
# Hoặc dùng OpenAI
# MODEL=openai/gpt-4o-mini
# OPENAI_API_KEY=sk-your-key-here
# Hoặc dùng Ollama (miễn phí, chạy local)
# MODEL=ollama/llama3.2
# OPENAI_API_BASE=http://localhost:11434
Cấu trúc project CrewAI

Sau khi tạo project, bạn sẽ thấy cấu trúc thư mục như sau:
research_demo/
├── .env # API key và model config
├── .gitignore
├── pyproject.toml # Dependencies (giống package.json)
├── README.md
├── knowledge/ # Thư mục chứa knowledge sources
│ └── user_preference.txt
└── src/
└── research_demo/
├── __init__.py
├── main.py # Entry point - nơi chạy crew
├── crew.py # Định nghĩa Crew, agents, tasks
├── config/
│ ├── agents.yaml # Cấu hình agents (role, goal, backstory)
│ └── tasks.yaml # Cấu hình tasks (description, expected_output)
└── tools/
├── __init__.py
└── custom_tool.py # Custom tools bạn tự viết
Các file quan trọng nhất:
- agents.yaml: Khai báo agents. Mỗi agent cần role, goal, backstory.
- tasks.yaml: Khai báo tasks. Mỗi task cần description, expected_output, agent.
- crew.py: Code Python gắn agents + tasks lại thành crew. Dùng decorator
@CrewBase. - main.py: Entry point gọi
crew.kickoff()để chạy.
Tạo Agents (agents.yaml)

File agents.yaml là nơi bạn định nghĩa các AI agents. Mỗi agent cần 3 thuộc tính chính:
- role: Vai trò của agent. Ví dụ: “Senior Data Researcher”
- goal: Mục tiêu agent cần đạt được
- backstory: Bối cảnh giúp agent hiểu mình là ai, tạo persona cho LLM
Dưới đây là file agents.yaml mẫu với 2 agents: Researcher tìm thông tin, Writer viết báo cáo.
# src/research_demo/config/agents.yaml
researcher:
role: >
{topic} Senior Data Researcher
goal: >
Uncover cutting-edge developments in {topic}
backstory: >
You're a seasoned researcher with a knack for uncovering the latest
developments in {topic}. Known for your ability to find the most relevant
information and present it in a clear and concise manner.
reporting_analyst:
role: >
{topic} Reporting Analyst
goal: >
Create detailed reports based on {topic} data analysis and research findings
backstory: >
You're a meticulous analyst with a keen eye for detail. You're known for
your ability to turn complex data into clear and concise reports, making
it easy for others to understand and act on the information you provide.
Chú ý {topic} là biến động. Khi gọi kickoff(inputs={"topic": "AI LLMs"}), CrewAI tự thay thế {topic} thành “AI LLMs” trong tất cả agents và tasks.
Tạo Tasks (tasks.yaml)

File tasks.yaml khai báo các công việc cụ thể. Mỗi task gồm:
- description: Mô tả chi tiết task cần làm gì
- expected_output: Kết quả mong đợi (giúp agent biết output cần trông như thế nào)
- agent: Tên agent phụ trách task này
- context (tùy chọn): Danh sách task trước đó mà task này cần kết quả làm input
# src/research_demo/config/tasks.yaml
research_task:
description: >
Conduct a thorough research about {topic}.
Make sure you find any interesting and relevant information given
the current year is {current_year}.
expected_output: >
A list with 10 bullet points of the most relevant information about {topic}
agent: researcher
reporting_task:
description: >
Review the context you got and expand each topic into a full section
for a report. Make sure the report is detailed and contains any and
all relevant information.
expected_output: >
A fully fledged report with the main topics, each with a full section
of information. Formatted as markdown without '```'
agent: reporting_analyst
Tip: Dùng {variable} để tạo dynamic input. Bạn có thể truyền bất kỳ biến nào khi gọi kickoff(inputs={...}). Cách này giúp tái sử dụng cùng một crew cho nhiều chủ đề khác nhau.
Tạo Crew và chạy (crew.py + main.py)

File crew.py là nơi ghép agents + tasks thành một crew hoàn chỉnh. CrewAI dùng decorator @CrewBase để tự động map agents.yaml và tasks.yaml vào code Python.
# src/research_demo/crew.py
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
@CrewBase
class ResearchDemo():
"""ResearchDemo crew"""
# Decorator @agent map với key trong agents.yaml
@agent
def researcher(self) -> Agent:
return Agent(
config=self.agents_config['researcher'],
verbose=True # In chi tiết quá trình suy nghĩ
)
@agent
def reporting_analyst(self) -> Agent:
return Agent(
config=self.agents_config['reporting_analyst'],
verbose=True
)
# Decorator @task map với key trong tasks.yaml
@task
def research_task(self) -> Task:
return Task(
config=self.tasks_config['research_task'],
)
@task
def reporting_task(self) -> Task:
return Task(
config=self.tasks_config['reporting_task'],
output_file='report.md' # Xuất kết quả ra file
)
# Decorator @crew tạo Crew object
@crew
def crew(self) -> Crew:
return Crew(
agents=self.agents, # Tự động lấy từ @agent decorators
tasks=self.tasks, # Tự động lấy từ @task decorators
process=Process.sequential, # Chạy tuần tự
verbose=True,
)
File main.py là entry point, nơi bạn gọi kickoff():
# src/research_demo/main.py
from datetime import datetime
from research_demo.crew import ResearchDemo
def run():
inputs = {
'topic': 'AI LLMs',
'current_year': str(datetime.now().year)
}
# Chạy crew - bắt đầu toàn bộ workflow
ResearchDemo().crew().kickoff(inputs=inputs)
Quy trình tuần tự và phân cấp
CrewAI hỗ trợ 2 kiểu process:
- Sequential: Tasks chạy lần lượt theo thứ tự. Task sau nhận kết quả task trước làm context. Đơn giản, dễ debug.
- Hierarchical: Có một manager agent tự động phân chia và delegate tasks cho các agents. Manager quyết định thứ tự và agent nào làm gì. Phù hợp workflow phức tạp.
Chạy crew và xem kết quả
Chạy project bằng lệnh crewai run:
cd research_demo
crewai run
Output mẫu khi chạy (rút gọn):
╭──────────────── 🚀 Crew Execution Started ────────────────╮
│ Crew Execution Started │
│ Name: crew │
│ ID: 5f4578aa-ade6-40d8-a7d5-4e8f02df1af0 │
╰────────────────────────────────────────────────────────────╯
╭──────────────────── 📋 Task Started ──────────────────────╮
│ Task Started: research_task │
╰────────────────────────────────────────────────────────────╯
╭──────────────────── 🤖 Agent Started ─────────────────────╮
│ Agent: AI LLMs Senior Data Researcher │
│ Task: Conduct a thorough research about AI LLMs... │
╰────────────────────────────────────────────────────────────╯
# Agent Working... (gọi LLM, xử lý task)
╭──────────────────── ✅ Task Completed ────────────────────╮
│ Task Completed: research_task │
│ Agent: AI LLMs Senior Data Researcher │
╰────────────────────────────────────────────────────────────╯
╭──────────────────── 📋 Task Started ──────────────────────╮
│ Task Started: reporting_task │
╰────────────────────────────────────────────────────────────╯
╭──────────────────── 🤖 Agent Started ─────────────────────╮
│ Agent: AI LLMs Reporting Analyst │
│ Task: Review the context and expand into full report... │
╰────────────────────────────────────────────────────────────╯
# Agent Working... (nhận kết quả research, viết report)
╭──────────────────── ✅ Task Completed ────────────────────╮
│ Task Completed: reporting_task │
│ Output saved to: report.md │
╰────────────────────────────────────────────────────────────╯
╭──────────────── 🎉 Crew Execution Completed ──────────────╮
│ Crew Execution Completed │
│ Name: crew │
╰────────────────────────────────────────────────────────────╯
Kết quả cuối cùng được ghi vào file report.md. Toàn bộ workflow hoàn thành tự động: Researcher tìm thông tin, Reporting Analyst nhận kết quả và viết thành báo cáo chi tiết.
Flows: luồng xử lý nâng cao theo sự kiện

Từ phiên bản 0.80+, CrewAI giới thiệu Flows: cách xây dựng workflow phức tạp hơn, kết hợp code Python thường với Crew execution.
Flows vs Crews: Khi nào dùng cái nào?
- Crew: Khi bạn cần nhiều agents phối hợp hoàn thành một nhóm tasks liên quan. Ví dụ: research + viết report.
- Flow: Khi bạn cần workflow nhiều bước, xen kẽ giữa code Python logic (if/else, loop, API calls) và các Crew executions. Ví dụ: nhận input → validate → gọi Crew phân tích → kiểm tra kết quả → gọi Crew khác viết email.
Ví dụ Flow đơn giản
from crewai.flow.flow import Flow, listen, start
from litellm import completion
class CityFactFlow(Flow):
model = "gpt-4o-mini"
@start()
def generate_city(self):
"""Bước 1: Tạo tên thành phố ngẫu nhiên"""
response = completion(
model=self.model,
messages=[{
"role": "user",
"content": "Return the name of a random city in the world."
}]
)
random_city = response["choices"][0]["message"]["content"]
print(f"Random City: {random_city}")
return random_city
@listen(generate_city)
def generate_fun_fact(self, random_city):
"""Bước 2: Lắng nghe kết quả bước 1, tạo fun fact"""
response = completion(
model=self.model,
messages=[{
"role": "user",
"content": f"Tell me a fun fact about {random_city}"
}]
)
return response["choices"][0]["message"]["content"]
# Chạy flow
flow = CityFactFlow()
result = flow.kickoff()
print(f"Fun fact: {result}")
Decorator @start() đánh dấu bước đầu tiên. @listen(generate_city) đánh dấu bước tiếp theo sẽ tự chạy khi generate_city hoàn thành. Flow hỗ trợ state management tự động: mỗi flow instance có ID riêng, dữ liệu được lưu xuyên suốt các bước.
Kết hợp Flow + Crew
Sức mạnh thực sự của Flows là kết hợp với Crew. Bạn có thể tạo một Flow với bước 1 là xử lý dữ liệu bằng Python, bước 2 gọi Crew để agents phân tích, bước 3 lại dùng Python gửi email kết quả.
from crewai.flow.flow import Flow, listen, start
class ContentPipeline(Flow):
@start()
def fetch_topics(self):
"""Bước 1: Lấy danh sách topics từ API"""
# Code Python thường, gọi API, query database...
return ["AI Agents", "RAG patterns", "Fine-tuning LLMs"]
@listen(fetch_topics)
def research_and_write(self, topics):
"""Bước 2: Dùng Crew để research + viết bài"""
from research_demo.crew import ResearchDemo
results = []
for topic in topics:
result = ResearchDemo().crew().kickoff(
inputs={"topic": topic, "current_year": "2026"}
)
results.append(result)
return results
@listen(research_and_write)
def publish(self, results):
"""Bước 3: Publish kết quả"""
for r in results:
print(f"Publishing: {r.raw[:100]}...")
return "Done"
Ứng dụng thực tế của CrewAI

CrewAI phù hợp cho nhiều bài toán thực tế. Dưới đây là những ứng dụng phổ biến nhất.
Quy trình tạo nội dung tự động
Tạo một crew gồm Researcher, Writer, Editor. Researcher tìm keyword và thông tin. Writer viết bài dựa trên research. Editor review, sửa lỗi, tối ưu SEO. Output là bài viết hoàn chỉnh, sẵn sàng publish.
Tự động nghiên cứu và phân tích
Crew phân tích thị trường: agent thu thập dữ liệu từ nhiều nguồn, agent phân tích xu hướng, agent tổng hợp thành báo cáo. Có thể dùng cho phân tích cổ phiếu, nghiên cứu đối thủ, hoặc tổng hợp paper học thuật.
Hỗ trợ khách hàng đa agent
Agent phân loại ticket, agent trả lời câu hỏi thường gặp, agent escalate vấn đề phức tạp cho người thật. Mỗi agent xử lý đúng phần việc của mình.
Quy trình xử lý dữ liệu
Agent thu thập data từ API, agent làm sạch và chuẩn hóa, agent phân tích và tạo visualization. Phù hợp cho ETL workflows hoặc data enrichment.
Tip: CrewAI production workloads cần server chạy liên tục. AZDIGI Pro VPS với CPU mạnh và RAM lớn là lựa chọn phù hợp để deploy CrewAI agents. Bạn có thể kết hợp CrewAI với Docker Compose để dễ dàng manage và scale.
Câu hỏi thường gặp
Tổng kết
CrewAI là framework multi-agent AI dễ tiếp cận nhất hiện tại. Bạn chỉ cần vài file YAML để khai báo agents và tasks, vài dòng Python để ghép thành crew, rồi crewai run là xong. Framework xử lý toàn bộ phần phức tạp: giao tiếp giữa agents, truyền context, quản lý memory.
Nếu bạn đang tìm cách tự động hóa workflow bằng AI, CrewAI là điểm bắt đầu tốt. Kết hợp với OpenClaw để điều phối agents qua chat, hoặc deploy trên VPS để chạy production, khả năng mở rộng gần như không giới hạn.
Bắt đầu với một crew đơn giản, rồi thêm agents, tools, flows dần dần khi bạn quen với framework. Đó là cách học CrewAI hiệu quả nhất.
Có thể bạn cần xem thêm
- n8n + AI: Xây dựng Workflow tự động với ChatGPT và LLMs
- Hướng dẫn dùng Subagents trong Claude để tạo trợ lý AI thông minh
- Cài đặt Dify AI trên VPS - No-code AI platform miễn phí
- 20 kinh nghiệm khi sử dụng Claude Code
- Kết nối OpenClaw với nhiều AI cùng lúc: Claude, ChatGPT, Gemini
- Ollama API - Tích hợp AI self-hosted vào ứng dụng web
Về tác giả
Trần Thắng
Chuyên gia tại AZDIGI với nhiều năm kinh nghiệm trong lĩnh vực web hosting và quản trị hệ thống.