crewai-multi-agent について
CrewAIは、役割分担とタスクプロセスを用いたAIエージェントチームを構築するためのオーケストレーションフレームワークです。自律型のCrewsとイベント駆動型のFlowsを備え、メモリー機能も含みます。
主な機能
- 01役割に基づくエージェントとタスクの定義
- 02逐次型・階層型のタスクプロセス
- 03Crewsとイベント駆動型Flows
- 04短期・長期・エンティティメモリー
- 05組み込みツールとカスタムツール
活用シーン
- 01調査・執筆・分析エージェントのチーム編成
- 02複数段階のタスクを順に実行
- 03イベント駆動フローで条件分岐を処理
- 04協調タスク間でコンテキストを保持
MCP 対応
READMEではTools GuideがMCPを扱うと記載されていますが、具体的なMCP機能やインターフェースは説明されていません。
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ orchestra-research/ ai-research-skills --skill crewai-multi-agentインストール後、Claude Code で/crewai-multi-agentを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
references/flows.mdtools.mdtroubleshooting.md詳細
CrewAI - マルチエージェント オーケストレーション フレームワーク
複雑なタスクを解決するために協調する、自律型 AI エージェントのチームを構築します。
CrewAI を使用するタイミング
CrewAI を使用する場合:
- 専門的な役割を持つマルチエージェント システムを構築するとき
- エージェント同士の自律的な協調が必要なとき
- 役割ベースのタスク委任(リサーチャー、ライター、アナリスト)が必要なとき
- 順次実行または階層的な実行プロセスが必要なとき
- メモリと可観測性を備えた本番ワークフローを構築するとき
- LangChain/LangGraph よりも簡単なセットアップが必要なとき
主な機能:
- スタンドアロン: LangChain への依存関係がなく、軽量です
- 役割ベース: エージェントは役割、目標、バックストーリーを持ちます
- デュアルパラダイム: Crews(自律型)+ Flows(イベント駆動型)
- 50 以上のツール: Web スクレイピング、検索、データベース、AI サービス
- メモリ: 短期メモリ、長期メモリ、エンティティメモリ
- 本番環境対応: トレーシング、エンタープライズ機能
代わりに以下を使用してください:
- LangChain: 汎用の LLM アプリ、RAG パイプライン
- LangGraph: サイクルを含む複雑なステートフル ワークフロー
- AutoGen: Microsoft エコシステム、マルチエージェントの会話
- LlamaIndex: ドキュメントの Q&A、ナレッジ検索
クイックスタート
インストール
# Core framework
pip install crewai
# With 50+ built-in tools
pip install 'crewai[tools]'
CLI でプロジェクトを作成
# Create new crew project
crewai create crew my_project
cd my_project
# Install dependencies
crewai install
# Run the crew
crewai run
シンプルな Crew(コードのみ)
from crewai import Agent, Task, Crew, Process
# 1. Define agents
researcher = Agent(
role="Senior Research Analyst",
goal="Discover cutting-edge developments in AI",
backstory="You are an expert analyst with a keen eye for emerging trends.",
verbose=True
)
writer = Agent(
role="Technical Writer",
goal="Create clear, engaging content about technical topics",
backstory="You excel at explaining complex concepts to general audiences.",
verbose=True
)
# 2. Define tasks
research_task = Task(
description="Research the latest developments in {topic}. Find 5 key trends.",
expected_output="A detailed report with 5 bullet points on key trends.",
agent=researcher
)
write_task = Task(
description="Write a blog post based on the research findings.",
expected_output="A 500-word blog post in markdown format.",
agent=writer,
context=[research_task] # Uses research output
)
# 3. Create and run crew
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, write_task],
process=Process.sequential, # Tasks run in order
verbose=True
)
# 4. Execute
result = crew.kickoff(inputs={"topic": "AI Agents"})
print(result.raw)
基本概念
エージェント - 自律型ワーカー
from crewai import Agent
agent = Agent(
role="Data Scientist", # Job title/role
goal="Analyze data to find insights", # What they aim to achieve
backstory="PhD in statistics...", # Background context
llm="gpt-4o", # LLM to use
tools=[], # Tools available
memory=True, # Enable memory
verbose=True, # Show reasoning
allow_delegation=True, # Can delegate to others
max_iter=15, # Max reasoning iterations
max_rpm=10 # Rate limit
)
タスク - 作業単位
from crewai import Task
task = Task(
description="Analyze the sales data for Q4 2024. {context}",
expected_output="A summary report with key metrics and trends.",
agent=analyst, # Assigned agent
context=[previous_task], # Input from other tasks
output_file="report.md", # Save to file
async_execution=False, # Run synchronously
human_input=False # No human approval needed
)
Crews - エージェントのチーム
from crewai import Crew, Process
crew = Crew(
agents=[researcher, writer, editor], # Team members
tasks=[research, write, edit], # Tasks to complete
process=Process.sequential, # Or Process.hierarchical
verbose=True,
memory=True, # Enable crew memory
cache=True, # Cache tool results
max_rpm=10, # Rate limit
share_crew=False # Opt-in telemetry
)
# Execute with inputs
result = crew.kickoff(inputs={"topic": "AI trends"})
# Access results
print(result.raw) # Final output
print(result.tasks_output) # All task outputs
print(result.token_usage) # Token consumption
プロセスの種類
順次実行(デフォルト)
タスクは順番に実行され、各エージェントは次のタスクに進む前に自身のタスクを完了します:
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, write_task],
process=Process.sequential # Task 1 → Task 2 → Task 3
)
階層型
委任と調整を行うマネージャー エージェントを自動的に作成します:
crew = Crew(
agents=[researcher, writer, analyst],
tasks=[research_task, write_task, analyze_task],
process=Process.hierarchical, # Manager delegates tasks
manager_llm="gpt-4o" # LLM for manager
)
ツールの使用
組み込みツール(50 以上)
pip install 'crewai[tools]'
from crewai_tools import (
SerperDevTool, # Web search
ScrapeWebsiteTool, # Web scraping
FileReadTool, # Read files
PDFSearchTool, # Search PDFs
WebsiteSearchTool, # Search websites
CodeDocsSearchTool, # Search code docs
YoutubeVideoSearchTool, # Search YouTube
)
# Assign tools to agent
researcher = Agent(
role="Researcher",
goal="Find accurate information",
backstory="Expert at finding data online.",
tools=[SerperDevTool(), ScrapeWebsiteTool()]
)
カスタムツール
from crewai.tools import BaseTool
from pydantic import Field
class CalculatorTool(BaseTool):
name: str = "Calculator"
description: str = "Performs mathematical calculations. Input: expression"
def _run(self, expression: str) -> str:
try:
result = eval(expression)
return f"Result: {result}"
except Exception as e:
return f"Error: {str(e)}"
# Use custom tool
agent = Agent(
role="Analyst",
goal="Perform calculations",
tools=[CalculatorTool()]
)
YAML 設定(推奨)
プロジェクト構造
my_project/
├── src/my_project/
│ ├── config/
│ │ ├── agents.yaml # Agent definitions
│ │ └── tasks.yaml # Task definitions
│ ├── crew.py # Crew assembly
│ └── main.py # Entry point
└── pyproject.toml
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 relevant information and present it clearly.
reporting_analyst:
role: "Reporting Analyst"
goal: "Create detailed reports based on research data"
backstory: >
You're a meticulous analyst who transforms raw data into
actionable insights through well-structured reports.
tasks.yaml
research_task:
description: >
Conduct thorough research about {topic}.
Find the most relevant information for {year}.
expected_output: >
A list with 10 bullet points of the most relevant
information about {topic}.
agent: researcher
reporting_task:
description: >
Review the research and create a comprehensive report.
Focus on key findings and recommendations.
expected_output: >
A detailed report in markdown format with executive
summary, findings, and recommendations.
agent: reporting_analyst
output_file: report.md
crew.py
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
from crewai_tools import SerperDevTool
@CrewBase
class MyProjectCrew:
"""My Project crew"""
@agent
def researcher(self) -> Agent:
return Agent(
config=self.agents_config['researcher'],
tools=[SerperDevTool()],
verbose=True
)
@agent
def reporting_analyst(self) -> Agent:
return Agent(
config=self.agents_config['reporting_analyst'],
verbose=True
)
@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'
)
@crew
def crew(self) -> Crew:
return Crew(
agents=self.agents,
tasks=self.tasks,
process=Process.sequential,
verbose=True
)
main.py
from my_project.crew import MyProjectCrew
def run():
inputs = {
'topic': 'AI Agents',
'year': 2025
}
MyProjectCrew().crew().kickoff(inputs=inputs)
if __name__ == "__main__":
run()
Flows - イベント駆動型オーケストレーション
条件分岐を伴う複雑なワークフローには、Flows を使用します:
from crewai.flow.flow import Flow, listen, start, router
from pydantic import BaseModel
class MyState(BaseModel):
confidence: float = 0.0
class MyFlow(Flow[MyState]):
@start()
def gather_data(self):
return {"data": "collected"}
@listen(gather_data)
def analyze(self, data):
self.state.confidence = 0.85
return analysis_crew.kickoff(inputs=data)
@router(analyze)
def decide(self):
return "high" if self.state.confidence > 0.8 else "low"
@listen("high")
def generate_report(self):
return report_crew.kickoff()
# Run flow
flow = MyFlow()
result = flow.kickoff()
完全なドキュメントは Flows ガイド を参照してください。
メモリシステム
# Enable all memory types
crew = Crew(
agents=[researcher],
tasks=[research_task],
memory=True, # Enable memory
embedder={ # Custom embeddings
"provider": "openai",
"config": {"model": "text-embedding-3-small"}
}
)
メモリの種類: 短期(ChromaDB)、長期(SQLite)、エンティティ(ChromaDB)
LLM プロバイダー
from crewai import LLM
llm = LLM(model="gpt-4o") # OpenAI (default)
llm = LLM(model="claude-sonnet-4-5-20250929") # Anthropic
llm = LLM(model="ollama/llama3.1", base_url="http://localhost:11434") # Local
llm = LLM(model="azure/gpt-4o", base_url="https://...") # Azure
agent = Agent(role="Analyst", goal="Analyze data", llm=llm)
CrewAI と代替ツールの比較
| 機能 | CrewAI | LangChain | LangGraph |
|---|---|---|---|
| 最適な用途 | マルチエージェント チーム | 汎用 LLM アプリ | ステートフル ワークフロー |
| 学習コスト | 低 | 中 | 高 |
| エージェントのパラダイム | 役割ベース | ツールベース | グラフベース |
| メモリ | 組み込み | プラグインベース | カスタム |
ベストプラクティス
- 明確な役割 - 各エージェントは明確な専門分野を持つべきです
- YAML 設定 - 大規模なプロジェクトでの整理に適しています
- メモリを有効化 - タスク間のコンテキストを改善します
- max_iter を設定 - 無限ループを防ぎます(デフォルトは 15)
- ツールを制限 - エージェントあたり最大 3〜5 個のツール
- レート制限 - max_rpm を設定して API の上限を回避します
よくある問題
エージェントがループから抜け出せない:
agent = Agent(
role="...",
max_iter=10, # Limit iterations
max_rpm=5 # Rate limit
)
タスクがコンテキストを使用しない:
task2 = Task(
description="...",
context=[task1], # Explicitly pass context
agent=writer
)
メモリのエラー:
# Use environment variable for storage
import os
os.environ["CREWAI_STORAGE_DIR"] = "./my_storage"
参考資料
- Flows ガイド - イベント駆動型ワークフロー、状態管理
- ツールガイド - 組み込みツール、カスタムツール、MCP
- トラブルシューティング - よくある問題、デバッグ
リソース
- GitHub: https://github.com/crewAIInc/crewAI (25k+ stars)
- ドキュメント: https://docs.crewai.com
- ツール: https://github.com/crewAIInc/crewAI-tools
- サンプル: https://github.com/crewAIInc/crewAI-examples
- バージョン: 1.2.0+
- ライセンス: MIT
コメント
Markdown 対応