Setup CrewAI trên VPS: orchestrate Claude + GPT crew agents

Chia sẻ bài viết

Mục lục
TL;DR
  • CrewAI là framework Python orchestrate multi-agent, focus role-based đơn giản hơn AutoGen.
  • Cài 1 dòng pip, chạy được trên VPS 2-4GB. Mỗi agent gắn model riêng (Claude, GPT, Ollama).
  • Cấu trúc: Crew (team) - Agent (role) - Task (job) - Tool (capability). Khai báo declarative.
  • Use case: research agent + writer agent + editor agent cho content marketing tự động.
  • Free tier: cost = chỉ API model. Pro tier (cloud Crew dashboard) ~99$/tháng, không bắt buộc.

CrewAI cùng với AutoGen, LangGraph là 3 framework multi-agent hot nhất 2026. Khác biệt CrewAI: API đơn giản, declarative, focus "role + task + tool" rất gần với cách dev VN nghĩ. Học 30 phút là viết được crew đầu tiên.

Bài này hướng dẫn self-host CrewAI trên VPS Ubuntu, build crew 3 agent (Researcher + Writer + Editor) cho task content marketing tự động, gắn Claude + GPT mix. Phù hợp dev/marketer VN muốn explore multi-agent workflow practical.

Mục tiêu cuối bài: bạn có CrewAI service chạy trên VPS, mỗi sáng tự động research topic, viết draft blog 1500 từ, edit lại, push vào WordPress draft. Time saved: 2-3 giờ/blog. Cost: ~0.5-1$ mỗi blog.

1. CrewAI vs AutoGen vs LangGraph

FrameworkTriết lýCode styleMaturity
CrewAIRole + Task + Tool, sequential/hierarchicalDeclarative YAML/Pythonv0.80+ ổn định
AutoGen (Microsoft)Conversation pattern, RoundRobin/SwarmPython lập trìnhv0.4 stable
LangGraph (LangChain)State machine graph, control flow tùy biếnPython low-levelMature

CrewAI dễ học nhất, AutoGen mạnh nhất cho conversation pattern phức tạp, LangGraph linh hoạt nhất cho flow tùy biến. Mình thường khuyên người mới dùng CrewAI trước, sau nâng cấp AutoGen/LangGraph khi cần.

2. Yêu cầu VPS

  • RAM: 2GB tối thiểu, 4GB khuyến nghị (cho crew >3 agent chạy song song).
  • vCPU: 2.
  • SSD: 20GB.
  • Ubuntu 22.04/24.04, Python 3.10+.
  • Network: tới Anthropic/OpenAI ổn định.

3. Cài CrewAI

sudo apt update
sudo apt install -y python3-pip python3-venv

# Virtualenv
python3 -m venv ~/crewai-venv
source ~/crewai-venv/bin/activate

# Cài CrewAI + tools optional
pip install -U crewai 'crewai[tools]'
pip install -U anthropic openai

# Kiểm tra
crewai --version

4. Tạo project crew đầu tiên

# CrewAI có CLI scaffold
crewai create crew content_factory
cd content_factory

# Cấu trúc:
# src/content_factory/
#   config/agents.yaml
#   config/tasks.yaml
#   crew.py
#   main.py
# .env

5. Khai báo agent trong YAML

# config/agents.yaml
researcher:
  role: "Researcher chuyên về tech VPS Việt Nam"
  goal: "Tìm thông tin chính xác và mới nhất về {topic}, ưu tiên nguồn tiếng Anh và VN"
  backstory: "Bạn là researcher 10 năm kinh nghiệm công nghệ, đọc nhanh, lọc tin tốt."

writer:
  role: "Blog writer tiếng Việt"
  goal: "Viết bài blog SEO 1500-2000 từ về {topic} dựa trên research"
  backstory: "Bạn là blogger viết tốt cho audience dev VN, văn phong thân thiện chuyên gia."

editor:
  role: "Editor và SEO specialist"
  goal: "Review bài viết, sửa lỗi, tối ưu SEO, đảm bảo structure H2/H3 chuẩn"
  backstory: "Bạn là editor 8 năm content marketing, biết Yoast SEO, structure cho rank."

6. Khai báo task trong YAML

# config/tasks.yaml
research_task:
  description: |
    Tìm hiểu sâu về topic: {topic}
    Output: bullet list 10 điểm quan trọng, mỗi điểm 2-3 câu, kèm source URL.
  expected_output: "Markdown 10 bullet với source URL"
  agent: researcher

