跳转到内容

智能体

在 CrewAI 框架中,Agent 是一个自治单元,可以:

  • 执行特定任务
  • 根据自身角色和目标做出决策
  • 使用工具完成目标
  • 与其他智能体通信并协作
  • 保留交互记忆
  • 在允许时委派任务
属性参数类型描述
角色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 中创建智能体有两种常见方式:使用 JSONC 项目配置(推荐用于新团队),或者直接在代码中定义。

使用 crewai create crew <name> 创建的新项目采用 JSON 优先配置。每个智能体定义在 agents/<agent_name>.jsonc 中,而 crew.jsonc 则列出团队中的智能体。

按照 安装 章节中描述的方式创建 CrewAI 项目后,编辑 agents/ 中生成的文件。

下面是一个 agents/researcher.jsonc 文件示例:

{
"role": "{topic} Senior Data Researcher",
"goal": "Uncover cutting-edge developments in {topic}",
"backstory": "You find the most relevant information and present it clearly.",
"llm": "openai/gpt-4o",
"tools": ["SerperDevTool"],
"settings": {
"verbose": true,
"allow_delegation": false,
"max_iter": 20
}
}

然后在 crew.jsonc 中包含该智能体:

{
"name": "Research Crew",
"agents": ["researcher"],
"tasks": [
{
"name": "research_task",
"description": "Research {topic}",
"expected_output": "A concise briefing about {topic}",
"agent": "researcher"
}
],
"inputs": {
"topic": "AI Agents"
}
}

智能体文件支持任何公开的 Agent 字段。常见字段包括 rolegoalbackstoryllmtoolsfunction_calling_llmguardrailstep_callbacksettingsverboseallow_delegationmax_itermax_rpmmemorycacheplanning_configuse_system_prompt 等行为选项可以放在顶层或 settings 下;settings 中的值优先。

使用 crewai create crew <name> --classic 创建的经典项目会使用 config/agents.yamlcrew.py 中的 @CrewBase 类。对于希望使用 Python 装饰器或已有 YAML 项目的团队,这种方式仍然受支持。

你可以直接通过实例化 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 (已弃用):此前通过 CodeInterpreterTool 启用内置代码执行。
  • code_execution_mode (已弃用):此前用于控制执行模式(safe 表示 Docker,unsafe 表示直接执行)。
  • multimodal:启用处理文本和视觉内容的多模态能力
  • reasoning:启用智能体在执行任务前进行反思和制定计划
  • inject_date:自动将当前日期注入任务描述
  • system_template:定义智能体的核心行为
  • prompt_template:构造输入格式
  • response_template:格式化智能体响应

智能体可以配备各种工具来增强能力。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
)

CrewAI 提供了复杂的自动上下文窗口管理,用于处理对话长度超过语言模型 token 限制的情况。这个强大的功能由 respect_context_window 参数控制。

当智能体的对话历史变得太长,超出 LLM 的上下文窗口时,CrewAI 会自动检测,并可以采取以下两种方式之一:

  1. 自动摘要内容(当 respect_context_window=True 时)
  2. 以错误终止执行(当 respect_context_window=False 时)

自动上下文处理(respect_context_window=True

Section titled “自动上下文处理(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

Section titled “严格上下文限制(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."
  • 🛑 执行停止:任务会立即中止
  • 🔧 需要人工干预:你需要调整方法

适合使用 respect_context_window=True(默认)的场景:

Section titled “适合使用 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 的场景:

Section titled “适合使用 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
)

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

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
)
# 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
  • multimodal 适合处理同时包含文本和图像输入的任务
  • reasoning 有助于复杂问题拆解和计划制定
  • function_calling_llm 可用于更高效的工具使用
  • 使用 inject_date: true 为智能体提供当前日期感知,适合时间敏感任务
  • 使用 date_format 并按照标准 Python datetime 格式代码自定义日期格式
  • 可用格式代码包括:%Y(年)、%m(月)、%d(日)、%B(完整月份名)等
  • 无效的日期格式会作为警告记录,不会修改任务描述
  • 对于受益于前期规划和反思的复杂任务,启用 reasoning: true
  • 对于不支持系统消息的旧模型,请设置 use_system_prompt: false
  • 确保你选择的 llm 支持所需功能(例如函数调用)
  1. 速率限制:如果你遇到了 API 速率限制:

    • 配置合适的 max_rpm
    • 对重复操作使用缓存
    • 考虑批量请求
  2. 上下文窗口错误:如果你超出了上下文限制:

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

    • 确认 Docker 已安装,以便安全模式使用
    • 检查执行权限
    • 查看代码沙箱设置
  4. 记忆问题:如果智能体响应看起来不一致:

    • 检查知识源配置
    • 查看对话历史管理

请记住,只有根据具体使用场景正确配置后,智能体才能发挥最佳效果。花时间理解你的需求,并相应调整这些参数。