Skip to content
CrewAI 文档版本 跟随上游 源快照 3399143d 更新于 2026-10-18

自定义提示词

深入了解 CrewAI 的低层提示词自定义,为不同模型和语言实现高度自定义的复杂用例。

为什么要自定义提示词?

尽管 CrewAI 的默认提示词在许多场景中运行良好,但低层自定义为实现更灵活、更强大的智能体行为打开了大门。以下是你可能希望利用这种更深层控制的原因:

  1. 针对特定 LLM 进行优化 – 不同模型(如 GPT-4、Claude 或 Llama)在为其独特架构量身定制的提示词格式下表现更佳。
  2. 更改语言 – 构建仅使用英语以外语言运行的智能体,精准处理细微差别。
  3. 针对复杂领域进行专门化 – 为医疗、金融或法律等高度专业化的行业调整提示词。
  4. 调整语气和风格 – 让智能体更正式、随意、富有创意或更具分析性。
  5. 支持高度自定义的用例 – 利用高级提示词结构和格式,满足复杂的项目特定需求。

本指南探讨如何在更底层利用 CrewAI 的提示词,让你对智能体的思考和交互方式进行细粒度控制。

了解 CrewAI 的提示词系统

在底层,CrewAI 采用模块化提示词系统,你可以对其进行广泛自定义:

  • 智能体模板 – 管理每个智能体履行其分配角色的方式。
  • 提示词片段 – 控制任务、工具使用和输出结构等专门行为。
  • 错误处理 – 指导智能体如何响应失败、异常或超时。
  • 工具特定提示词 – 定义有关如何调用或使用工具的详细说明。

查看 CrewAI 仓库中的原始提示词模板,了解这些元素是如何组织的。然后,你可以根据需要覆盖或调整它们,以解锁高级行为。

了解默认系统指令

WARNING

生产环境透明度问题:CrewAI 会自动向你的提示词中注入你可能并未察觉的默认指令。本节说明底层发生了什么,以及如何获得完全控制。

当你使用 role、goal 和 backstory 定义智能体时,CrewAI 会自动添加额外的系统指令来控制格式和行为。对于需要完全提示词透明度的生产系统而言,理解这些默认注入内容至关重要。

CrewAI 自动注入的内容

根据你的智能体配置,CrewAI 会添加不同的默认指令:

对于不使用工具的智能体

text
"I MUST use these formats, my job depends on it!"

对于使用工具的智能体

text
"IMPORTANT: Use the following format in your response:

Thought: you should always think about what to do
Action: the action to take, only one name of [tool_names]
Action Input: the input to the action, just a simple JSON object...

对于结构化输出(JSON/Pydantic)

text
"Ensure your final answer contains only the content in the following format: {output_format}
Ensure the final output does not include any code block markers like ```json or ```python."

查看完整的系统提示词

要确切查看发送给 LLM 的提示词,你可以检查生成的提示词:

python
from crewai import Agent, Crew, Task
from crewai.utilities.prompts import Prompts

# Create your agent
agent = Agent(
    role="Data Analyst",
    goal="Analyze data and provide insights",
    backstory="You are an expert data analyst with 10 years of experience.",
    verbose=True
)

# Create a sample task
task = Task(
    description="Analyze the sales data and identify trends",
    expected_output="A detailed analysis with key insights and trends",
    agent=agent
)

# Create the prompt generator
prompt_generator = Prompts(
    agent=agent,
    has_tools=len(agent.tools) > 0,
    use_system_prompt=agent.use_system_prompt
)

# Generate and inspect the actual prompt
generated_prompt = prompt_generator.task_execution()

# Print the complete system prompt that will be sent to the LLM
if "system" in generated_prompt:
    print("=== SYSTEM PROMPT ===")
    print(generated_prompt["system"])
    print("\n=== USER PROMPT ===")
    print(generated_prompt["user"])
