目錄
- 1. CrewAI簡介
- 1.1 CrewAI Crews
- 1.2 CrewAI Flows
- 1.3 Crews和Flows的使用情景
- 2. CrewAI安裝
- 2.1 安裝uv
- 2.2 安裝CrewAI CLI
- 3. 官網QuickStart樣例
- 3.1 創建CrewAI Crews項目
- 3.2 項目結構
- 3.3 .env
- 3.4 智能體角色及其任務
- 3.4.1 agents.yaml
- 3.4.2 tasks.yaml
- 3.5 crew.py
- 3.6 main.py
- 3.7 本地運行
- 參考
1. CrewAI簡介
??CrewAI是一個精簡、快如閃電的Python框架,完全獨立于LangChain或其他Agent框架。它為開發者提供了高層次簡潔性與精準低層次控制的雙重優勢,是創建適用于任何場景的自主AI代理的理想框架,存在如下的兩種模式:
??1. CrewAI Crews:優化自主性與協作智能,使您能夠創建具備特定角色、工具、目標的智能體團隊。
??2. CrewAI Flows:支持細粒度的事件驅動控制,通過單一LLM調用實現精準任務編排,并原生支持智能體團隊協作。
1.1 CrewAI Crews
??下圖源自CrewAI。
組成 | 描述 | 作用 |
---|---|---|
Crew | 最頂層的組織 | 1. 管理智能體團隊 2. 監督工作流 3. 保證協作 4. 輸出結果 |
AI Agents | 專業的團隊成員 | 1. 有特定的角色 2. 使用指定的工具 3. 可以委派任務 4. 自主決策 |
Process | 工作流管理系統 | 1. 定義協作模式 2. 控制任務 3. 管理交互 4. 保證高效執行 |
Tasks | 個人任務 | 1. 有明確的目標 2. 使用特定的工具 3. 輸入到更大的Process 4. 產生可行的結果 |
1.2 CrewAI Flows
??下圖源自CrewAI。
組成 | 描述 | 作用 |
---|---|---|
Flow | 結構化工作流安排 | 1. 管理執行路徑 2. 處理state 3. 控制任務順序 4. 保證執行可靠 |
Events | 工作流行動的觸發器 | 1. 啟動特定Processes 2. 啟用動態響應 3. 支持條件分支 4. 允許實時適應 |
States | 工作流執行上下文 | 1. 維持執行數據 2. 啟用持久性 3. 支持可恢復性 4. 保證執行完整性 |
Crew Support | 增強工作流自動化 | 1. 在需要時注入Crew 2. 補充結構化工作流 3. 平衡自動化與智能 4. 支持自適應決策 |
1.3 Crews和Flows的使用情景
情景 | 推薦方法 | 原因 |
---|---|---|
開放性研究 | Crews | 任務需要創造性思考、探索和適應 |
生成內容 | Crews | 文章、報告和營銷材料需要聯合協作 |
決策工作流 | Flows | 決策路徑具備可預測性、審計性和精細控制 |
API編排 | Flows | 需要按照特定順序對多個外部服務進行可靠的集成 |
混合應用 | Crews、Flows | 使用Flows編排整個過程,同時使用Crews處理復雜子任務 |
??當你需要自主解決問題、合作創新或進行探索性任務時,應該選擇Crews;當你需要確定性的結果、審計能力或對執行的精準控制,應該選擇Flows;當你的應用需要結構化過程和一些自主智能時,應該聯合Crews和Flows。
2. CrewAI安裝
2.1 安裝uv
??uv是用Rust編寫的Python包管理器,目前使用Python的新項目基本上都使用它來對項目中的依賴進行管理。Windows上安裝的命令:
??powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
2.2 安裝CrewAI CLI
??安裝CrewAI CLI的命令:
??uv tool install crewai
??配置CrewAI的路徑:
??uv tool update-shell
??驗證CrewAI安裝:
??uv tool list
??更新CrewAI:
??uv tool install crewai --upgrade
3. 官網QuickStart樣例
3.1 創建CrewAI Crews項目
??創建CrewAI Crews項目:
??crewai create crew <your-project-name>
3.2 項目結構
??項目結構圖如下。
路徑 | 作用 |
---|---|
<your-project-name>/.venv | 項目下的Python環境 |
<your-project-name>/knowledge | 本地知識庫目錄 |
<your-project-name>/src/<your-project-name>/config/agents.yaml | 定義智能體及其角色 |
<your-project-name>/src/<your-project-name>/config/tasks.yaml | 設置智能體任務和工作流 |
<your-project-name>/src/<your-project-name>/tools | 自定義智能體工具的目錄 |
<your-project-name>/src/crew.py | 協調、編排Crews |
<your-project-name>/src/main.py | 項目入口、執行流 |
<your-project-name>/tests | 測試目錄 |
<your-project-name>/.env | 存放大模型API Keys和環境變量 |
<your-project-name>/.gitignore | 配置git忽略的文件或文件夾 |
<your-project-name>/pyproject.toml | Python項目配置 |
<your-project-name>/README.md | CrewAI官方給出的項目運行指導 |
<your-project-name>/uv.lock | uv鎖定的Python依賴 |
3.3 .env
??CrewAI支持調用和OpenAI的API規范一致的大模型,這里我選擇了deepseek-chat。
MODEL=openai/deepseek-chat
OPENAI_API_KEY="your-api-key"
OPENAI_API_BASE="https://api.deepseek.com/v1"
3.4 智能體角色及其任務
3.4.1 agents.yaml
??樣例中定義了兩個智能體research和reporting_analyst,分別給它們定義了role、goal和backstory。此外,在role、goal和backstory中可以通過{變量名}的方式插入用戶輸入的內容。
researcher:role: >{topic}領域的高級數據研究員goal: >發掘{topic}領域的前沿發展backstory: >你是一位經驗豐富的研究員,擅長發掘{topic}領域的最新進展。你能夠找到最相關的信息并以清晰簡潔的方式呈現。reporting_analyst:role: >{topic}領域的報告分析師goal: >基于{topic}領域的數據分析和研究發現,創建詳細的報告backstory: >你是一位細致入微的分析師,對細節有著敏銳的洞察力。你能夠將復雜的數據轉化為清晰簡潔的報告,使他人能夠輕松理解并基于你提供的信息采取行動。
3.4.2 tasks.yaml
??tasks.yaml中給researcher和reporting_analyst分別分配了任務research_task和reporting_task,在每個任務中給出了任務描述description、任務輸出expected_output和該任務所屬的智能體agent。同樣,在description、expected_output中可以通過{變量名}的方式插入用戶的內容。
research_task:description: >對{topic}領域進行深入研究,確保在當前年份{current_year}下找到所有有趣且相關的信息。expected_output: >列出關于{topic}的10個要點,涵蓋最相關的信息。agent: researcherreporting_task:description: >審查獲取的內容,并將每個主題擴展為完整的報告章節。確保報告詳盡,包含所有相關信息。expected_output: >一份完整的報告,每個主要主題均包含詳細的信息章節,以Markdown格式呈現(不包含代碼塊標記)。agent: reporting_analyst
3.5 crew.py
?&emsp以下代碼皆是創建項目時自動生成的,從下面的代碼中可以看出FirstAgent類主要完成3個任務:1. 創建智能體Agent。2. 創建智能體的任務Task。3. 創建最頂層組織Crew。
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task# If you want to run a snippet of code before or after the crew starts,
# you can use the @before_kickoff and @after_kickoff decorators
# https://docs.crewai.com/concepts/crews#example-crew-class-with-decorators@CrewBase
class FirstAgent():"""FirstAgent crew"""# Learn more about YAML configuration files here:# Agents: https://docs.crewai.com/concepts/agents#yaml-configuration-recommended# Tasks: https://docs.crewai.com/concepts/tasks#yaml-configuration-recommendedagents_config = 'config/agents.yaml'tasks_config = 'config/tasks.yaml'# If you would like to add tools to your agents, you can learn more about it here:# https://docs.crewai.com/concepts/agents#agent-tools@agentdef researcher(self) -> Agent:return Agent(config=self.agents_config['researcher'],verbose=True)@agentdef reporting_analyst(self) -> Agent:return Agent(config=self.agents_config['reporting_analyst'],verbose=True)# To learn more about structured task outputs,# task dependencies, and task callbacks, check out the documentation:# https://docs.crewai.com/concepts/tasks#overview-of-a-task@taskdef research_task(self) -> Task:return Task(config=self.tasks_config['research_task'],)@taskdef reporting_task(self) -> Task:return Task(config=self.tasks_config['reporting_task'],output_file='report.md')@crewdef crew(self) -> Crew:"""Creates the FirstAgent crew"""# To learn how to add knowledge sources to your crew, check out the documentation:# https://docs.crewai.com/concepts/knowledge#what-is-knowledgereturn Crew(agents=self.agents, # Automatically created by the @agent decoratortasks=self.tasks, # Automatically created by the @task decoratorprocess=Process.sequential,verbose=True,# process=Process.hierarchical, # In case you wanna use that instead https://docs.crewai.com/how-to/Hierarchical/)
3.6 main.py
??main.py文件主要功能是讓你在本地運行Crew,以達到測試的目的。以下代碼也是在創建項目時自動生成的。
import sys
import warningsfrom datetime import datetimefrom first_agent.crew import FirstAgentwarnings.filterwarnings("ignore", category=SyntaxWarning, module="pysbd")# This main file is intended to be a way for you to run your
# crew locally, so refrain from adding unnecessary logic into this file.
# Replace with inputs you want to test with, it will automatically
# interpolate any tasks and agents informationdef run():"""Run the crew."""inputs = {'topic': '大語言模型','current_year': str(datetime.now().year)}try:FirstAgent().crew().kickoff(inputs=inputs)except Exception as e:raise Exception(f"An error occurred while running the crew: {e}")def train():"""Train the crew for a given number of iterations."""inputs = {"topic": "大語言模型"}try:FirstAgent().crew().train(n_iterations=int(sys.argv[1]), filename=sys.argv[2], inputs=inputs)except Exception as e:raise Exception(f"An error occurred while training the crew: {e}")def replay():"""Replay the crew execution from a specific task."""try:FirstAgent().crew().replay(task_id=sys.argv[1])except Exception as e:raise Exception(f"An error occurred while replaying the crew: {e}")def test():"""Test the crew execution and returns the results."""inputs = {"topic": "大語言模型","current_year": str(datetime.now().year)}try:FirstAgent().crew().test(n_iterations=int(sys.argv[1]), openai_model_name=sys.argv[2], inputs=inputs)except Exception as e:raise Exception(f"An error occurred while testing the crew: {e}")
3.7 本地運行
??在項目路徑下先安裝依賴,然后運行:
crewai install
crewai run
??從上面的Agents.yaml和Tasks.yaml中可以看出,該樣例的目的是產出一份指定topic、指定年份year的報告,報告最終輸出為Markdown文件。
??生成該報告的過程如下:
??1. research Agent查找關于指定主題topic、指定年份year的內容,并將其總結成10個要點。
??2. research Agent完成任務后,將得到10個要點交給reporting_analyst Agent。reporting_analyst審查獲取的10個要點,并將其擴寫成一份指定主題topic、指定年份year的報告,并以Markdown文件格式輸出。
參考
https://docs.crewai.com/introduction
https://docs.crewai.com/installation
https://docs.crewai.com/quickstart