代理概述

在CrewAI框架中,Agent是一个可以执行以下操作的自主单元:

  • 执行特定任务
  • 根据其角色和目标做出决策
  • 使用工具来实现目标
  • 与其他代理进行沟通和协作
  • 保持交互的记忆
  • 在允许的情况下委派任务

将代理视为具有特定技能、专业知识和职责的专门团队成员。例如,Researcher代理可能擅长收集和分析信息,而Writer代理可能更擅长创建内容。

代理属性

属性参数类型描述
角色rolestr定义代理在团队中的功能和专长。
目标goalstr指导代理决策的个体目标。
背景故事backstorystr为代理提供背景和个性,丰富互动。
LLM (可选)llmUnion[str, LLM, Any]驱动代理的语言模型。默认为OPENAI_MODEL_NAME中指定的模型或“gpt-4”。
工具 (可选)toolsList[BaseTool]代理可用的能力或功能。默认为空列表。
函数调用LLM (可选)function_calling_llmOptional[Any]用于工具调用的语言模型,如果指定则覆盖crew的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'。
嵌入器配置 (可选)embedder_configOptional[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文件并修改模板以符合您的要求。

在运行crew时,您的YAML文件中的变量(如{topic})将被输入值替换:

Code
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的crew类:

Code
# 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'],
      verbose=True,
      tools=[SerperDevTool()]
    )

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

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

直接代码定义

你可以通过实例化Agent类直接在代码中创建代理。以下是一个展示所有可用参数的完整示例:

Code
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_config=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
)

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

基础研究代理

Code
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
)

代码开发代理

Code
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
)

长时间运行分析代理

Code
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
)

自定义模板代理

Code
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|>""",
)

参数详情

关键参数

  • role, goal, 和 backstory 是必需的,并且塑造了代理的行为
  • llm 决定使用的语言模型(默认:OpenAI 的 GPT-4)

内存和上下文

  • memory: 启用以维护对话历史记录
  • respect_context_window: 防止令牌限制问题
  • 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: 格式化代理响应

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

代理工具

代理可以配备各种工具以增强其能力。CrewAI支持来自以下工具:

以下是如何向代理添加工具:

Code
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
)

代理记忆与上下文

代理可以维护其交互的记忆,并使用来自先前任务的上下文。这对于需要在多个任务之间保留信息的复杂工作流特别有用。

Code
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 来防止令牌限制问题
  • 设置适当的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. 内存问题: 如果代理响应似乎不一致:

    • 验证内存是否启用
    • 检查知识源配置
    • 审查对话历史管理

请记住,根据特定用例配置代理时,代理最为有效。花时间了解您的需求,并相应地调整这些参数。

这个页面有帮助吗?