智能体概述

在 CrewAI 框架中,一个 Agent 是一个自主单元,能够

  • 执行特定任务
  • 根据其角色和目标做出决策
  • 使用工具实现目标
  • 与其他智能体沟通和协作
  • 维护交互记忆
  • 在允许时委托任务

可以将智能体视为具有特定技能、专长和职责的专业团队成员。例如,一个 Researcher 智能体可能擅长收集和分析信息,而一个 Writer 智能体可能更擅长创作内容。

CrewAI Enterprise 包含一个可视化智能体构建器,无需编写代码即可简化智能体的创建和配置。可视化设计您的智能体并实时测试它们。

可视化智能体构建器支持

  • 通过基于表单的界面直观配置智能体
  • 实时测试和验证
  • 带有预配置智能体类型的模板库
  • 轻松自定义智能体属性和行为

智能体属性

属性参数类型描述
角色rolestr定义智能体在团队中的功能和专长。
目标goalstr指导智能体决策的个体目标。
背景故事backstorystr为智能体提供背景和个性,丰富交互。
LLM (可选)llmUnion[str, LLM, Any]驱动智能体的语言模型。默认为 OPENAI_MODEL_NAME 中指定的模型或“gpt-4”。
工具 (可选)toolsList[BaseTool]智能体可用的能力或功能。默认为空列表。
函数调用 LLM (可选)function_calling_llmOptional[Any]用于工具调用的语言模型,如果指定,将覆盖团队的 LLM。
最大迭代次数 (可选)max_iterint智能体必须提供其最佳答案之前的最大迭代次数。默认为 20。
最大 RPM (可选)max_rpmOptional[int]每分钟最大请求数,以避免速率限制。
最大执行时间 (可选)max_execution_timeOptional[int]任务执行的最大时间(秒)。
记忆 (可选)memorybool智能体是否应维护交互记忆。默认为 True。
详细模式 (可选)verbosebool启用详细的执行日志进行调试。默认为 False。
允许委托 (可选)allow_delegationbool允许智能体将任务委托给其他智能体。默认为 False。
步骤回调 (可选)step_callbackOptional[Any]在每个智能体步骤后调用的函数,覆盖团队回调。
缓存 (可选)cachebool为工具使用启用缓存。默认为 True。
系统模板 (可选)system_templateOptional[str]智能体的自定义系统提示模板。
提示模板 (可选)prompt_templateOptional[str]智能体的自定义提示模板。
响应模板 (可选)response_templateOptional[str]智能体的自定义响应模板。
允许代码执行 (可选)allow_code_executionOptional[bool]为智能体启用代码执行。默认为 False。
最大重试次数 (可选)max_retry_limitint发生错误时最大重试次数。默认为 2。
尊重上下文窗口 (可选)respect_context_windowbool通过摘要将消息保持在上下文窗口大小内。默认为 True。
代码执行模式 (可选)code_execution_modeLiteral["safe", "unsafe"]代码执行模式:‘safe’(使用 Docker)或 ‘unsafe’(直接执行)。默认为 ‘safe’。
嵌入器 (可选)embedderOptional[Dict[str, Any]]智能体使用的嵌入器的配置。
知识来源 (可选)knowledge_sourcesOptional[List[BaseKnowledgeSource]]智能体可用的知识来源。
使用系统提示 (可选)use_system_promptOptional[bool]是否使用系统提示(用于 o1 模型支持)。默认为 True。

创建智能体

在 CrewAI 中创建智能体有两种方法:使用 YAML 配置(推荐)直接在代码中定义它们。

使用 YAML 配置提供了一种更清晰、更易于维护的方式来定义智能体。强烈建议在 CrewAI 项目中使用此方法。

按照安装部分所述创建 CrewAI 项目后,导航到 src/latest_ai_development/config/agents.yaml 文件并修改模板以匹配您的需求。

YAML 文件中的变量(如 {topic})在运行团队时将替换为您的输入值

代码
crew.kickoff(inputs={'topic': 'AI Agents'})

