构建你的第一个CrewAI代理

让我们创建一个简单的团队,帮助我们researchreport关于给定主题或主题的latest AI developments

在我们继续之前,请确保你已经安装了crewaicrewai-tools。 如果你还没有安装它们,你可以按照安装指南进行操作。

按照以下步骤开始船员配置! 🚣‍♂️

1

创建你的团队

在终端中运行以下命令以创建一个新的crew项目。 这将创建一个名为latest-ai-development的新目录,其中包含crew的基本结构。

2

修改你的 `agents.yaml` 文件

你也可以根据需要修改代理以适应你的使用场景,或者直接复制粘贴到你的项目中。 任何在你的agents.yamltasks.yaml文件中插入的变量,如{topic},将会被main.py文件中的变量值替换。

agents.yaml
# src/latest_ai_development/config/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 the most relevant
    information and present it in a clear and concise manner.

reporting_analyst:
  role: >
    {topic} Reporting Analyst
  goal: >
    Create detailed reports based on {topic} data analysis and research findings
  backstory: >
    You're a meticulous analyst with a keen eye for detail. You're known for
    your ability to turn complex data into clear and concise reports, making
    it easy for others to understand and act on the information you provide.
3

修改你的 `tasks.yaml` 文件

tasks.yaml
# src/latest_ai_development/config/tasks.yaml
research_task:
  description: >
    Conduct a thorough research about {topic}
    Make sure you find any interesting and relevant information given
    the current year is 2024.
  expected_output: >
    A list with 10 bullet points of the most relevant information about {topic}
  agent: researcher

reporting_task:
  description: >
    Review the context you got and expand each topic into a full section for a report.
    Make sure the report is detailed and contains any and all relevant information.
  expected_output: >
    A fully fledge reports with the mains topics, each with a full section of information.
    Formatted as markdown without '```'
  agent: reporting_analyst
  output_file: report.md
4

修改你的 `crew.py` 文件

crew.py
# src/latest_ai_development/crew.py
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
from crewai_tools import SerperDevTool

@CrewBase
class LatestAiDevelopmentCrew():
  """LatestAiDevelopment crew"""

  @agent
  def researcher(self) -> Agent:
    return Agent(
      config=self.agents_config['researcher'],
      verbose=True,
      tools=[SerperDevTool()]
    )

  @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='output/report.md' # This is the file that will be contain the final report.
    )

  @crew
  def crew(self) -> Crew:
    """Creates the LatestAiDevelopment crew"""
    return Crew(
      agents=self.agents, # Automatically created by the @agent decorator
      tasks=self.tasks, # Automatically created by the @task decorator
      process=Process.sequential,
      verbose=True,
    )
5

[可选] 添加前后机组功能

crew.py
# src/latest_ai_development/crew.py
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task, before_kickoff, after_kickoff
from crewai_tools import SerperDevTool

@CrewBase
class LatestAiDevelopmentCrew():
  """LatestAiDevelopment crew"""

  @before_kickoff
  def before_kickoff_function(self, inputs):
    print(f"Before kickoff function with inputs: {inputs}")
    return inputs # You can return the inputs or modify them as needed

  @after_kickoff
  def after_kickoff_function(self, result):
    print(f"After kickoff function with result: {result}")
    return result # You can return the result or modify it as needed

  # ... remaining code
6

请随意传递自定义输入到您的团队

例如,你可以将topic输入传递给你的团队,以定制研究和报告。

main.py
#!/usr/bin/env python
# src/latest_ai_development/main.py
import sys
from latest_ai_development.crew import LatestAiDevelopmentCrew

def run():
  """
  Run the crew.
  """
  inputs = {
    'topic': 'AI Agents'
  }
  LatestAiDevelopmentCrew().crew().kickoff(inputs=inputs)
7

设置您的环境变量

在运行你的crew之前,请确保你已经在.env文件中将以下键设置为环境变量:

  • 一个 OpenAI API key(或其他LLM API密钥):OPENAI_API_KEY=sk-...
  • 一个 Serper.dev API 密钥:SERPER_API_KEY=YOUR_KEY_HERE
8

锁定并安装依赖项

锁定依赖项并使用CLI命令安装它们,但首先,导航到您的项目目录:

9

运行你的团队

要运行你的团队,请在项目的根目录下执行以下命令:

10

查看您的最终报告

你应该在控制台中看到输出,并且report.md文件应该会在项目的根目录下创建,包含最终报告。

以下是报告应呈现的示例:

关于命名一致性的说明

你在YAML文件中使用的名称(agents.yamltasks.yaml)应与Python代码中的方法名称匹配。 例如,你可以从tasks.yaml文件中引用特定任务的代理。 这种命名一致性使CrewAI能够自动将你的配置与代码链接;否则,你的任务将无法正确识别引用。

示例参考

注意我们在agents.yamlemail_summarizer)文件中使用的代理名称与crew.pyemail_summarizer)文件中的方法名称相同。

agents.yaml
email_summarizer:
    role: >
      Email Summarizer
    goal: >
      Summarize emails into a concise and clear summary
    backstory: >
      You will create a 5 bullet point summary of the report
    llm: mixtal_llm

注意我们在tasks.yamlemail_summarizer_task)文件中为代理使用的名称与crew.pyemail_summarizer_task)文件中的方法名称相同。

tasks.yaml
email_summarizer_task:
    description: >
      Summarize the email into a 5 bullet point summary
    expected_output: >
      A 5 bullet point summary of the email
    agent: email_summarizer
    context:
      - reporting_task
      - research_task

使用注释在crew.py文件中正确引用代理和任务。

注释包括:

  • @agent
  • @task
  • @crew
  • @tool
  • @before_kickoff
  • @after_kickoff
  • @callback
  • @output_json
  • @output_pydantic
  • @cache_handler
crew.py
# ...
@agent
def email_summarizer(self) -> Agent:
    return Agent(
        config=self.agents_config["email_summarizer"],
    )

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

除了顺序流程,您还可以使用分层流程, 它会自动为定义的团队分配一个经理,通过委派和验证结果来正确协调任务的规划和执行。 您可以在这里了解更多关于核心概念的信息。

从最新团队启动重放任务

CrewAI 现在包含一个重放功能,允许您列出上次运行的任务并从特定任务重放。要使用此功能,请运行。

crewai replay <task_id>

替换为您想要重放的任务的ID。

重置船员记忆

如果你需要在再次运行之前重置你的crew的内存,你可以通过调用重置内存功能来实现:

crewai reset-memories --all

这将清除船员们的记忆,允许重新开始。

部署您的项目

部署你的团队的最简单方法是通过CrewAI Enterprise,你可以在几次点击中部署你的团队。

这个页面有帮助吗?