自定义提示词
为什么要自定义提示词?
Section titled “为什么要自定义提示词?”虽然 CrewAI 的默认提示词在许多场景下都能很好地工作,但底层自定义会打开更灵活、更强大的智能体行为空间。你可能会想使用这种更深层控制的原因包括:
- 针对特定 LLM 优化 - 不同模型(如 GPT-4、Claude 或 Llama)更适合与其独特架构匹配的提示词格式。
- 更改语言 - 构建只使用英语之外语言运行的智能体,并准确处理语言细节。
- 面向复杂领域专门化 - 将提示词适配到医疗、金融或法律等高度专业化行业。
- 调整语气和风格 - 让智能体更正式、更随意、更有创意或更具分析性。
- 支持高度定制的用例 - 使用高级提示结构和格式,满足复杂的项目专属需求。
本指南会介绍如何以更底层的方式使用 CrewAI 的提示词,让你可以细粒度控制智能体的思考和交互方式。
理解 CrewAI 的提示词系统
Section titled “理解 CrewAI 的提示词系统”在底层,CrewAI 使用了一个可以广泛自定义的模块化提示词系统:
- 智能体模板 - 决定每个智能体如何处理分配给它的角色。
- 提示切片 - 控制任务、工具使用和输出结构等专门行为。
- 错误处理 - 决定智能体如何响应失败、异常或超时。
- 工具专用提示词 - 定义工具如何被调用或使用的详细说明。
查看 CrewAI 仓库中的原始提示词模板 ,可以了解这些元素是如何组织的。然后你可以按需覆盖或调整它们,以解锁高级行为。
理解默认系统指令
Section titled “理解默认系统指令”当你定义一个包含 role、goal 和 backstory 的智能体时,CrewAI 会自动添加额外的系统指令来控制格式和行为。对于需要完整提示词透明度的生产系统来说,理解这些默认注入非常重要。
CrewAI 会自动注入什么
Section titled “CrewAI 会自动注入什么”根据你的智能体配置,CrewAI 会添加不同的默认指令:
对于没有工具的智能体
Section titled “对于没有工具的智能体”"I MUST use these formats, my job depends on it!"对于有工具的智能体
Section titled “对于有工具的智能体”"IMPORTANT: Use the following format in your response:
Thought: you should always think about what to doAction: the action to take, only one name of [tool_names]Action Input: the input to the action, just a simple JSON object...对于结构化输出(JSON/Pydantic)
Section titled “对于结构化输出(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."查看完整的系统提示词
Section titled “查看完整的系统提示词”要准确查看发送给 LLM 的提示词,可以检查生成后的提示词:
from crewai import Agent, Crew, Taskfrom crewai.utilities.prompts import Prompts
# Create your agentagent = 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 tasktask = Task( description="Analyze the sales data and identify trends", expected_output="A detailed analysis with key insights and trends", agent=agent)
# Create the prompt generatorprompt_generator = Prompts( agent=agent, has_tools=len(agent.tools) > 0, use_system_prompt=agent.use_system_prompt)
# Generate and inspect the actual promptgenerated_prompt = prompt_generator.task_execution()
# Print the complete system prompt that will be sent to the LLMif "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 formattedprint("\n=== TASK CONTEXT ===")print(f"Task Description: {task.description}")print(f"Expected Output: {task.expected_output}")覆盖默认指令
Section titled “覆盖默认指令”你可以通过几种方式获得对提示词的完全控制:
选项 1:自定义模板(推荐)
Section titled “选项 1:自定义模板(推荐)”from crewai import Agent
# Define your own system template without default instructionscustom_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:自定义提示词文件
Section titled “选项 2:自定义提示词文件”创建一个 custom_prompts.json 文件,覆盖特定的提示切片:
{ "slices": { "no_tools": "\n以自然、对话式的方式给出你的最佳答案。", "tools": "\n你可以使用以下工具:{tools}\n\n在有帮助时使用它们,但请自然地作答。", "formatted_task_instructions": "请将你的回复格式化为:{output_format}" }}然后在 crew 中使用它:
crew = Crew( agents=[agent], tasks=[task], prompt_file="custom_prompts.json", verbose=True)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 模型禁用系统提示词
Section titled “选项 3:为 o1 模型禁用系统提示词”agent = Agent( role="Analyst", goal="Analyze data", backstory="Expert analyst", use_system_prompt=False # Disables system prompt separation)使用 Observability 工具进行调试
Section titled “使用 Observability 工具进行调试”为了提升生产环境的透明度,可以集成 observability 平台来监控所有提示词和 LLM 交互。这样你就能准确看到发送给 LLM 的提示词内容,包括默认指令。
请参阅我们的 Observability 文档 以获取与 Langfuse、MLflow、Weights & Biases 以及自定义日志方案等平台的详细集成指南。
生产最佳实践
Section titled “生产最佳实践”- 在部署到生产前始终检查生成的提示词
- 在需要完全控制提示内容时使用自定义模板
- 集成 observability 工具进行持续的提示词监控(参见 Observability 文档)
- 使用不同 LLM 进行测试,因为默认指令在不同模型上的表现可能不同
- 记录你的提示词自定义,以便团队透明协作
管理提示词文件的最佳实践
Section titled “管理提示词文件的最佳实践”进行底层提示词自定义时,请遵循以下建议,以保持组织清晰且易维护:
- 保持文件分离 - 将自定义提示词存放在主代码库之外的独立 JSON 文件中。
- 版本控制 - 在仓库中跟踪变更,确保对提示调整有清晰的历史记录。
- 按模型或语言组织 - 使用类似
prompts_llama.json或prompts_es.json的命名方式,快速识别特定配置。 - 记录变更 - 提供注释或维护 README,说明自定义的目的和范围。
- 尽量少改动 - 只覆盖真正需要调整的提示切片,保留其他内容的默认功能。
最简单的提示词自定义方式
Section titled “最简单的提示词自定义方式”一个直接的方法是创建一个 JSON 文件来覆盖你想修改的提示词,然后让你的 Crew 指向该文件:
- 创建一个包含更新后提示切片的 JSON 文件。
from crewai import Agent, Crew, Task
researcher = Agent( role="Researcher", goal="Research topics thoroughly", backstory="You are a careful and thorough researcher.")
research_task = Task( description="Research the best practices for prompt engineering", expected_output="A clear summary of best practices", agent=researcher)
crew = Crew( agents=[researcher], tasks=[research_task], prompt_file="path/to/custom_prompts.json", verbose=True)
# Run the crewresult = crew.kickoff()只需做这几处修改,你就能对智能体如何沟通和解决任务获得底层控制权。
针对特定模型进行优化
Section titled “针对特定模型进行优化”不同模型对提示词结构的偏好不同。做更深层的调整,可以通过贴合模型特性来显著提升性能。
示例:Llama 3.3 提示模板
Section titled “示例:Llama 3.3 提示模板”例如,在使用 Meta 的 Llama 3.3 时,更深层的自定义可以参考如下推荐结构: https://www.llama.com/docs/model-cards-and-prompt-formats/llama3_1/#prompt-template
下面的示例展示了如何在代码中微调 Agent 以利用 Llama 3.3:
from crewai import Agent, Crew, Task, Processfrom crewai_tools import DirectoryReadTool, FileReadTool
# Define templates for system, user (prompt), and assistant (response) messagessystem_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 layoutsprincipal_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 taskengineering_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 taskllama_crew = Crew( agents=[principal_engineer], tasks=[engineering_task], process=Process.sequential, verbose=True)
# Execute the crewresult = llama_crew.kickoff()print(result.raw)通过这种更深层的配置,你可以在不依赖单独 JSON 文件的情况下,对基于 Llama 的工作流进行全面的底层控制。
CrewAI 的底层提示词自定义为极其定制化、复杂的用例打开了大门。通过组织良好的提示词文件(或直接内联模板),你可以适配不同模型、语言和专业领域。这种灵活性确保你能够精确塑造所需的 AI 行为,同时在不覆盖默认值时仍然依赖 CrewAI 提供的可靠默认设置。