else:
    print("=== COMPLETE PROMPT ===")
    print(generated_prompt["prompt"])

# You can also see how the task description gets formatted
print("\n=== TASK CONTEXT ===")
print(f"Task Description: {task.description}")
print(f"Expected Output: {task.expected_output}")

覆盖默认指令

你可以通过几种方式获得对提示词的完全控制:

选项 1:自定义模板(推荐)

python
from crewai import Agent

# Define your own system template without default instructions
custom_system_template = """You are {role}. {backstory}
Your goal is: {goal}

Respond naturally and conversationally. Focus on providing helpful, accurate information."""

custom_prompt_template = """Task: {input}

Please complete this task thoughtfully."""

agent = Agent(
    role="Research Assistant",
    goal="Help users find accurate information",
    backstory="You are a helpful research assistant.",
    system_template=custom_system_template,
    prompt_template=custom_prompt_template,
    use_system_prompt=True  # Use separate system/user messages
)

选项 2:自定义提示词文件

创建 custom_prompts.json 文件以覆盖特定提示词片段:

json
{
  "slices": {
    "no_tools": "\nProvide your best answer in a natural, conversational way.",
    "tools": "\nYou have access to these tools: {tools}\n\nUse them when helpful, but respond naturally.",
    "formatted_task_instructions": "Format your response as: {output_format}"
  }
}

然后在你的团队中使用它:

python
crew = Crew(
    agents=[agent],
    tasks=[task],
    prompt_file="custom_prompts.json",
    verbose=True
)

NOTE

agent.i18n 仅为向后兼容而保留,并已弃用。若要在运行时自定义提示词,请将 prompt_file 传递给 Crew。若要以编程方式访问提示词片段,请直接使用 i18n 工具:

python
from crewai.utilities.i18n import get_i18n

i18n = get_i18n("custom_prompts.json")
format_slice = i18n.slice("format")
tool_prompt = i18n.tools("ask_question")

选项 3:为 o1 模型禁用系统提示词

python
agent = Agent(
    role="Analyst",
    goal="Analyze data",
    backstory="Expert analyst",
    use_system_prompt=False  # Disables system prompt separation
)

使用可观测性工具进行调试

为实现生产环境透明度,可与可观测性平台集成,以监控所有提示词和 LLM 交互。这样你可以确切查看发送给 LLM 的提示词(包括默认指令)。

查看我们的 可观测性文档,了解与 Langfuse、MLflow、Weights & Biases 以及自定义日志记录解决方案等各种平台集成的详细指南。

生产环境最佳实践

  1. 始终检查生成的提示词,然后再部署到生产环境
  2. 在需要完全控制提示词内容时使用自定义模板
  3. 集成可观测性工具以持续监控提示词(参见 可观测性文档)
  4. 使用不同的 LLM 进行测试,因为默认指令在不同模型中的效果可能不同
  5. 记录你的提示词自定义内容,以实现团队透明度

TIP

默认指令的存在是为了确保一致的智能体行为,但它们可能会干扰特定领域的需求。使用上述自定义选项,以在生产系统中保持对智能体行为的完全控制。

管理提示词文件的最佳实践

进行低层提示词自定义时,请遵循以下准则,以保持条理清晰且易于维护:

  1. 保持文件分离 – 将自定义提示词存储在主要代码库之外的专用 JSON 文件中。
  2. 版本控制 – 在仓库中跟踪更改,确保清晰记录提示词随时间的调整。
  3. 按模型或语言组织 – 使用 prompts_llama.json 或 prompts_es.json 等命名方案,快速识别专门配置。
  4. 记录更改 – 提供注释或维护 README,详细说明自定义的目的和范围。
  5. 尽量减少改动 – 仅覆盖你确实需要调整的特定片段,其余部分保持默认功能不变。

自定义提示词的最简单方法

