跳转到内容

在 crew.py 中使用注解

本指南解释了如何使用注解在经典 crew.py 文件中正确引用智能体任务以及其他组件。

CrewAI 框架中的注解用于装饰类和方法,为 crew 的各类组件提供元数据和功能。在经典 Python/YAML 项目中,这些注解有助于组织加载 config/agents.yamlconfig/tasks.yaml 并返回 Crew 对象的代码。

CrewAI 框架提供以下注解:

  • @CrewBase:用于装饰主 crew 类。
  • @agent:装饰定义并返回 Agent 对象的方法。
  • @task:装饰定义并返回 Task 对象的方法。
  • @crew:装饰创建并返回 Crew 对象的方法。
  • @llm:装饰初始化并返回 Language Model 对象的方法。
  • @tool:装饰初始化并返回 Tool 对象的方法。
  • @callback:用于定义回调方法。
  • @output_json:用于输出 JSON 数据的方法。
  • @output_pydantic:用于输出 Pydantic 模型的方法。
  • @cache_handler:用于定义缓存处理方法。

下面通过示例说明如何使用这些注解:

@CrewBase
class LinkedinProfileCrew():
"""LinkedinProfile crew"""
agents_config = 'config/agents.yaml'
tasks_config = 'config/tasks.yaml'

@CrewBase 注解用于装饰主 crew 类。这个类通常包含创建智能体、任务以及 crew 本身的配置和方法。

@tool
def myLinkedInProfileTool(self):
return LinkedInProfileTool()

@tool 注解用于装饰返回工具对象的方法。这些工具可供智能体执行特定任务。

@llm
def groq_llm(self):
api_key = os.getenv('api_key')
return ChatGroq(api_key=api_key, temperature=0, model_name="mixtral-8x7b-32768")

@llm 注解用于装饰初始化并返回 Language Model 对象的方法。这些 LLM 会被智能体用于自然语言处理任务。

@agent
def researcher(self) -> Agent:
return Agent(
config=self.agents_config['researcher']
)

@agent 注解用于装饰定义并返回 Agent 对象的方法。

@task
def research_task(self) -> Task:
return Task(
config=self.tasks_config['research_linkedin_task'],
agent=self.researcher()
)

@task 注解用于装饰定义并返回 Task 对象的方法。这些方法指定任务配置以及负责该任务的智能体。

@crew
def crew(self) -> Crew:
"""Creates the LinkedinProfile crew"""
return Crew(
agents=self.agents,
tasks=self.tasks,
process=Process.sequential,
verbose=True
)

@crew 注解用于装饰创建并返回 Crew 对象的方法。这个方法把所有组件(智能体和任务)组装成一个可运行的 crew。

在经典项目中,智能体配置通常保存在 YAML 文件里。下面是 agents.yaml 为 researcher 智能体可能具有的样子:

researcher:
role: >
LinkedIn Profile Senior Data Researcher
goal: >
Uncover detailed LinkedIn profiles based on provided name {name} and domain {domain}
Generate a Dall-E image based on domain {domain}
backstory: >
You're a seasoned researcher with a knack for uncovering the most relevant LinkedIn profiles.
Known for your ability to navigate LinkedIn efficiently, you excel at gathering and presenting
professional information clearly and concisely.
allow_delegation: False
verbose: True
llm: groq_llm
tools:
- myLinkedInProfileTool
- mySerperDevTool
- myDallETool

这个 YAML 配置对应于 LinkedinProfileCrew 类中定义的 researcher 智能体。配置指定了智能体的角色、目标、背景,以及它使用的 LLM 和工具等属性。

注意 YAML 文件中的 llmtools 如何对应到 Python 类中带有 @llm@tool 装饰的方法。

  • 命名一致性:为方法使用清晰且一致的命名约定。例如,智能体方法可以按角色命名(如 researcher、reporting_analyst)。
  • 环境变量:将 API key 这类敏感信息放在环境变量中。
  • 灵活性:通过允许轻松添加或删除智能体和任务,让 crew 保持灵活。
  • YAML 与代码对应:在经典项目中,确保 YAML 文件中的名称和结构与 Python 代码中带注解的方法正确对应。

遵循这些指南并正确使用注解,你就可以整洁地维护经典 Python/YAML crew。对于新建 crew,请优先使用 Crews 中介绍的 JSON-first 结构。