Agents
关于如何在 CrewAI 框架中创建和管理 Agent 的详细指南。
Agent 概览
在 CrewAI 框架中,Agent 是一个自治单元,它可以:
- 执行特定任务
- 根据自身角色和目标做出决策
- 使用工具完成目标
- 与其他 Agent 沟通和协作
- 维护交互记忆
- 在被允许时委派任务
Researcher Agent 可能擅长收集和分析信息,而一个 Writer Agent 则可能更擅长内容创作。
<img src="https://mintcdn.com/crewai/5SZbe87tsCWZY09V/images/enterprise/crew-studio-interface.png?fit=max&auto=format&n=5SZbe87tsCWZY09V&q=85&s=c4f5428b111816273b3b53d9cef14fad" alt="Visual Agent Builder Screenshot" width="2654" height="1710" data-path="images/enterprise/crew-studio-interface.png" />
可视化 Agent 构建器支持:
使用基于表单的界面进行直观的 Agent 配置
实时测试与验证
带有预配置 Agent 类型的模板库
便捷地自定义 Agent 属性与行为
Agent 属性
| 属性 | 参数 | 类型 | 说明 |
|---|---|---|---|
| 角色 | role |
str |
定义 Agent 在 crew 中的职能和专业领域。 |
| 目标 | goal |
str |
引导 Agent 做出决策的个人目标。 |
| 背景故事 | backstory |
str |
为 Agent 提供上下文和个性特征,从而增强交互表现。 |
| LLM (可选) | llm |
Union[str, LLM, Any] |
驱动 Agent 的语言模型。默认使用 OPENAI_MODEL_NAME 中指定的模型或 "gpt-4"。 |
| 工具 (可选) | tools |
List[BaseTool] |
Agent 可用的能力或函数。默认为空列表。 |
| 函数调用 LLM (可选) | function_calling_llm |
Optional[Any] |
用于工具调用的语言模型;如果指定,则会覆盖 crew 的 LLM。 |
| 最大迭代次数 (可选) | max_iter |
int |
Agent 在必须给出最佳答案前允许执行的最大迭代次数。默认是 20。 |
| 最大 RPM (可选) | max_rpm |
Optional[int] |
每分钟最大请求数,用于避免触发速率限制。 |
| 最大执行时间 (可选) | max_execution_time |
Optional[int] |
任务执行的最大时间(秒)。 |
| 详细模式 (可选) | verbose |
bool |
启用详细执行日志,便于调试。默认是 False。 |
| 允许委派 (可选) | allow_delegation |
bool |
是否允许 Agent 将任务委派给其他 Agent。默认是 False。 |
| 步骤回调 (可选) | step_callback |
Optional[Any] |
每个 Agent 步骤后调用的函数,会覆盖 crew 的回调。 |
| 缓存 (可选) | cache |
bool |
是否启用工具使用缓存。默认是 True。 |
| 系统模板 (可选) | system_template |
Optional[str] |
Agent 的自定义系统 Prompt 模板。 |
| Prompt 模板 (可选) | prompt_template |
Optional[str] |
Agent 的自定义 Prompt 模板。 |
| 响应模板 (可选) | response_template |
Optional[str] |
Agent 的自定义响应模板。 |
| 允许代码执行 (可选) | allow_code_execution |
Optional[bool] |
是否允许 Agent 执行代码。默认是 False。 |
| 最大重试次数 (可选) | max_retry_limit |
int |
出现错误时允许的最大重试次数。默认是 2。 |
| 尊重上下文窗口 (可选) | respect_context_window |
bool |
通过摘要方式将消息控制在上下文窗口大小内。默认是 True。 |
| 代码执行模式 (可选) | code_execution_mode |
Literal["safe", "unsafe"] |
代码执行模式:'safe'(使用 Docker)或 'unsafe'(直接执行)。默认是 'safe'。 |
| 多模态 (可选) | multimodal |
bool |
Agent 是否支持多模态能力。默认是 False。 |
| 注入日期 (可选) | inject_date |
bool |
是否自动将当前日期注入任务中。默认是 False。 |
| 日期格式 (可选) | date_format |
str |
当启用 inject_date 时使用的日期格式字符串。默认是 "%Y-%m-%d"(ISO 格式)。 |
| 推理 (可选) | reasoning |
bool |
Agent 在执行任务前是否应进行反思并创建计划。默认是 False。 |
| 最大推理尝试次数 (可选) | max_reasoning_attempts |
Optional[int] |
执行任务前允许的最大推理尝试次数。如果为 None,则会一直尝试直到准备就绪。 |
| 嵌入器 (可选) | embedder |
Optional[Dict[str, Any]] |
Agent 使用的嵌入器配置。 |
| 知识源 (可选) | knowledge_sources |
Optional[List[BaseKnowledgeSource]] |
Agent 可用的知识源。 |
| 使用系统 Prompt (可选) | use_system_prompt |
Optional[bool] |
是否使用系统 Prompt(用于支持 o1 模型)。默认是 True。 |
创建 Agent
在 CrewAI 中有两种方式可以创建 Agent:使用 YAML 配置(推荐) 或 直接在代码中定义。
YAML 配置(推荐)
使用 YAML 配置是一种更清晰、更易维护的 Agent 定义方式。我们强烈建议你在 CrewAI 项目中采用这种方式。
按照 安装 章节所述创建 CrewAI 项目后,进入 src/latest_ai_development/config/agents.yaml 文件,并修改模板以符合你的需求。
{topic})会在运行 crew 时,被输入中的值替换:
python
crew.kickoff(inputs={'topic': 'AI Agents'})
以下是一个使用 YAML 配置 Agent 的示例:
# src/latest_ai_development/config/agents.yamlresearcher:role: >{topic} Senior Data Researchergoal: >Uncover cutting-edge developments in {topic}backstory: >You're a seasoned researcher with a knack for uncovering the latestdevelopments in {topic}. Known for your ability to find the most relevantinformation and present it in a clear and concise manner.reporting_analyst:role: >{topic} Reporting Analystgoal: >Create detailed reports based on {topic} data analysis and research findingsbackstory: >You're a meticulous analyst with a keen eye for detail. You're known foryour ability to turn complex data into clear and concise reports, makingit easy for others to understand and act on the information you provide.
要在代码中使用这份 YAML 配置,请创建一个继承自 CrewBase 的 crew 类:
# src/latest_ai_development/crew.pyfrom crewai import Agent, Crew, Processfrom crewai.project import CrewBase, agent, crewfrom crewai_tools import SerperDevTool@CrewBaseclass LatestAiDevelopmentCrew():"""LatestAiDevelopment crew"""agents_config = "config/agents.yaml"@agentdef researcher(self) -> Agent:return Agent(config=self.agents_config['researcher'], # type: ignore[index]verbose=True,tools=[SerperDevTool()])@agentdef reporting_analyst(self) -> Agent:return Agent(config=self.agents_config['reporting_analyst'], # type: ignore[index]verbose=True)
agents.yaml)中使用的名称,应当与 Python 代码中的方法名保持一致。
直接用代码定义
你也可以通过实例化 Agent 类,直接在代码中创建 Agent。下面是一个展示所有可用参数的完整示例:
from crewai import Agentfrom crewai_tools import SerperDevTool# Create an agent with all available parametersagent = 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 callingverbose=False, # Default: Falseallow_delegation=False, # Default: Falsemax_iter=20, # Default: 20 iterationsmax_rpm=None, # Optional: Rate limit for API callsmax_execution_time=None, # Optional: Maximum execution time in secondsmax_retry_limit=2, # Default: 2 retries on errorallow_code_execution=False, # Default: Falsecode_execution_mode="safe", # Default: "safe" (options: "safe", "unsafe")respect_context_window=True, # Default: Trueuse_system_prompt=True, # Default: Truemultimodal=False, # Default: Falseinject_date=False, # Default: Falsedate_format="%Y-%m-%d", # Default: ISO formatreasoning=False, # Default: Falsemax_reasoning_attempts=None, # Default: Nonetools=[SerperDevTool()], # Optional: List of toolsknowledge_sources=None, # Optional: List of knowledge sourcesembedder=None, # Optional: Custom embedder configurationsystem_template=None, # Optional: Custom system prompt templateprompt_template=None, # Optional: Custom prompt templateresponse_template=None, # Optional: Custom response templatestep_callback=None, # Optional: Callback function for monitoring)
下面我们拆解一些常见用例中的关键参数组合:
基础研究 Agent
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)
代码开发 Agent
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 safetymax_execution_time=300, # 5-minute timeoutmax_retry_limit=3 # More retries for complex code tasks)
长时间运行的分析 Agent
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 callsfunction_calling_llm="gpt-4o-mini" # Cheaper model for tool calls)
自定义模板 Agent
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|>""",)
带日期感知和推理能力的 Agent
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 tasksdate_format="%B %d, %Y", # Format as "May 21, 2025"reasoning=True, # Enable strategic planningmax_reasoning_attempts=2, # Limit planning iterationsverbose=True)
推理型 Agent
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 planningmax_reasoning_attempts=3, # Limit reasoning attemptsmax_iter=30, # Allow more iterations for complex planningverbose=True)
多模态 Agent
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 capabilitiesverbose=True)
参数详解
关键参数
role、goal和backstory是必填项,它们共同塑造 Agent 的行为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":直接执行(仅在可信环境中使用)
高级特性
multimodal:启用后可处理文本和视觉内容reasoning:启用后,Agent 会先反思并制定计划,再执行任务inject_date:自动将当前日期注入任务描述中
模板
system_template:定义 Agent 的核心行为prompt_template:定义输入格式结构response_template:定义 Agent 的响应格式
system_template 和 prompt_template。response_template 是可选的,但建议提供,以保持输出格式一致。
{role}、{goal} 和 {backstory} 等变量。执行时这些变量会被自动填充。
Agent 工具
你可以为 Agent 配置多种工具,以增强其能力。CrewAI 支持以下来源的工具:
以下是为 Agent 添加工具的方法:
from crewai import Agentfrom crewai_tools import SerperDevTool, WikipediaTools# Create toolssearch_tool = SerperDevTool()wiki_tool = WikipediaTools()# Add tools to agentresearcher = Agent(role="AI Technology Researcher",goal="Research the latest AI developments",tools=[search_tool, wiki_tool],verbose=True)
Agent 记忆与上下文
Agent 可以保留其交互记忆,并使用前面任务提供的上下文。这对于需要跨多个任务保留信息的复杂工作流尤其有用。
from crewai import Agentanalyst = Agent(role="Data Analyst",goal="Analyze and remember complex data patterns",memory=True, # Enable memoryverbose=True)
memory 时,Agent 会在多次交互之间保持上下文,从而提升其处理复杂多步骤任务的能力。
上下文窗口管理
CrewAI 内置了复杂的自动上下文窗口管理机制,用于处理对话内容超出语言模型 Token 限制的情况。这个强大功能由 respect_context_window 参数控制。
上下文窗口管理如何工作
当 Agent 的对话历史过大,超过 LLM 的上下文窗口时,CrewAI 会自动检测这种情况,并可以选择:
- 自动总结内容(当
respect_context_window=True时) - 报错并停止执行(当
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 limitsverbose=True)
当上下文超限时会发生:
- ⚠️ 警告信息:
"Context length exceeded. Summarizing content to fit the model context window." - 🔄 自动摘要:CrewAI 会智能总结对话历史
- ✅ 继续执行:任务会在摘要后的上下文上无缝继续
- 📝 保留关键信息:核心信息会被保留,同时减少 Token 数量
严格上下文限制(respect_context_window=False)
当你需要精确控制,并且宁愿中止执行也不接受信息损失时:
# Agent with strict context limitsstrict_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 limitverbose=True)
当上下文超限时会发生:
- ❌ 错误信息:
"Context length exceeded. Consider using smaller text or RAG tools from crewai_tools." - 🛑 停止执行:任务会立即中止
- 🔧 需要人工干预:你必须修改处理方式
如何选择合适的设置
以下场景建议使用 respect_context_window=True(默认):
- 处理大型文档,可能超出上下文限制
- 长时间对话,允许一定程度的总结
- 研究任务,更关注总体上下文而非逐字精确内容
- 原型开发阶段,希望执行更稳健
# Perfect for document processingdocument_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 gracefullymax_iter=50, # Allow more iterations for complex analysisverbose=True)
以下场景建议使用 respect_context_window=False:
- 精度至关重要,不能接受任何信息丢失
- 法律或医疗任务,要求完整上下文
- 代码审查,遗漏细节可能引入 Bug
- 金融分析,准确性要求极高
# Perfect for precision tasksprecision_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 analysismax_retry_limit=1, # Fail fast on context issuesverbose=True)
处理大数据的替代方案
当处理非常大的数据集时,可以考虑以下策略:
1. 使用 RAG 工具
from crewai_tools import RagTool# Create RAG tool for large document processingrag_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 windowsrespect_context_window=True,verbose=True)
2. 使用知识源
# Use knowledge sources instead of large promptsknowledge_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 knowledgerespect_context_window=True,verbose=True)
上下文窗口最佳实践
- 监控上下文使用情况:启用
verbose=True,观察上下文管理是如何工作的 - 为效率而设计:设计任务时尽量减少上下文累积
- 选择合适的模型:使用具有足够上下文窗口的 LLM
- 两种设置都进行测试:分别尝试
True和False,找到更适合你的场景的方式 - 结合 RAG 使用:对于特别大的数据集,使用 RAG,而不是只依赖上下文窗口
排查上下文问题
如果你遇到上下文上限报错:
# Quick fix: Enable automatic handlingagent.respect_context_window = True# Better solution: Use RAG tools for large datafrom crewai_tools import RagToolagent.tools = [RagTool()]# Alternative: Break tasks into smaller pieces# Or use knowledge sources instead of large prompts
如果自动摘要丢失了重要信息:
# Disable auto-summarization and use RAG insteadagent = Agent(role="Detailed Analyst",goal="Maintain complete information accuracy",backstory="Expert requiring full context",respect_context_window=False, # No summarizationtools=[RagTool()], # Use RAG for large dataverbose=True)
respect_context_window 设置为你希望的行为方式,剩下的由 CrewAI 自动处理!
使用 kickoff() 进行 Agent 直接交互
你可以不经过 task 或 crew 工作流,而是直接使用 kickoff() 方法与 Agent 交互。当你不需要完整 crew 编排能力时,这是一种更简单的方式。
kickoff() 如何工作
kickoff() 方法允许你直接向 Agent 发送消息并获得回复,类似于直接与 LLM 交互,但同时保留了 Agent 的全部能力(工具、推理等)。
from crewai import Agentfrom crewai_tools import SerperDevTool# Create an agentresearcher = Agent(role="AI Technology Researcher",goal="Research the latest AI developments",tools=[SerperDevTool()],verbose=True)# Use kickoff() to interact directly with the agentresult = researcher.kickoff("What are the latest developments in language models?")# Access the raw responseprint(result.raw)
参数与返回值
| 参数 | 类型 | 说明 |
|---|---|---|
messages |
Union[str, List[Dict[str, str]]] |
可以是字符串查询,也可以是包含 role / content 的消息字典列表 |
response_format |
Optional[Type[Any]] |
可选的 Pydantic 模型,用于结构化输出 |
该方法返回一个 LiteAgentOutput 对象,具有以下属性:
raw:原始输出文本字符串pydantic:解析后的 Pydantic 模型(如果提供了response_format)agent_role:生成该输出的 Agent 角色usage_metrics:本次执行的 Token 使用统计
结构化输出
你可以通过传入 Pydantic 模型作为 response_format 来获取结构化输出:
from pydantic import BaseModelfrom typing import Listclass ResearchFindings(BaseModel):main_points: List[str]key_technologies: List[str]future_predictions: str# Get structured outputresult = researcher.kickoff("Summarize the latest developments in AI for 2025",response_format=ResearchFindings)# Access structured dataprint(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 asyncioasync def main():result = await researcher.kickoff_async("What are the latest developments in AI?")print(result.raw)asyncio.run(main())
kickoff() 方法内部使用的是 LiteAgent,它提供了更简化的执行流程,同时保留了 Agent 的全部配置(角色、目标、背景故事、工具等)。
重要注意事项与最佳实践
安全性与代码执行
- 当使用
allow_code_execution时,要谨慎处理用户输入,并始终进行校验 - 在生产环境中使用
code_execution_mode: "safe"(Docker) - 考虑设置合理的
max_execution_time,防止无限循环
性能优化
- 使用
respect_context_window: true,避免 Token 上限问题 - 设置适当的
max_rpm,避免触发速率限制 - 启用
cache: true,提升重复任务的性能 - 根据任务复杂度调整
max_iter和max_retry_limit
记忆与上下文管理
- 使用
knowledge_sources注入领域知识 - 在使用自定义嵌入模型时配置
embedder - 使用自定义模板(
system_template、prompt_template、response_template)精细控制 Agent 行为
高级特性
- 对需要在执行复杂任务前先计划和反思的 Agent,启用
reasoning: true - 设置合适的
max_reasoning_attempts,控制规划迭代次数(None 表示不设上限) - 使用
inject_date: true,让 Agent 具备当前日期感知能力,以处理时效性任务 - 使用标准 Python datetime 格式码,通过
date_format自定义日期格式 - 对需要同时处理文本和视觉内容的 Agent,启用
multimodal: true
Agent 协作
- 当 Agent 需要彼此配合时,启用
allow_delegation: true - 使用
step_callback监控并记录 Agent 交互 考虑为不同用途使用不同的 LLM:
- 主
llm用于复杂推理 function_calling_llm用于高效工具调用
- 主
日期感知与推理
- 使用
inject_date: true,让 Agent 具备日期感知能力 - 使用标准 Python datetime 格式码通过
date_format自定义日期格式 - 常见格式码包括:
%Y(年)、%m(月)、%d(日)、%B(完整月份名)等 - 无效日期格式会以警告形式记录,并且不会修改任务描述
- 对于适合提前规划与反思的复杂任务,启用
reasoning: true
模型兼容性
- 对于不支持 system message 的旧模型,请设置
use_system_prompt: false - 确保所选
llm支持你需要的功能(例如 function calling)
常见问题排查
速率限制:如果你遇到了 API 速率限制:
- 设置合适的
max_rpm - 为重复操作启用缓存
- 考虑批量处理请求
- 设置合适的
上下文窗口错误:如果你超过了上下文限制:
- 启用
respect_context_window - 使用更高效的 Prompt
- 定期清理 Agent 记忆
- 启用
代码执行问题:如果代码执行失败:
- 确认 safe 模式下 Docker 已安装
- 检查执行权限
- 查看代码沙箱设置
记忆问题:如果 Agent 的回复看起来不一致:
- 检查知识源配置
- 检查对话历史管理方式
请记住,只有根据具体用例进行恰当配置时,Agent 才能发挥最大效果。花时间理解你的需求,并相应调整这些参数。
