Agents

关于如何在 CrewAI 框架中创建和管理 Agent 的详细指南。

Agent 概览

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

  • 执行特定任务
  • 根据自身角色和目标做出决策
  • 使用工具完成目标
  • 与其他 Agent 沟通和协作
  • 维护交互记忆
  • 在被允许时委派任务
你可以将 Agent 理解为一个具备特定技能、专业知识和职责的团队成员。例如,一个 Researcher Agent 可能擅长收集和分析信息,而一个 Writer Agent 则可能更擅长内容创作。 CrewAI AMP 提供了一个可视化 Agent 构建器,无需编写代码即可简化 Agent 的创建与配置。你可以通过可视化方式设计 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 文件,并修改模板以符合你的需求。

你在 YAML 文件中使用的变量(例如 {topic})会在运行 crew 时,被输入中的值替换: python crew.kickoff(inputs={'topic': 'AI Agents'})

以下是一个使用 YAML 配置 Agent 的示例:

  1. # src/latest_ai_development/config/agents.yaml
  2. researcher:
  3. role: >
  4. {topic} Senior Data Researcher
  5. goal: >
  6. Uncover cutting-edge developments in {topic}
  7. backstory: >
  8. You're a seasoned researcher with a knack for uncovering the latest
  9. developments in {topic}. Known for your ability to find the most relevant
  10. information and present it in a clear and concise manner.
  11. reporting_analyst:
  12. role: >
  13. {topic} Reporting Analyst
  14. goal: >
  15. Create detailed reports based on {topic} data analysis and research findings
  16. backstory: >
  17. You're a meticulous analyst with a keen eye for detail. You're known for
  18. your ability to turn complex data into clear and concise reports, making
  19. it easy for others to understand and act on the information you provide.

要在代码中使用这份 YAML 配置,请创建一个继承自 CrewBase 的 crew 类:

  1. # src/latest_ai_development/crew.py
  2. from crewai import Agent, Crew, Process
  3. from crewai.project import CrewBase, agent, crew
  4. from crewai_tools import SerperDevTool
  5. @CrewBase
  6. class LatestAiDevelopmentCrew():
  7. """LatestAiDevelopment crew"""
  8. agents_config = "config/agents.yaml"
  9. @agent
  10. def researcher(self) -> Agent:
  11. return Agent(
  12. config=self.agents_config['researcher'], # type: ignore[index]
  13. verbose=True,
  14. tools=[SerperDevTool()]
  15. )
  16. @agent
  17. def reporting_analyst(self) -> Agent:
  18. return Agent(
  19. config=self.agents_config['reporting_analyst'], # type: ignore[index]
  20. verbose=True
  21. )
你在 YAML 文件(agents.yaml)中使用的名称,应当与 Python 代码中的方法名保持一致。

直接用代码定义

你也可以通过实例化 Agent 类,直接在代码中创建 Agent。下面是一个展示所有可用参数的完整示例:

  1. from crewai import Agent
  2. from crewai_tools import SerperDevTool
  3. # Create an agent with all available parameters
  4. agent = Agent(
  5. role="Senior Data Scientist",
  6. goal="Analyze and interpret complex datasets to provide actionable insights",
  7. backstory="With over 10 years of experience in data science and machine learning, "
  8. "you excel at finding patterns in complex datasets.",
  9. llm="gpt-4", # Default: OPENAI_MODEL_NAME or "gpt-4"
  10. function_calling_llm=None, # Optional: Separate LLM for tool calling
  11. verbose=False, # Default: False
  12. allow_delegation=False, # Default: False
  13. max_iter=20, # Default: 20 iterations
  14. max_rpm=None, # Optional: Rate limit for API calls
  15. max_execution_time=None, # Optional: Maximum execution time in seconds
  16. max_retry_limit=2, # Default: 2 retries on error
  17. allow_code_execution=False, # Default: False
  18. code_execution_mode="safe", # Default: "safe" (options: "safe", "unsafe")
  19. respect_context_window=True, # Default: True
  20. use_system_prompt=True, # Default: True
  21. multimodal=False, # Default: False
  22. inject_date=False, # Default: False
  23. date_format="%Y-%m-%d", # Default: ISO format
  24. reasoning=False, # Default: False
  25. max_reasoning_attempts=None, # Default: None
  26. tools=[SerperDevTool()], # Optional: List of tools
  27. knowledge_sources=None, # Optional: List of knowledge sources
  28. embedder=None, # Optional: Custom embedder configuration
  29. system_template=None, # Optional: Custom system prompt template
  30. prompt_template=None, # Optional: Custom prompt template
  31. response_template=None, # Optional: Custom response template
  32. step_callback=None, # Optional: Callback function for monitoring
  33. )

