跳转到主要内容

代理概述

在 CrewAI 框架中,Agent 是一个自治单元,可以
  • 执行特定任务
  • 根据其角色和目标做出决策
  • 使用工具完成目标
  • 与其他代理沟通和协作
  • 维护交互记忆
  • 允许时委派任务
可以将代理视为具有特定技能、专业知识和职责的专业团队成员。例如,一个研究员代理可能擅长收集和分析信息,而一个作家代理可能更擅长创作内容。
CrewAI AOP 包含一个可视化代理构建器,无需编写代码即可简化代理的创建和配置。可视化设计您的代理并实时测试它们。Visual Agent Builder Screenshot可视化代理构建器支持:
  • 通过基于表单的界面进行直观的代理配置
  • 实时测试和验证
  • 带有预配置代理类型的模板库
  • 轻松自定义代理属性和行为

代理属性

属性参数类型描述
角色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]任务执行的最大时间(秒)。
详细模式 (可选)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”。
多模态 (可选)multimodalbool代理是否支持多模态能力。默认值为 False。
注入日期 (可选)inject_datebool是否自动将当前日期注入任务。默认值为 False。
日期格式 (可选)date_formatstr启用 inject_date 时日期的格式字符串。默认值为“%Y-%m-%d”(ISO 格式)。
推理 (可选)reasoningbool代理是否应在执行任务前进行反思并制定计划。默认值为 False。
最大推理尝试次数 (可选)max_reasoning_attemptsOptional[int]执行任务前的最大推理尝试次数。如果为 None,将尝试直到准备就绪。
嵌入器 (可选)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
    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
    multimodal=False,  # Default: False
    inject_date=False,  # Default: False
    date_format="%Y-%m-%d",  # Default: ISO format
    reasoning=False,  # Default: False
    max_reasoning_attempts=None,  # Default: None
    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|>""",
)

具有推理功能的日期感知代理

代码
strategic_agent = Agent(
    role="Market Analyst",
    goal="Track market movements with precise date references and strategic planning",
    backstory="Expert in time-sensitive financial analysis and strategic reporting",
    inject_date=True,  # Automatically inject current date into tasks
    date_format="%B %d, %Y",  # Format as "May 21, 2025"
    reasoning=True,  # Enable strategic planning
    max_reasoning_attempts=2,  # Limit planning iterations
    verbose=True
)

推理代理

代码
reasoning_agent = Agent(
    role="Strategic Planner",
    goal="Analyze complex problems and create detailed execution plans",
    backstory="Expert strategic planner who methodically breaks down complex challenges",
    reasoning=True,  # Enable reasoning and planning
    max_reasoning_attempts=3,  # Limit reasoning attempts
    max_iter=30,  # Allow more iterations for complex planning
    verbose=True
)

多模态代理

代码
multimodal_agent = Agent(
    role="Visual Content Analyst",
    goal="Analyze and process both text and visual content",
    backstory="Specialized in multimodal analysis combining text and image understanding",
    multimodal=True,  # Enable multimodal capabilities
    verbose=True
)

参数详情

关键参数

  • rolegoalbackstory 是必需的,并塑造代理的行为
  • 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":直接执行(仅在受信任的环境中使用)
这将运行默认的 Docker 镜像。如果您想配置 Docker 镜像,请查看工具部分中的代码解释器工具。将代码解释器工具作为代理的工具参数添加。

高级功能

  • multimodal:启用多模态功能以处理文本和视觉内容
  • reasoning:使代理能够在执行任务前进行反思并制定计划
  • inject_date:自动将当前日期注入任务描述

模板

  • 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 后,代理将跨多个交互维护上下文,从而提高其处理复杂、多步骤任务的能力。

上下文窗口管理

CrewAI 包含复杂的自动上下文窗口管理,用于处理对话超出语言模型令牌限制的情况。此强大功能由 respect_context_window 参数控制。

上下文窗口管理的工作原理

当代理的对话历史对于 LLM 的上下文窗口来说变得过大时,CrewAI 会自动检测到这种情况,并且可以
  1. 自动总结内容(当 respect_context_window=True 时)
  2. 停止执行并报错(当 respect_context_window=False 时)

自动上下文处理(respect_context_window=True

这是大多数用例的默认和推荐设置。启用后,CrewAI 将
代码
# Agent with automatic context management (default)
smart_agent = Agent(
    role="Research Analyst",
    goal="Analyze large documents and datasets",
    backstory="Expert at processing extensive information",
    respect_context_window=True,  # 🔑 Default: auto-handle context limits
    verbose=True
)
当超出上下文限制时会发生什么
  • ⚠️ 警告消息"上下文长度超出。正在总结内容以适应模型上下文窗口。"
  • 🔄 自动总结:CrewAI 智能地总结对话历史
  • 继续执行:任务执行与总结后的上下文无缝地继续
  • 📝 保留信息:在减少令牌计数的同时保留关键信息

严格上下文限制(respect_context_window=False

当您需要精确控制并希望执行停止而不是丢失任何信息时
代码
# Agent with strict context limits
strict_agent = Agent(
    role="Legal Document Reviewer",
    goal="Provide precise legal analysis without information loss",
    backstory="Legal expert requiring complete context for accurate analysis",
    respect_context_window=False,  # ❌ Stop execution on context limit
    verbose=True
)
当超出上下文限制时会发生什么
  • 错误消息"上下文长度超出。请考虑使用更小的文本或 crewai_tools 中的 RAG 工具。"
  • 🛑 执行停止:任务执行立即停止
  • 🔧 需要手动干预:您需要修改您的方法

选择正确的设置

在以下情况下使用 respect_context_window=True(默认)

  • 处理可能超出上下文限制的大型文档
  • 长时间运行的对话,其中一些总结是可接受的
  • 研究任务,其中一般上下文比确切细节更重要
  • 原型设计和开发,您希望获得健壮的执行
代码
# Perfect for document processing
document_processor = Agent(
    role="Document Analyst",
    goal="Extract insights from large research papers",
    backstory="Expert at analyzing extensive documentation",
    respect_context_window=True,  # Handle large documents gracefully
    max_iter=50,  # Allow more iterations for complex analysis
    verbose=True
)

在以下情况下使用 respect_context_window=False

  • 精度至关重要,信息丢失不可接受
  • 法律或医疗任务需要完整的上下文
  • 代码审查,其中丢失细节可能导致错误
  • 财务分析,其中准确性至关重要
代码
# Perfect for precision tasks
precision_agent = Agent(
    role="Code Security Auditor",
    goal="Identify security vulnerabilities in code",
    backstory="Security expert requiring complete code context",
    respect_context_window=False,  # Prefer failure over incomplete analysis
    max_retry_limit=1,  # Fail fast on context issues
    verbose=True
)

处理大数据量的替代方法

处理超大数据集时,请考虑以下策略:

1. 使用 RAG 工具

代码
from crewai_tools import RagTool

# Create RAG tool for large document processing
rag_tool = RagTool()

rag_agent = Agent(
    role="Research Assistant",
    goal="Query large knowledge bases efficiently",
    backstory="Expert at using RAG tools for information retrieval",
    tools=[rag_tool],  # Use RAG instead of large context windows
    respect_context_window=True,
    verbose=True
)

2. 使用知识源

代码
# Use knowledge sources instead of large prompts
knowledge_agent = Agent(
    role="Knowledge Expert",
    goal="Answer questions using curated knowledge",
    backstory="Expert at leveraging structured knowledge sources",
    knowledge_sources=[your_knowledge_sources],  # Pre-processed knowledge
    respect_context_window=True,
    verbose=True
)

上下文窗口最佳实践

  1. 监控上下文使用情况:启用 verbose=True 以查看上下文管理的作用
  2. 设计效率:构建任务以最大程度地减少上下文积累
  3. 使用适当的模型:选择具有适合您任务的上下文窗口的 LLM
  4. 测试两种设置:尝试 TrueFalse,看看哪种更适合您的用例
  5. 与 RAG 结合使用:对于非常大的数据集,使用 RAG 工具而不是仅依赖上下文窗口

上下文问题故障排除

如果您遇到上下文限制错误
代码
# Quick fix: Enable automatic handling
agent.respect_context_window = True

# Better solution: Use RAG tools for large data
from crewai_tools import RagTool
agent.tools = [RagTool()]

# Alternative: Break tasks into smaller pieces
# Or use knowledge sources instead of large prompts
如果自动摘要丢失了重要信息
代码
# Disable auto-summarization and use RAG instead
agent = Agent(
    role="Detailed Analyst",
    goal="Maintain complete information accuracy",
    backstory="Expert requiring full context",
    respect_context_window=False,  # No summarization
    tools=[RagTool()],  # Use RAG for large data
    verbose=True
)
上下文窗口管理功能在后台自动运行。您无需调用任何特殊函数——只需将 respect_context_window 设置为您喜欢的行为,CrewAI 会处理其余部分!

通过 kickoff() 直接代理交互

代理可以直接使用,而无需通过任务或团队工作流,只需使用 kickoff() 方法。当您不需要完整的团队编排功能时,这提供了一种与代理交互的更简单方式。

kickoff() 的工作原理

kickoff() 方法允许您直接向代理发送消息并获得响应,类似于您与 LLM 交互的方式,但具有代理的所有功能(工具、推理等)。
代码
from crewai import Agent
from crewai_tools import SerperDevTool

# Create an agent
researcher = Agent(
    role="AI Technology Researcher",
    goal="Research the latest AI developments",
    tools=[SerperDevTool()],
    verbose=True
)

# Use kickoff() to interact directly with the agent
result = researcher.kickoff("What are the latest developments in language models?")

# Access the raw response
print(result.raw)

参数和返回值

参数类型描述
messagesUnion[str, List[Dict[str, str]]]字符串查询或包含角色/内容的字典消息列表
response_formatOptional[Type[Any]]用于结构化输出的可选 Pydantic 模型
该方法返回一个具有以下属性的 LiteAgentOutput 对象
  • raw:包含原始输出文本的字符串
  • pydantic:解析的 Pydantic 模型(如果提供了 response_format
  • agent_role:生成输出的代理角色
  • usage_metrics:执行的令牌使用指标

结构化输出

您可以通过提供 Pydantic 模型作为 response_format 来获得结构化输出
代码
from pydantic import BaseModel
from typing import List

class ResearchFindings(BaseModel):
    main_points: List[str]
    key_technologies: List[str]
    future_predictions: str

# Get structured output
result = researcher.kickoff(
    "Summarize the latest developments in AI for 2025",
    response_format=ResearchFindings
)

# Access structured data
print(result.pydantic.main_points)
print(result.pydantic.future_predictions)

多条消息

您还可以提供对话历史作为消息字典列表
代码
messages = [
    {"role": "user", "content": "I need information about large language models"},
    {"role": "assistant", "content": "I'd be happy to help with that! What specifically would you like to know?"},
    {"role": "user", "content": "What are the latest developments in 2025?"}
]

result = researcher.kickoff(messages)

异步支持

异步版本可通过 kickoff_async() 获得,参数相同
代码
import asyncio

async def main():
    result = await researcher.kickoff_async("What are the latest developments in AI?")
    print(result.raw)

asyncio.run(main())
kickoff() 方法内部使用 LiteAgent,它提供了一个更简单的执行流程,同时保留了代理的所有配置(角色、目标、背景故事、工具等)。

重要注意事项和最佳实践

安全与代码执行

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

性能优化

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

记忆与上下文管理

  • 利用 knowledge_sources 获取领域特定信息
  • 使用自定义嵌入模型时配置 embedder
  • 使用自定义模板(system_templateprompt_templateresponse_template)精细控制代理行为

高级功能

  • 为需要在执行复杂任务前进行规划和反思的代理启用 reasoning: true
  • 设置适当的 max_reasoning_attempts 以控制规划迭代次数(None 表示无限次尝试)
  • 使用 inject_date: true 为对时间敏感的任务提供代理当前日期意识
  • 使用标准 Python datetime 格式代码自定义 date_format
  • 为需要处理文本和视觉内容的代理启用 multimodal: true

代理协作

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

日期感知和推理

  • 使用 inject_date: true 为对时间敏感的任务提供代理当前日期意识
  • 使用标准 Python datetime 格式代码自定义 date_format
  • 有效格式代码包括:%Y(年份)、%m(月份)、%d(日期)、%B(完整月份名称)等。
  • 无效日期格式将作为警告记录,并且不会修改任务描述
  • 为受益于前期规划和反思的复杂任务启用 reasoning: true

模型兼容性

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

常见问题故障排除

  1. 速率限制:如果您遇到 API 速率限制
    • 实施适当的 max_rpm
    • 对重复操作使用缓存
    • 考虑批量请求
  2. 上下文窗口错误:如果您超出上下文限制
    • 启用 respect_context_window
    • 使用更有效的提示
    • 定期清除代理记忆
  3. 代码执行问题:如果代码执行失败
    • 验证 Docker 是否已安装以实现安全模式
    • 检查执行权限
    • 审查代码沙盒设置
  4. 记忆问题:如果代理响应似乎不一致
    • 检查知识源配置
    • 审查对话历史管理
请记住,代理在根据其特定用例进行配置时最有效。花时间了解您的要求并相应地调整这些参数。