write_task:
  description: |
    Viết blog 1500-2000 từ tiếng Việt về {topic} dựa trên research từ Researcher.
    Structure: TL;DR -> 8-10 H2 -> kết luận. Tone chuyên gia thân thiện.
  expected_output: "Markdown blog full structure"
  agent: writer

edit_task:
  description: |
    Review bài blog, fix grammar, optimize SEO (focus_kw: {focus_kw}),
    đảm bảo từ khóa xuất hiện trong title, H2, paragraph đầu.
  expected_output: "Markdown blog đã edit"
  agent: editor

7. Define Crew trong Python

# src/content_factory/crew.py
from crewai import Agent, Crew, Task, Process
from crewai.project import CrewBase, agent, task, crew
from crewai_tools import SerperDevTool
from langchain_anthropic import ChatAnthropic
from langchain_openai import ChatOpenAI

@CrewBase
class ContentFactoryCrew:
    agents_config = "config/agents.yaml"
    tasks_config = "config/tasks.yaml"

    @agent
    def researcher(self) -> Agent:
        return Agent(
            config=self.agents_config["researcher"],
            llm=ChatAnthropic(model="claude-sonnet-4-7-20260301"),
            tools=[SerperDevTool()],
            verbose=True
        )

    @agent
    def writer(self) -> Agent:
        return Agent(
            config=self.agents_config["writer"],
            llm=ChatAnthropic(model="claude-sonnet-4-7-20260301"),
            verbose=True
        )

    @agent
    def editor(self) -> Agent:
        return Agent(
            config=self.agents_config["editor"],
            llm=ChatOpenAI(model="gpt-5-mini"),
            verbose=True
        )

    @task
    def research_task(self) -> Task:
        return Task(config=self.tasks_config["research_task"])

    @task
    def write_task(self) -> Task:
        return Task(config=self.tasks_config["write_task"])

    @task
    def edit_task(self) -> Task:
        return Task(config=self.tasks_config["edit_task"], output_file="blog.md")

    @crew
    def crew(self) -> Crew:
        return Crew(
            agents=self.agents,
            tasks=self.tasks,
            process=Process.sequential,
            verbose=True
        )

8. File .env và main.py

# .env
ANTHROPIC_API_KEY=sk-ant-api03-xxx
OPENAI_API_KEY=sk-xxx
SERPER_API_KEY=xxx  # google search tool
# src/content_factory/main.py
from content_factory.crew import ContentFactoryCrew

def run():
    inputs = {
        "topic": "Cloud VPS cho dev VN 2026",
        "focus_kw": "cloud vps dev vn"
    }
    result = ContentFactoryCrew().crew().kickoff(inputs=inputs)
    print(result)

if __name__ == "__main__":
    run()
# Chạy
crewai run
# Hoặc python -m content_factory.main

Trong 2-4 phút, crew sẽ research (gọi Serper search), viết draft 1500 từ, edit lại. Output lưu vào blog.md.

9. Tích hợp với WordPress qua REST API

# Thêm task push WordPress
push_to_wp_task:
  description: |
    Đọc file blog.md, POST tới WordPress REST API tạo post draft.
    Endpoint: https://your-domain.com/wp-json/wp/v2/posts
    Auth: application password
  expected_output: "post_id của draft tạo được"
  agent: editor
# Tool custom Python
from crewai_tools import tool
import requests, base64

@tool("PostToWordPress")
def post_to_wp(title: str, content: str, status: str = "draft") -> str:
    """Post bài lên WordPress qua REST API"""
    user = "admin"
    pwd = "your_app_password"
    auth = base64.b64encode(f"{user}:{pwd}".encode()).decode()
    r = requests.post(
        "https://your-domain.com/wp-json/wp/v2/posts",
        headers={"Authorization": f"Basic {auth}"},
        json={"title": title, "content": content, "status": status}
    )
    return f"Post created with ID {r.json()['id']}"

10. Hierarchical process: Manager agent

CrewAI hỗ trợ 2 process: Sequential (chạy task theo thứ tự) và Hierarchical (manager agent delegate task cho worker agent động).

# Hierarchical: thêm manager
return Crew(
    agents=[researcher, writer, editor],
    tasks=[main_task],
    process=Process.hierarchical,
    manager_llm=ChatAnthropic(model="claude-opus-4-7"),
    verbose=True
)

