跳转到主要内容

智能体概述

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

智能体属性

属性参数类型描述
角色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:防止 token 限制问题
  • 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_template 都已定义。response_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
)
当超出上下文限制时会发生什么
  • ⚠️ 警告消息: "上下文长度超出。正在摘要内容以适应模型上下文窗口。"
  • 🔄 自动摘要: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
)
当超出上下文限制时会发生什么
  • 错误消息: "上下文长度超出。考虑使用更小的文本或来自 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:执行的 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_execution 时,请谨慎处理用户输入并始终对其进行验证
  • 在生产环境中使用 code_execution_mode: "safe" (Docker)
  • 考虑设置适当的 max_execution_time 限制以防止无限循环

性能优化

  • 使用 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 日期时间格式代码通过 `date_format` 自定义日期格式
  • 为需要处理文本和视觉内容的智能体启用 `multimodal: true`

智能体协作

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

日期意识与推理

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

模型兼容性

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

常见问题故障排除

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