跳转到主要内容

文档索引

获取完整文档索引: https://docs.crewai.com.cn/llms.txt

在深入了解之前,请使用此文件来浏览所有可用页面。

智能体概述

在 CrewAI 框架中,Agent(智能体)是一个自主单元,它可以:
  • 执行特定任务
  • 根据其角色和目标做出决策
  • 使用工具实现目标
  • 与其他智能体进行交流与协作
  • 保持交互记忆
  • 在允许的情况下委派任务
可以将智能体视为具有特定技能、专业知识和职责的专业团队成员。例如,一个 Researcher(研究员)智能体可能擅长收集和分析信息,而一个 Writer(写作)智能体可能更擅长创作内容。
CrewAI AMP 包含一个可视化智能体构建器,无需编写代码即可简化智能体的创建和配置。你可以可视化地设计智能体并进行实时测试。可视化智能体构建器截图可视化智能体构建器支持:
  • 基于表单界面的直观智能体配置
  • 实时测试与验证
  • 预配置智能体类型的模板库
  • 智能体属性和行为的轻松自定义

智能体属性

属性参数类型描述
角色 (Role)rolestr定义智能体在工作组中的职能和专业知识。
目标 (Goal)goalstr指导智能体决策的个人目标。
背景故事 (Backstory)backstorystr提供背景和性格特征,丰富智能体的交互体验。
大语言模型 (LLM) (可选)llmUnion[str, LLM, Any]驱动智能体的语言模型。默认为 OPENAI_MODEL_NAME 中指定的模型或 “gpt-4”。
工具 (Tools) (可选)toolsList[BaseTool]智能体可用的能力或功能。默认为空列表。
函数调用模型 (Function Calling LLM) (可选)function_calling_llmOptional[Any]用于工具调用的语言模型,如果指定,将覆盖工作组的 LLM。
最大迭代次数 (Max Iterations) (可选)max_iterint智能体在必须提供最佳答案前的最大迭代次数。默认值为 20。
最大每分钟请求数 (Max RPM) (可选)max_rpmOptional[int]每分钟最大请求数,以避免触发速率限制。
最大执行时间 (Max Execution Time) (可选)max_execution_timeOptional[int]任务执行的最大时间(以秒为单位)。
详细日志 (Verbose) (可选)verbosebool启用详细的执行日志以供调试。默认为 False。
允许委派 (Allow Delegation) (可选)allow_delegationbool允许智能体将任务委派给其他智能体。默认为 False。
步骤回调 (Step Callback) (可选)step_callbackOptional[Any]在每个智能体步骤后调用的函数,将覆盖工作组回调。
缓存 (Cache) (可选)cachebool为工具使用启用缓存。默认为 True。
系统模板 (System Template) (可选)system_templateOptional[str]智能体的自定义系统提示词模板。
提示词模板 (Prompt Template) (可选)prompt_templateOptional[str]智能体的自定义提示词模板。
响应模板 (Response Template) (可选)response_templateOptional[str]智能体的自定义响应模板。
允许代码执行 (Allow Code Execution) (可选)allow_code_executionOptional[bool]启用智能体的代码执行功能。默认为 False。
最大重试次数 (Max Retry Limit) (可选)max_retry_limitint发生错误时的最大重试次数。默认值为 2。
遵守上下文窗口 (Respect Context Window) (可选)respect_context_windowbool通过摘要保持消息在上下文窗口大小限制内。默认为 True。
代码执行模式 (Code Execution Mode) (可选)code_execution_modeLiteral["safe", "unsafe"]代码执行模式:“safe”(使用 Docker)或“unsafe”(直接执行)。默认为“safe”。
多模态 (Multimodal) (可选)multimodalbool智能体是否支持多模态能力。默认为 False。
注入日期 (Inject Date) (可选)inject_datebool是否自动将当前日期注入任务。默认为 False。
日期格式 (Date Format) (可选)date_formatstr启用 inject_date 时的日期格式字符串。默认为 “%Y-%m-%d”(ISO 格式)。
推理 (Reasoning) (可选)reasoningbool智能体在执行任务前是否应反思并制定计划。默认为 False。
最大推理尝试次数 (Max Reasoning Attempts) (可选)max_reasoning_attemptsOptional[int]执行任务前的最大推理尝试次数。如果为 None,将尝试直到准备就绪。
嵌入模型 (Embedder) (可选)embedderOptional[Dict[str, Any]]智能体使用的嵌入模型配置。
知识源 (Knowledge Sources) (可选)knowledge_sourcesOptional[List[BaseKnowledgeSource]]智能体可用的知识源。
使用系统提示词 (Use System Prompt) (可选)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
)

参数详情

关键参数

  • role, goalbackstory 是必填项,决定了智能体的行为。
  • llm 确定使用的语言模型(默认:OpenAI 的 GPT-4)。

记忆与上下文

  • memory: 启用以保持对话历史。
  • respect_context_window: 防止 Token 限制问题。
  • knowledge_sources: 添加特定领域的知识库。

执行控制

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

代码执行

allow_code_executioncode_execution_mode 已弃用。CodeInterpreterTool 已从 crewai-tools 中移除。请使用如 E2BModal 等专用沙箱服务进行安全的代码执行。
  • allow_code_execution (已弃用): 此前通过 CodeInterpreterTool 启用内置代码执行。
  • code_execution_mode (已弃用): 此前控制执行模式("safe" 用于 Docker,"unsafe" 用于直接执行)。

高级功能

  • 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 包含了完善的自动上下文窗口管理功能,用于处理对话超出语言模型 Token 限制的情况。此功能由 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
)
当超出上下文限制时会发生什么
  • ⚠️ 警告消息: "Context length exceeded. Summarizing content to fit the model context window."(上下文长度超出限制。正在摘要内容以适应模型上下文窗口。)
  • 🔄 自动摘要: CrewAI 智能地摘要对话历史。
  • 继续执行: 任务执行在摘要后的上下文中无缝继续。
  • 📝 保留信息: 在减少 Token 数量的同时保留关键信息。

严格的上下文限制 (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
)
当超出上下文限制时会发生什么
  • 错误消息: "Context length exceeded. Consider using smaller text or RAG tools from crewai_tools."(上下文长度超出限制。考虑使用更小的文本或来自 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

  • 精确度至关重要,不可接受任何信息丢失。
  • 法律或医疗任务,需要完整的上下文。
  • 代码审查,缺失细节可能导致引入 bug。
  • 财务分析,准确性至关重要。
代码
# 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: 执行的 Token 使用指标。

结构化输出

你可以通过提供一个 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_executioncode_execution_mode 已弃用,且 CodeInterpreterTool 已移除。请使用如 E2BModal 等专用沙箱服务进行安全的代码执行。

性能优化

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

记忆与上下文管理

  • 利用 knowledge_sources 获取特定领域信息。
  • 在使用自定义嵌入模型时配置 embedder
  • 使用自定义模板 (system_template, prompt_template, response_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. 记忆问题: 如果智能体响应似乎不一致:
    • 检查知识源配置。
    • 审查对话历史管理。
请记住,智能体在根据特定用例配置时效率最高。花时间了解你的需求并相应地调整这些参数。