Hierarchical phù hợp khi task không xác định trước thứ tự. Manager (thường dùng Opus mạnh hơn) sẽ decide gọi agent nào, đợi kết quả, chia lại task. Cost cao hơn nhưng smart hơn.

11. Schedule crew chạy daily

# Cron 6h sáng hằng ngày
crontab -e

0 6 * * * cd /home/dev/content_factory && /home/dev/crewai-venv/bin/python -m content_factory.main >> /var/log/crew.log 2>&1

Mỗi sáng có 1 blog draft mới trong WordPress, editor chỉ review + tinh chỉnh + publish. Tiết kiệm 2-3 giờ/blog, scale 5-10 blog/tuần dễ.

12. Tối ưu cost

  • Mix model: Claude Sonnet cho researcher + writer, GPT-5-mini cho editor đơn giản.
  • Max iter: set Agent(max_iter=5) tránh agent loop tốn token.
  • Prompt caching: Claude hỗ trợ cache 1h, repeat task cùng research base giảm 80% cost.
  • Memory: Crew.memory=False khi không cần (tiết kiệm context).
  • Monitor: log token usage qua callback, alert khi vượt budget.
Cloud VPS cho vibe coder

VPS 2-4GB chạy CrewAI orchestrate multi-agent 24/7

Cloud VPS TND Ubuntu 24.04, SSD CEPH, snapshot 1-click, backup hằng ngày, network 200Mbps. Đủ resource cho Python venv + crew agent + cron schedule, latency thấp tới Anthropic/OpenAI cho agent realtime kickoff.

Xem 8 cấu hình Cloud VPS →

FAQ

CrewAI khác LangChain Agent như thế nào?

LangChain Agent là single-agent ReAct pattern (Reasoning + Acting). CrewAI multi-agent với role-based. CrewAI dùng LangChain dưới hood cho LLM client + tool, nhưng abstract cao hơn. Khi cần đa role cộng tác, CrewAI cleaner. Khi cần 1 agent thông minh dùng nhiều tool, LangChain Agent đủ.

CrewAI có miễn phí không?

CrewAI framework Python hoàn toàn miễn phí MIT license. CrewAI Plus (cloud dashboard, deploy, monitor) ~99$/tháng cho team enterprise. Cá nhân + startup nhỏ chỉ cần framework free, deploy trên VPS riêng. Cost duy nhất: API model (Claude/GPT).

Multi-agent có cần GPU không?

Không. CrewAI chỉ orchestrate, model chạy ở API (Claude, GPT) hoặc Ollama (CPU OK cho 7B). VPS CPU 2-4GB chạy được. Cần GPU khi tự host model lớn (Llama 70B) local, không phải yêu cầu framework.

Có tool ngoài cho CrewAI: scraping, file, DB không?

Có. crewai_tools package có sẵn ~30 tool: SerperDevTool (search), ScrapeWebsiteTool, FileReadTool, DirectoryReadTool, PGSearchTool, GithubSearchTool. Tự viết tool dễ với decorator @tool. MCP server cũng tích hợp được qua adapter community.

Cách debug khi agent loop hoặc trả output sai?

Bật verbose=True trên Agent và Crew, log full conversation. Set max_iter giới hạn vòng. Thêm callback callback_handler để intercept mỗi step. Reduce complexity: chia task lớn thành sub-task nhỏ, mỗi sub-task 1 agent rõ ràng. Tránh prompt mơ hồ ("hãy làm sao cho tốt").

CrewAI có support tiếng Việt tốt?

Tự thân CrewAI không liên quan ngôn ngữ - chất lượng phụ thuộc model. Claude Sonnet 4.7 và GPT-5 viết tiếng Việt tự nhiên, agent role/goal/backstory viết tiếng Việt OK. Mình hay viết role/goal tiếng Việt, task description tiếng Việt + technical term tiếng Anh, output tự nhiên VN.

2009
15+ năm vận hành liên tục
10+
tập đoàn lớn tin dùng
100+
doanh nghiệp SMB Việt
30 ngày
đổi key lỗi miễn phí
Phần mềm bản quyền chính hãng chúng tôi cung cấp
Bản quyền chính hãng Hóa đơn VAT đầy đủ Đổi key lỗi 30 ngày Vận hành từ 2009 MST 0200994870 Hotline 0225.999.6666