CrewAIチュートリアル: マルチエージェントAIシステムの構築
CrewAIとは?
CrewAIは、複雑なタスクに取り組むために協力するロールプレイ型の自律AIエージェントを編成するためのオープンソースのPythonフレームワークです。各AIエージェントが専門的なスキルと責任を持つチームを構築するようなものと考えてください。
コアコンセプト
1. Agents(エージェント)
エージェントは、特定のスキル、専門知識、責任を持つ専門チームメンバーと考えてください。例えば、Researcherエージェントは情報収集と分析に優れている一方で、Writerエージェントはコンテンツ作成に適しているかもしれません。
2. Tasks(タスク)
タスクはエージェントに与えられる具体的な課題です。各タスクには達成すべき内容、期待される成果、そしてどのエージェントがそれを担当するかが定義されています。
3. Crews(クルー)
クルーは、プロセスを完了するために協力するエージェントとタスクの構造化されたグループです。クルーは複数のエージェント間の連携を調整します。
4. Tools(ツール)
これにより、エージェントはウェブからの情報取得や複雑なデータ分析の実行など、コア能力を超えたタスクを実行できるようになります。
チュートリアル概要
以下を備えたコンテンツ調査および執筆システムを構築します:
- Research Agent: トピックに関する情報を収集
- Writer Agent: 調査に基づいて記事を作成
- Editor Agent: コンテンツをレビューし改善
このチュートリアルでは、単一のLLMをプロンプトする場合を超えるパフォーマンスを発揮する、AIエージェントのチームを設計しプロンプトすることで、マルチAIエージェントシステムの力を実証します。
Step 1: セットアップと環境構成
# Uncomment to install required packages
# !pip install crewai crewai-tools python-dotenv -q# Load environment variables
import os
from dotenv import load_dotenv
# Load API keys from .env file
load_dotenv()
# Required environment variables:
# OPENAI_API_KEY=your_openai_key_here
# SERPER_API_KEY=your_serper_key_here (for web search)
print("Environment variables loaded successfully!")
print(f"OpenAI API Key: {'✓ Set' if os.getenv('OPENAI_API_KEY') else '✗ Missing'}")
print(f"Serper API Key: {'✓ Set' if os.getenv('SERPER_API_KEY') else '✗ Missing'}")Environment variables loaded successfully! OpenAI API Key: ✓ Set Serper API Key: ✓ Set
Step 2: CrewAIコンポーネントをインポートする
from crewai import Agent, Task, Crew, Process
from crewai_tools import SerperDevTool, FileWriterTool
from langchain_openai import ChatOpenAI/Users/devon/.pyenv/versions/3.10.14/lib/python3.10/site-packages/pydantic/fields.py:1093: PydanticDeprecatedSince20: Using extra keyword arguments on `Field` is deprecated and will be removed. Use `json_schema_extra` instead. (Extra keys: 'required'). Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.11/migration/ warn(
Step 3: ツールとLLMの初期化
# Initialize tools
search_tool = SerperDevTool()
file_writer = FileWriterTool()
# Initialize LLM
llm = ChatOpenAI(
model_name="gpt-4o-mini",
temperature=0.1
)
print("Tools and LLM initialized successfully!")Tools and LLM initialized successfully!
Step 4: 専門エージェントの作成
# Research Agent - Expert at gathering information
researcher = Agent(
role='Senior Research Analyst',
goal='Conduct thorough research on given topics and provide comprehensive insights',
backstory="""You are an experienced research analyst with expertise in gathering,
analyzing, and synthesizing information from multiple sources. You have a keen eye
for detail and excel at identifying key trends and insights.""",
tools=[search_tool],
llm=llm,
verbose=False
)
# Writer Agent - Expert at content creation
writer = Agent(
role='Content Writer',
goal='Create engaging, informative articles based on research findings',
backstory="""You are a skilled content writer with years of experience in creating
compelling articles. You excel at transforming complex research into accessible,
engaging content that resonates with readers.""",
tools=[file_writer],
llm=llm,
verbose=False
)
# Editor Agent - Expert at content review and improvement
editor = Agent(
role='Senior Editor',
goal='Review and enhance content for clarity, accuracy, and engagement',
backstory="""You are a meticulous editor with exceptional attention to detail.
You excel at improving content structure, clarity, and overall quality while
maintaining the author's voice and intent.""",
llm=llm,
verbose=False
)
# print("Agents created successfully!")Agents created successfully!
Step 5: 各エージェントのタスクを定義する
def create_tasks(topic):
# Research Task
research_task = Task(
description=f"""Conduct comprehensive research on: {topic}
Your research should include:
- Current trends and developments
- Key statistics and data points
- Expert opinions and insights
- Future implications and predictions
Provide a detailed research summary with sources with 50 words.""",
agent=researcher,
expected_output="A comprehensive research summary with key findings and sources"
)
# Writing Task
writing_task = Task(
description=f"""Based on the research findings, write an engaging article about: {topic} in 50 words
The article should:
- Have a compelling introduction and conclusion
- Include relevant statistics and expert insights
- Be structured with clear headings and subheadings
- Be written for a general audience
""",
agent=writer,
context=[research_task],
expected_output="A well-structured, engaging article saved as a markdown file"
)
# Editing Task
editing_task = Task(
description="""Review the written article and provide:
1. Overall assessment of content quality
2. Suggestions for improvement in:
- Structure and flow
- Clarity and readability
- Factual accuracy
- Engagement and interest
3. A final edited version with improvements
Provide both your review comments and the improved article within 50 words.""",
agent=editor,
context=[writing_task],
expected_output="Editorial review with improvement suggestions and final edited article"
)
return [research_task, writing_task, editing_task]
print("Task creation function defined!")Task creation function defined!
Step 6: Create and Execute the Crew
ステップ6: Crew の作成と実行
# Define the topic for research and writing
topic = "Artificial Intelligence in Sales 2025"
# Create tasks for the topic
tasks = create_tasks(topic)
# Create the crew
content_crew = Crew(
agents=[researcher, writer, editor],
tasks=tasks,
process=Process.sequential, # Tasks executed one after another
verbose=0
)from IPython.display import display, Markdown
# Execute the crew
print("Starting crew execution...\n")
result = content_crew.kickoff()
print("\n" + "="*50)
print("CREW EXECUTION COMPLETED!")
print("="*50)
print("\nFinal Result:")
# Convert CrewOutput to text and display as markdown
if hasattr(result, 'raw') and result.raw:
result_text = result.raw
elif hasattr(result, 'tasks_output') and result.tasks_output:
result_text = "\n\n".join([str(task.output) for task in result.tasks_output])
else:
result_text = str(result)
display(Markdown(result_text))Starting crew execution... ================================================== CREW EXECUTION COMPLETED! ================================================== Final Result: ================================================== CREW EXECUTION COMPLETED! ================================================== Final Result:
Overall Assessment of Content Quality: The article presents a clear overview of AI's impact on sales by 2025 but lacks depth in certain areas and could benefit from improved structure and engagement.
Suggestions for Improvement:
- Structure and Flow: Introduce subheadings for each section to enhance navigation.
- Clarity and Readability: Simplify complex sentences and use bullet points for key trends.
- Factual Accuracy: Ensure all statistics are up-to-date and properly cited.
- Engagement and Interest: Include real-world examples or case studies to illustrate points.
Final Edited Version:
Artificial Intelligence in Sales 2025
Introduction
As we approach 2025, Artificial Intelligence (AI) is poised to revolutionize the sales landscape. With productivity enhancements projected at 15% (Gartner), businesses are preparing for a transformative shift in customer engagement.
Key Trends
- AI-Driven Insights: Understanding customer behavior through AI is essential for effective sales strategies.
- Competitive Edge: Companies utilizing these insights can tailor their approaches to meet evolving consumer needs.
The Need for Skilled Professionals
Despite the benefits, there is a looming shortage of 4.3 million AI specialists, emphasizing the urgent need for skilled professionals in this field.
Conclusion
The integration of AI in sales by 2025 promises significant benefits but requires a workforce equipped to harness its potential. For more insights, visit SuperAGI and PwC.
結論
CrewAI を使用してマルチエージェントシステムを構築することに成功しました!このチュートリアルでは以下をカバーしました:
✅ 環境設定: APIキーと依存関係
✅ エージェント作成: 明確な役割を持つ専門的なAIエージェント
✅ タスク定義: 明確な目標と期待される出力
✅ クルーオーケストレーション: エージェントを連携させて作業を調整
✅ 実行: 完全なワークフローの実行
覚えておいてください: 効果的なAIエージェントを設計するための重要な原則を学び、複雑で多段階のタスクを実行するAIエージェントのチームを組織することが、成功するマルチエージェントシステムの基盤です!