Kamu punya tugas riset yang butuh searching web, analisis hasilnya, lalu nulis laporan terstruktur. Satu panggilan LLM bisa ngelakuin ketiganya, tapi hasilnya biasanya dangkal. Tiap langkah butuh konteks sendiri, prompt sendiri, dan kemampuan pake tool. Itu yang dibikin CrewAI.
CrewAI bikin kamu bisa define agent dengan role spesifik, kasih tool ke masing-masing, sambungkan task mereka, dan biarin mereka oper hasil ke satu sama lain. Kamu bisa jalanin task dalam urutan tetap (sequential) atau biar manager agent yang delegate berdasarkan siapa yang paling cocok (hierarchical). Tutorial ini bahas keduanya.
Prasyarat
- Python 3.10 atau lebih tinggi (cek dengan
python3 --version). CrewAI butuh Python >=3.10 dan <3.14. uvudah terinstall. Kalau belum:curl -LsSf https://astral.sh/uv/install.sh | sh- OpenAI API key (atau provider LLM lain, lihat docs CrewAI untuk alternatif).
- Serper.dev API key buat web search. Tier gratis kasih 2,500 query, cukup buat testing.
Langkah 1: Install CrewAI
Install CrewAI CLI sebagai tool global:
uv tool install crewai
Cek instalasi:
uv tool list
# crewai v1.x.x
# - crewai
Kalau kena warning PATH, jalanin uv tool update-shell dan restart terminal.
Langkah 2: Scaffold project baru
Buat crew project:
crewai create crew research-crew
cd research-crew
Ini bikin folder dengan src/research_crew/ yang isinya file config, direktori agents, dan tasks. Project default pake file config JSONC untuk definisi agent dan crew, sesuai struktur yang direkomendasiin saat ini.
Set API key di .env di root project:
OPENAI_API_KEY=sk-your-key-here
SERPER_API_KEY=your-serper-key-here
Langkah 3: Define tiga agent
Buka src/research_crew/config/agents.yaml. Ganti isinya dengan tiga agent: researcher, analyst, dan writer.
researcher:
role: "Senior Research Analyst"
goal: "Find credible, recent information about {topic} using web search"
backstory: "You are a meticulous researcher. You cross-reference sources, prefer primary documentation over blog posts, and flag uncertainty rather than guessing."
tools: ["serper_dev_tool"]
verbose: true
analyst:
role: "Research Synthesizer"
goal: "Analyze the raw findings and identify key themes, contradictions, and gaps"
backstory: "You have spent years turning messy research notes into structured analysis. You care about what the evidence actually says, not what sounds compelling."
verbose: true
writer:
role: "Technical Report Writer"
goal: "Turn the analysis into a clear, well-structured markdown report"
backstory: "You write reports that engineers and product managers can act on. You use clear headings, avoid filler, and cite sources inline."
verbose: true
Tiap agent punya role (apa yang dia lakukan), goal (apa yang dia optimalkan), dan backstory (kepribadian dan gaya kerja). Field tools list nama tool yang CrewAI resolve dari toolkit bawaan. Cuman researcher yang dapet Serper web search tool di sini, dua lainnya kerja sama text.
Langkah 4: Define task
Buka src/research_crew/config/tasks.yaml. Ganti isinya:
research_task:
description: "Search the web for recent, credible information about {topic}. Focus on: (1) what the topic is and why it matters now, (2) key tools or projects, (3) notable practitioners or companies, (4) open debates or criticism. Use at least 5 different search queries to get coverage. Return raw findings with source URLs."
expected_output: "A list of findings with source URLs, organized by the four focus areas. 800-1200 words."
agent: researcher
analysis_task:
description: "Read the research findings and produce a structured analysis. Identify 3-5 key themes. Note where sources agree, where they contradict, and where evidence is thin. Suggest what the report should emphasize."
expected_output: "A structured analysis with 3-5 themes, each with a summary, supporting evidence, and confidence level. 500-800 words."
agent: analyst
writing_task:
description: "Write a markdown report based on the analysis. Structure: executive summary, key themes (one section each), implications, and a sources list. Keep paragraphs short. No marketing language."
expected_output: "A markdown report, 1500-2000 words, with clear headings, inline source citations, and a sources section at the end."
agent: writer
output_file: "output/report.md"
Field context opsional dan bikin satu task bisa lihat output task lain. Di mode sequential, tiap task otomatis dapet output task sebelumnya sebagai context, jadi kamu nggak perlu set manual. Field output_file di task terakhir simpen laporan akhir ke disk.
Langkah 5: Sambungkan crew
Buka src/research_crew/crew.py dan ganti isinya:
from crewai import Agent, Crew, Process, Task
from crewai_tools import SerperDevTool
from pydantic import BaseModel
import yaml
from pathlib import Path
# Load config
config_dir = Path(__file__).parent / "config"
def load_yaml(name):
with open(config_dir / f"{name}.yaml") as f:
return yaml.safe_load(f)
agents_config = load_yaml("agents")
tasks_config = load_yaml("tasks")
# Tool
serper = SerperDevTool()
# Build agents
agents = []
for key, cfg in agents_config.items():
tools = []
if "serper_dev_tool" in cfg.get("tools", []):
tools = [serper]
agent = Agent(
role=cfg["role"],
goal=cfg["goal"],
backstory=cfg["backstory"],
tools=tools,
verbose=cfg.get("verbose", False),
)
agents.append(agent)
agent_map = {key: agent for key, agent in zip(agents_config.keys(), agents)}
# Build tasks
tasks = []
for key, cfg in tasks_config.items():
task = Task(
description=cfg["description"],
expected_output=cfg["expected_output"],
agent=agent_map[cfg["agent"]],
output_file=cfg.get("output_file"),
)
tasks.append(task)
# The crew
research_crew = Crew(
agents=agents,
tasks=tasks,
process=Process.sequential,
verbose=True,
)
Bagian-bagian penting: Crew nerima list agent, list task, dan tipe process. Process.sequential berarti task jalan dalam urutan list, dan tiap task dapet output task sebelumnya sebagai context. SerperDevTool dateng dari crewai_tools dan bungkus search API Serper.dev.
Langkah 6: Jalanin crew
Kick off crew dengan topik:
crewai run
Atau langsung dari Python:
from research_crew.crew import research_crew
result = research_crew.kickoff(inputs={"topic": "Model Context Protocol"})
print(result.raw)
Kamu harus lihat verbose log yang nunjukin tiap agent ngerjain task, pake tool (researcher bakal nunjukin query search), dan oper output ke agent berikutnya. Laporan akhir mendarat di output/report.md.
Switch ke proses hierarchical
Sequential cocok kalau urutan task tetap dan jelas. Kalau urutan kurang jelas, atau kamu mau agent yang mutusin siapa ngerjain apa, pake hierarchical process. Ini nambah manager agent yang delegate task.
Ganti definisi crew:
from crewai import Agent, Crew, Process, Task
manager = Agent(
role="Research Project Manager",
goal="Coordinate the research crew to produce the best report for {topic}",
backstory="You are a project manager who delegates to the right specialist and keeps the work moving.",
allow_delegation=True,
verbose=True,
)
research_crew = Crew(
agents=agents,
tasks=tasks,
process=Process.hierarchical,
manager_llm="gpt-4o",
verbose=True,
)
result = research_crew.kickoff(inputs={"topic": "Model Context Protocol"})
Di mode hierarchical, manager agent nerima list task dan mutusin urutan eksekusi serta delegation. Tiap agent juga bisa delegate ke agent lain kalau allow_delegation=True diset di mereka. Parameter manager_llm specify model mana yang dipake manager untuk planning dan delegation. Kamu harus provide ini karena manager adalah agent yang auto-generated, bukan yang kamu define di YAML.
Trade-off-nya: hierarchical lebih fleksibel tapi makan lebih banyak token dan kurang predictable. Buat pipeline tetap seperti research-analyze-write, sequential lebih cocok jadi default. Hierarchical worth it kalau task punya dependency yang tergantung hasil intermediate.
Kapan pake CrewAI vs alternatif
CrewAI pas kalau kamu punya workflow multi-step di mana tiap step butuh role atau toolset berbeda, dan antar step benefit dari oper context. Config basis YAML bikin gampang ubah behavior agent tanpa sentuh code.
Kalau kamu butuh kontrol granular atas graf percakapan (conditional branching, loop), LangGraph lebih cocok. CrewAI fokus ke workflow berbasis tim, LangGraph fokus ke state machine. Kalau kamu cuma butuh satu agent dengan tool calling, OpenAI Assistants API atau Claude Agent SDK lebih simpel.
Troubleshooting
"No module named 'crewai_tools'": Jalanin uv add crewai-tools di virtual environment project kamu.
Output agent pendek atau generic: Cek backstory agent dan expected_output task. Prompt yang vague ngasil output vague. Field expected_output dengan word count spesifik dan struktur adalah yang ngconstrain agent.
Rate limit error: Set max_rpm di agent atau crew. Buat OpenAI gpt-4o, 30 RPM aman buat plan personal.
Hierarchical process nggak delegate: Pastikan manager_llm diset. Tanpa itu, manager nggak punya model buat reason.
Referensi
- CrewAI Documentation: Introduction - overview arsitektur Flows dan Crews
- CrewAI Documentation: Agents - atribut dan konfigurasi agent
- CrewAI Documentation: Tasks - atribut task, sequential vs hierarchical execution