跳转到主要内容

为什么要自定义提示词?

尽管 CrewAI 的默认提示词在许多场景中都能很好地工作,但低级定制为代理行为带来了显著的灵活性和强大功能。以下是您可能希望利用这种更深层次控制的原因:
  1. 针对特定 LLM 进行优化 – 不同的模型(如 GPT-4、Claude 或 Llama)通过针对其独特架构量身定制的提示词格式而蓬勃发展。
  2. 更改语言 – 构建专门以英语以外的语言运行的代理,精确处理细微差别。
  3. 针对复杂领域进行专业化 – 为医疗保健、金融或法律等高度专业化的行业调整提示词。
  4. 调整语气和风格 – 使代理更正式、更随意、更有创意或更具分析性。
  5. 支持超自定义用例 – 利用高级提示词结构和格式来满足复杂的、项目特定的要求。
本指南探讨如何从较低级别利用 CrewAI 的提示词,让您对代理的思考和交互方式进行细粒度控制。

了解 CrewAI 的提示词系统

CrewAI 在底层采用模块化提示词系统,您可以对其进行广泛定制:
  • 代理模板 – 管理每个代理对其分配角色的处理方式。
  • 提示词切片 – 控制任务、工具使用和输出结构等专门行为。
  • 错误处理 – 指导代理如何响应故障、异常或超时。
  • 工具特定提示词 – 定义有关如何调用或利用工具的详细说明。
查看CrewAI 存储库中的原始提示词模板,了解这些元素的组织方式。从那里,您可以根据需要覆盖或调整它们以解锁高级行为。

了解默认系统指令

生产透明度问题:CrewAI 会自动将您可能不知道的默认指令注入到您的提示词中。本节解释了底层发生了什么以及如何获得完全控制。
当您使用 rolegoalbackstory 定义代理时,CrewAI 会自动添加额外的系统指令,这些指令控制格式和行为。了解这些默认注入对于需要完全提示词透明度的生产系统至关重要。

CrewAI 自动注入的内容

根据您的代理配置,CrewAI 会添加不同的默认指令:

对于没有工具的代理

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

对于有工具的代理

"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)

"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 的提示词,您可以检查生成的提示词:
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}")

覆盖默认指令

您有几个选项可以完全控制提示词:
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 文件来覆盖特定的提示词切片
{
  "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}"
  }
}
然后在您的 Crew 中使用它
crew = Crew(
    agents=[agent],
    tasks=[task],
    prompt_file="custom_prompts.json",
    verbose=True
)

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

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. 记录您的提示词定制以实现团队透明度
默认指令旨在确保代理行为一致,但它们可能会干扰特定领域的要求。使用上述定制选项来维护对生产系统中代理行为的完全控制。

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

在进行低级提示词定制时,请遵循以下准则以保持组织性和可维护性:
  1. 保持文件分离 – 将您的自定义提示词存储在主代码库之外的专用 JSON 文件中。
  2. 版本控制 – 在您的存储库中跟踪更改,确保提示词调整的清晰文档。
  3. 按模型或语言组织 – 使用 prompts_llama.jsonprompts_es.json 等命名方案快速识别专门配置。
  4. 记录更改 – 提供注释或维护 README,详细说明您的定制目的和范围。
  5. 最小化修改 – 只覆盖您真正需要调整的特定切片,保留所有其他默认功能。

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

一个简单的方法是为要覆盖的提示词创建一个 JSON 文件,然后将您的 Crew 指向该文件。
  1. 创建一个包含更新的提示词切片的 JSON 文件。
  2. 通过 Crew 中的 prompt_file 参数引用该文件。
CrewAI 然后将您的定制与默认值合并,因此您无需重新定义每个提示词。以下是操作方法:

示例:基本提示词定制

创建一个 custom_prompts.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"
  }
}
然后像这样集成它:
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:
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 在您不覆盖它们时仍提供可靠的默认值。
您现在已经掌握了 CrewAI 中高级提示词定制的基础。无论您是适应模型特定结构还是领域特定限制,这种低级方法都允许您以高度专业化的方式塑造代理交互。