下面我们拆解一些常见用例中的关键参数组合:

基础研究 Agent

  1. research_agent = Agent(
  2. role="Research Analyst",
  3. goal="Find and summarize information about specific topics",
  4. backstory="You are an experienced researcher with attention to detail",
  5. tools=[SerperDevTool()],
  6. verbose=True # Enable logging for debugging
  7. )

代码开发 Agent

  1. dev_agent = Agent(
  2. role="Senior Python Developer",
  3. goal="Write and debug Python code",
  4. backstory="Expert Python developer with 10 years of experience",
  5. allow_code_execution=True,
  6. code_execution_mode="safe", # Uses Docker for safety
  7. max_execution_time=300, # 5-minute timeout
  8. max_retry_limit=3 # More retries for complex code tasks
  9. )

长时间运行的分析 Agent

  1. analysis_agent = Agent(
  2. role="Data Analyst",
  3. goal="Perform deep analysis of large datasets",
  4. backstory="Specialized in big data analysis and pattern recognition",
  5. memory=True,
  6. respect_context_window=True,
  7. max_rpm=10, # Limit API calls
  8. function_calling_llm="gpt-4o-mini" # Cheaper model for tool calls
  9. )

自定义模板 Agent

  1. custom_agent = Agent(
  2. role="Customer Service Representative",
  3. goal="Assist customers with their inquiries",
  4. backstory="Experienced in customer support with a focus on satisfaction",
  5. system_template="""<|start_header_id|>system<|end_header_id|>
  6. {{ .System }}<|eot_id|>""",
  7. prompt_template="""<|start_header_id|>user<|end_header_id|>
  8. {{ .Prompt }}<|eot_id|>""",
  9. response_template="""<|start_header_id|>assistant<|end_header_id|>
  10. {{ .Response }}<|eot_id|>""",
  11. )

带日期感知和推理能力的 Agent

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

推理型 Agent

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

多模态 Agent

  1. multimodal_agent = Agent(
  2. role="Visual Content Analyst",
  3. goal="Analyze and process both text and visual content",
  4. backstory="Specialized in multimodal analysis combining text and image understanding",
  5. multimodal=True, # Enable multimodal capabilities
  6. verbose=True
  7. )

参数详解

关键参数

  • rolegoalbackstory 是必填项,它们共同塑造 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":直接执行(仅在可信环境中使用)
这会运行一个默认 Docker 镜像。如果你想自定义 Docker 镜像,请查看 tools 章节中的 Code Interpreter Tool。将代码解释器工具作为 tool 参数加入 Agent。

高级特性

  • multimodal:启用后可处理文本和视觉内容
  • reasoning:启用后,Agent 会先反思并制定计划,再执行任务
  • inject_date:自动将当前日期注入任务描述中

模板

  • system_template:定义 Agent 的核心行为
  • prompt_template:定义输入格式结构
  • response_template:定义 Agent 的响应格式
使用自定义模板时,请确保同时定义 system_templateprompt_templateresponse_template 是可选的,但建议提供,以保持输出格式一致。 使用自定义模板时,你可以在模板中使用 {role}{goal}{backstory} 等变量。执行时这些变量会被自动填充。

Agent 工具

你可以为 Agent 配置多种工具,以增强其能力。CrewAI 支持以下来源的工具:

以下是为 Agent 添加工具的方法:

  1. from crewai import Agent
  2. from crewai_tools import SerperDevTool, WikipediaTools
  3. # Create tools
  4. search_tool = SerperDevTool()
  5. wiki_tool = WikipediaTools()
  6. # Add tools to agent
  7. researcher = Agent(
  8. role="AI Technology Researcher",
  9. goal="Research the latest AI developments",
  10. tools=[search_tool, wiki_tool],
  11. verbose=True
  12. )

Agent 记忆与上下文

Agent 可以保留其交互记忆,并使用前面任务提供的上下文。这对于需要跨多个任务保留信息的复杂工作流尤其有用。

  1. from crewai import Agent
  2. analyst = Agent(
  3. role="Data Analyst",
  4. goal="Analyze and remember complex data patterns",
  5. memory=True, # Enable memory
  6. verbose=True
  7. )