以下是使用 YAML 配置智能体的示例

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.

要在代码中使用此 YAML 配置,请创建一个继承自 CrewBase 的团队类

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

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

  agents_config = "config/agents.yaml"

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

  @agent
  def reporting_analyst(self) -> Agent:
    return Agent(
      config=self.agents_config['reporting_analyst'], # type: ignore[index]
      verbose=True
    )

您在 YAML 文件 (agents.yaml) 中使用的名称应与 Python 代码中的方法名称匹配。

直接代码定义

您可以通过实例化 Agent 类直接在代码中创建智能体。以下是显示所有可用参数的综合示例

代码
from crewai import Agent
from crewai_tools import SerperDevTool

# Create an agent with all available parameters
agent = Agent(
    role="Senior Data Scientist",
    goal="Analyze and interpret complex datasets to provide actionable insights",
    backstory="With over 10 years of experience in data science and machine learning, "
              "you excel at finding patterns in complex datasets.",
    llm="gpt-4",  # Default: OPENAI_MODEL_NAME or "gpt-4"
    function_calling_llm=None,  # Optional: Separate LLM for tool calling
    memory=True,  # Default: True
    verbose=False,  # Default: False
    allow_delegation=False,  # Default: False
    max_iter=20,  # Default: 20 iterations
    max_rpm=None,  # Optional: Rate limit for API calls
    max_execution_time=None,  # Optional: Maximum execution time in seconds
    max_retry_limit=2,  # Default: 2 retries on error
    allow_code_execution=False,  # Default: False
    code_execution_mode="safe",  # Default: "safe" (options: "safe", "unsafe")
    respect_context_window=True,  # Default: True
    use_system_prompt=True,  # Default: True
    tools=[SerperDevTool()],  # Optional: List of tools
    knowledge_sources=None,  # Optional: List of knowledge sources
    embedder=None,  # Optional: Custom embedder configuration
    system_template=None,  # Optional: Custom system prompt template
    prompt_template=None,  # Optional: Custom prompt template
    response_template=None,  # Optional: Custom response template
    step_callback=None,  # Optional: Callback function for monitoring
)

让我们分解一些常见用例的关键参数组合

基础研究智能体

代码
research_agent = Agent(
    role="Research Analyst",
    goal="Find and summarize information about specific topics",
    backstory="You are an experienced researcher with attention to detail",
    tools=[SerperDevTool()],
    verbose=True  # Enable logging for debugging
)

代码开发智能体

代码
dev_agent = Agent(
    role="Senior Python Developer",
    goal="Write and debug Python code",
    backstory="Expert Python developer with 10 years of experience",
    allow_code_execution=True,
    code_execution_mode="safe",  # Uses Docker for safety
    max_execution_time=300,  # 5-minute timeout
    max_retry_limit=3  # More retries for complex code tasks
)

长时间运行分析智能体

代码
analysis_agent = Agent(
    role="Data Analyst",
    goal="Perform deep analysis of large datasets",
    backstory="Specialized in big data analysis and pattern recognition",
    memory=True,
    respect_context_window=True,
    max_rpm=10,  # Limit API calls
    function_calling_llm="gpt-4o-mini"  # Cheaper model for tool calls
)

自定义模板智能体

代码
custom_agent = Agent(
    role="Customer Service Representative",
    goal="Assist customers with their inquiries",
    backstory="Experienced in customer support with a focus on satisfaction",
    system_template="""<|start_header_id|>system<|end_header_id|>
                        {{ .System }}<|eot_id|>""",
    prompt_template="""<|start_header_id|>user<|end_header_id|>
                        {{ .Prompt }}<|eot_id|>""",
    response_template="""<|start_header_id|>assistant<|end_header_id|>
                        {{ .Response }}<|eot_id|>""",
)

参数详情

关键参数

  • rolegoalbackstory 是必需的,并塑造智能体的行为
  • llm 决定使用的语言模型(默认:OpenAI 的 GPT-4)