一种直接的方法是,为想要覆盖的提示词创建一个 JSON 文件,然后让 Crew 指向该文件:

  1. 创建一个包含更新后提示词片段的 JSON 文件。
  2. 通过 Crew 中的 prompt_file 参数引用该文件。

然后 CrewAI 会将你的自定义内容与默认内容合并,因此你无需重新定义每个提示词。具体如下:

对于需要直接读取提示词片段的代码,请使用 crewai.utilities.i18n.get_i18n() 并传入相同的提示词文件,而不是读取 agent.i18n。

示例:基本提示词自定义

创建一个 custom_prompts.json 文件,包含你想要修改的提示词。确保列出它应包含的所有顶层提示词,而不仅仅是你的更改:

json
{
  "slices": {
    "format": "When responding, follow this structure:\n\nTHOUGHTS: Your step-by-step thinking\nACTION: Any tool you're using\nRESULT: Your final answer or conclusion"
  }
}

然后像这样集成它:

python
from crewai import Agent, Crew, Task, Process

# Create agents and tasks as normal
researcher = Agent(
    role="Research Specialist",
    goal="Find information on quantum computing",
    backstory="You are a quantum physics expert",
    verbose=True
)

research_task = Task(
    description="Research quantum computing applications",
    expected_output="A summary of practical applications",
    agent=researcher
)

# Create a crew with your custom prompt file
crew = Crew(
    agents=[researcher],
    tasks=[research_task],
    prompt_file="path/to/custom_prompts.json",
    verbose=True
)

# Run the crew
result = crew.kickoff()

通过这少量编辑,你就能对智能体的沟通和任务解决方式获得低层控制。

针对特定模型进行优化

不同模型在结构不同的提示词下表现更佳。通过让提示词与模型的细微特性保持一致,进行更深入的调整可以显著提升性能。

示例:Llama 3.3 提示词模板

例如,在处理 Meta 的 Llama 3.3 时,更深层自定义可以体现以下地址所述的建议结构: https://www.llama.com/docs/model-cards-and-prompt-formats/llama3_1/#prompt-template

以下示例展示了如何在代码中微调智能体以利用 Llama 3.3:

python
from crewai import Agent, Crew, Task, Process
from crewai_tools import DirectoryReadTool, FileReadTool

# Define templates for system, user (prompt), and assistant (response) messages
system_template = """<|begin_of_text|><|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|>"""

# Create an Agent using Llama-specific layouts
principal_engineer = Agent(
    role="Principal Engineer",
    goal="Oversee AI architecture and make high-level decisions",
    backstory="You are the lead engineer responsible for critical AI systems",
    verbose=True,
    llm="groq/llama-3.3-70b-versatile",  # Using the Llama 3 model
    system_template=system_template,
    prompt_template=prompt_template,
    response_template=response_template,
    tools=[DirectoryReadTool(), FileReadTool()]
)

# Define a sample task
engineering_task = Task(
    description="Review AI implementation files for potential improvements",
    expected_output="A summary of key findings and recommendations",
    agent=principal_engineer
)

# Create a Crew for the task
llama_crew = Crew(
    agents=[principal_engineer],
    tasks=[engineering_task],
    process=Process.sequential,
    verbose=True
)

# Execute the crew
result = llama_crew.kickoff()
print(result.raw)

通过这种更深层的配置,你可以对基于 Llama 的工作流实现全面的低层控制,而无需单独的 JSON 文件。

结论

CrewAI 中的低层提示词自定义为实现高度自定义的复杂用例打开了大门。通过建立组织良好的提示词文件(或直接使用内联模板),你可以适配各种模型、语言和专门领域。这种灵活性确保你能精确打造所需的 AI 行为,同时你也会知道,在未覆盖默认内容时,CrewAI 仍会提供可靠的默认值。

TIP

你现在已经掌握了在 CrewAI 中进行高级提示词自定义的基础。无论你是要适配特定模型的结构,还是特定领域的约束,这种低层方法都能让你以高度专门化的方式塑造智能体交互。

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。