当启用 memory 时,Agent 会在多次交互之间保持上下文,从而提升其处理复杂多步骤任务的能力。

上下文窗口管理

CrewAI 内置了复杂的自动上下文窗口管理机制,用于处理对话内容超出语言模型 Token 限制的情况。这个强大功能由 respect_context_window 参数控制。

上下文窗口管理如何工作

当 Agent 的对话历史过大,超过 LLM 的上下文窗口时,CrewAI 会自动检测这种情况,并可以选择:

  1. 自动总结内容(当 respect_context_window=True 时)
  2. 报错并停止执行(当 respect_context_window=False 时)

自动上下文处理(respect_context_window=True

这是 默认且推荐 的设置,适用于大多数场景。启用后,CrewAI 会:

  1. # Agent with automatic context management (default)
  2. smart_agent = Agent(
  3. role="Research Analyst",
  4. goal="Analyze large documents and datasets",
  5. backstory="Expert at processing extensive information",
  6. respect_context_window=True, # 🔑 Default: auto-handle context limits
  7. verbose=True
  8. )

当上下文超限时会发生:

  • ⚠️ 警告信息"Context length exceeded. Summarizing content to fit the model context window."
  • 🔄 自动摘要:CrewAI 会智能总结对话历史
  • 继续执行:任务会在摘要后的上下文上无缝继续
  • 📝 保留关键信息:核心信息会被保留,同时减少 Token 数量

严格上下文限制(respect_context_window=False

当你需要精确控制,并且宁愿中止执行也不接受信息损失时:

  1. # Agent with strict context limits
  2. strict_agent = Agent(
  3. role="Legal Document Reviewer",
  4. goal="Provide precise legal analysis without information loss",
  5. backstory="Legal expert requiring complete context for accurate analysis",
  6. respect_context_window=False, # ❌ Stop execution on context limit
  7. verbose=True
  8. )

当上下文超限时会发生:

  • 错误信息"Context length exceeded. Consider using smaller text or RAG tools from crewai_tools."
  • 🛑 停止执行:任务会立即中止
  • 🔧 需要人工干预:你必须修改处理方式

如何选择合适的设置

以下场景建议使用 respect_context_window=True(默认):

  • 处理大型文档,可能超出上下文限制
  • 长时间对话,允许一定程度的总结
  • 研究任务,更关注总体上下文而非逐字精确内容
  • 原型开发阶段,希望执行更稳健
  1. # Perfect for document processing
  2. document_processor = Agent(
  3. role="Document Analyst",
  4. goal="Extract insights from large research papers",
  5. backstory="Expert at analyzing extensive documentation",
  6. respect_context_window=True, # Handle large documents gracefully
  7. max_iter=50, # Allow more iterations for complex analysis
  8. verbose=True
  9. )

以下场景建议使用 respect_context_window=False

  • 精度至关重要,不能接受任何信息丢失
  • 法律或医疗任务,要求完整上下文
  • 代码审查,遗漏细节可能引入 Bug
  • 金融分析,准确性要求极高
  1. # Perfect for precision tasks
  2. precision_agent = Agent(
  3. role="Code Security Auditor",
  4. goal="Identify security vulnerabilities in code",
  5. backstory="Security expert requiring complete code context",
  6. respect_context_window=False, # Prefer failure over incomplete analysis
  7. max_retry_limit=1, # Fail fast on context issues
  8. verbose=True
  9. )

处理大数据的替代方案

当处理非常大的数据集时,可以考虑以下策略:

1. 使用 RAG 工具

  1. from crewai_tools import RagTool
  2. # Create RAG tool for large document processing
  3. rag_tool = RagTool()
  4. rag_agent = Agent(
  5. role="Research Assistant",
  6. goal="Query large knowledge bases efficiently",
  7. backstory="Expert at using RAG tools for information retrieval",
  8. tools=[rag_tool], # Use RAG instead of large context windows
  9. respect_context_window=True,
  10. verbose=True
  11. )

2. 使用知识源

  1. # Use knowledge sources instead of large prompts
  2. knowledge_agent = Agent(
  3. role="Knowledge Expert",
  4. goal="Answer questions using curated knowledge",
  5. backstory="Expert at leveraging structured knowledge sources",
  6. knowledge_sources=[your_knowledge_sources], # Pre-processed knowledge
  7. respect_context_window=True,
  8. verbose=True
  9. )

上下文窗口最佳实践

  1. 监控上下文使用情况:启用 verbose=True,观察上下文管理是如何工作的
  2. 为效率而设计:设计任务时尽量减少上下文累积
  3. 选择合适的模型:使用具有足够上下文窗口的 LLM
  4. 两种设置都进行测试:分别尝试 TrueFalse,找到更适合你的场景的方式
  5. 结合 RAG 使用:对于特别大的数据集,使用 RAG,而不是只依赖上下文窗口

排查上下文问题

如果你遇到上下文上限报错:

  1. # Quick fix: Enable automatic handling
  2. agent.respect_context_window = True
  3. # Better solution: Use RAG tools for large data
  4. from crewai_tools import RagTool
  5. agent.tools = [RagTool()]
  6. # Alternative: Break tasks into smaller pieces
  7. # Or use knowledge sources instead of large prompts

如果自动摘要丢失了重要信息:

  1. # Disable auto-summarization and use RAG instead
  2. agent = Agent(
  3. role="Detailed Analyst",
  4. goal="Maintain complete information accuracy",
  5. backstory="Expert requiring full context",
  6. respect_context_window=False, # No summarization
  7. tools=[RagTool()], # Use RAG for large data
  8. verbose=True
  9. )
上下文窗口管理功能会在后台自动运行。你不需要手动调用任何特殊函数 —— 只需将 respect_context_window 设置为你希望的行为方式,剩下的由 CrewAI 自动处理!

使用 kickoff() 进行 Agent 直接交互

你可以不经过 task 或 crew 工作流,而是直接使用 kickoff() 方法与 Agent 交互。当你不需要完整 crew 编排能力时,这是一种更简单的方式。

kickoff() 如何工作

kickoff() 方法允许你直接向 Agent 发送消息并获得回复,类似于直接与 LLM 交互,但同时保留了 Agent 的全部能力(工具、推理等)。

  1. from crewai import Agent
  2. from crewai_tools import SerperDevTool
  3. # Create an agent
  4. researcher = Agent(
  5. role="AI Technology Researcher",
  6. goal="Research the latest AI developments",
  7. tools=[SerperDevTool()],
  8. verbose=True
  9. )
  10. # Use kickoff() to interact directly with the agent
  11. result = researcher.kickoff("What are the latest developments in language models?")
  12. # Access the raw response
  13. print(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 来获取结构化输出:

  1. from pydantic import BaseModel
  2. from typing import List
  3. class ResearchFindings(BaseModel):
  4. main_points: List[str]
  5. key_technologies: List[str]
  6. future_predictions: str
  7. # Get structured output
  8. result = researcher.kickoff(
  9. "Summarize the latest developments in AI for 2025",
  10. response_format=ResearchFindings
  11. )
  12. # Access structured data
  13. print(result.pydantic.main_points)
  14. print(result.pydantic.future_predictions)

多轮消息

你也可以传入一个由消息字典组成的对话历史列表:

  1. messages = [
  2. {"role": "user", "content": "I need information about large language models"},
  3. {"role": "assistant", "content": "I'd be happy to help with that! What specifically would you like to know?"},
  4. {"role": "user", "content": "What are the latest developments in 2025?"}
  5. ]
  6. result = researcher.kickoff(messages)

异步支持

可以通过 kickoff_async() 使用异步版本,参数保持一致:

  1. import asyncio
  2. async def main():
  3. result = await researcher.kickoff_async("What are the latest developments in AI?")
  4. print(result.raw)
  5. 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_itermax_retry_limit

记忆与上下文管理

  • 使用 knowledge_sources 注入领域知识
  • 在使用自定义嵌入模型时配置 embedder
  • 使用自定义模板(system_templateprompt_templateresponse_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)

常见问题排查

  1. 速率限制:如果你遇到了 API 速率限制:

    • 设置合适的 max_rpm
    • 为重复操作启用缓存
    • 考虑批量处理请求
  2. 上下文窗口错误:如果你超过了上下文限制:

    • 启用 respect_context_window
    • 使用更高效的 Prompt
    • 定期清理 Agent 记忆
  3. 代码执行问题:如果代码执行失败:

    • 确认 safe 模式下 Docker 已安装
    • 检查执行权限
    • 查看代码沙箱设置
  4. 记忆问题:如果 Agent 的回复看起来不一致:

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

请记住,只有根据具体用例进行恰当配置时,Agent 才能发挥最大效果。花时间理解你的需求,并相应调整这些参数。