记忆与上下文

  • memory:启用以维护对话历史记录
  • respect_context_window:防止 token 限制问题
  • knowledge_sources:添加特定领域的知识库

执行控制

  • max_iter:提供最佳答案前的最大尝试次数
  • max_execution_time:超时时间(秒)
  • max_rpm:API 调用的速率限制
  • max_retry_limit:错误时的重试次数

代码执行

  • allow_code_execution:必须为 True 才能运行代码
  • code_execution_mode:
    • "safe":使用 Docker(推荐用于生产环境)
    • "unsafe":直接执行(仅在受信任的环境中使用)

模板

  • system_template:定义智能体的核心行为
  • prompt_template:构建输入格式
  • response_template:格式化智能体响应

使用自定义模板时,请确保定义了 system_templateprompt_templateresponse_template 是可选的,但推荐用于一致的输出格式。

使用自定义模板时,您可以在模板中使用变量,如 {role}{goal}{backstory}。这些变量将在执行期间自动填充。

智能体工具

智能体可以配备各种工具来增强其能力。CrewAI 支持来自以下来源的工具:

以下是如何为智能体添加工具

代码
from crewai import Agent
from crewai_tools import SerperDevTool, WikipediaTools

# Create tools
search_tool = SerperDevTool()
wiki_tool = WikipediaTools()

# Add tools to agent
researcher = Agent(
    role="AI Technology Researcher",
    goal="Research the latest AI developments",
    tools=[search_tool, wiki_tool],
    verbose=True
)

智能体记忆与上下文

智能体可以维护其交互记忆,并使用来自先前任务的上下文。这对于需要在多个任务中保留信息的复杂工作流尤其有用。

代码
from crewai import Agent

analyst = Agent(
    role="Data Analyst",
    goal="Analyze and remember complex data patterns",
    memory=True,  # Enable memory
    verbose=True
)

启用 memory 后,智能体将在多次交互中保持上下文,提高其处理复杂、多步骤任务的能力。

重要考量和最佳实践

安全性与代码执行

  • 使用 allow_code_execution 时,请谨慎处理用户输入并始终验证它
  • 在生产环境中使用 code_execution_mode: "safe" (Docker)
  • 考虑设置适当的 max_execution_time 限制以防止无限循环

性能优化

  • 使用 respect_context_window: true 防止 token 限制问题
  • 设置适当的 max_rpm 以避免速率限制
  • 启用 cache: true 以提高重复任务的性能
  • 根据任务复杂性调整 max_itermax_retry_limit

记忆与上下文管理

  • 对于需要历史上下文的任务,使用 memory: true
  • 利用 knowledge_sources 获取领域特定信息
  • 使用自定义嵌入模型时配置 embedder_config
  • 使用自定义模板(system_templateprompt_templateresponse_template)对智能体行为进行精细控制

智能体协作

  • 当智能体需要协作时,启用 allow_delegation: true
  • 使用 step_callback 监控和记录智能体交互
  • 考虑为不同目的使用不同的 LLM
    • 主要的 llm 用于复杂推理
    • function_calling_llm 用于高效的工具使用

模型兼容性

  • 对于不支持系统消息的旧模型,设置 use_system_prompt: false
  • 确保您选择的 llm 支持您需要的功能(如函数调用)

常见问题排除

  1. 速率限制:如果您遇到了 API 速率限制

    • 实施适当的 max_rpm
    • 对重复操作使用缓存
    • 考虑批量处理请求
  2. 上下文窗口错误:如果您超出了上下文限制

    • 启用 respect_context_window
    • 使用更高效的提示
    • 定期清除智能体记忆
  3. 代码执行问题:如果代码执行失败

    • 验证是否安装了 Docker 以使用安全模式
    • 检查执行权限
    • 检查代码沙箱设置
  4. 记忆问题:如果智能体响应不一致

    • 验证是否启用了记忆
    • 检查知识来源配置
    • 检查对话历史管理

请记住,智能体根据其特定用例进行配置时效果最佳。花时间了解您的需求并相应地调整这些参数。