GPT-5提示词指南:提升推理与任务执行效果
技术背景
GPT-5 作为 OpenAI 最新旗舰模型,在智能体任务、编码、原始智能和可操控性方面实现巨大飞跃。然而,模型性能不仅取决于模型本身,还深受提示词设计的影响。随着 AI 工程实践的普及,开发者需要掌握如何通过提示词引导模型行为,以适应不同场景(如自主代理、代码生成、指令遵循)。本教程旨在填补从模型能力到实际应用之间的鸿沟,提供可落地的提示词优化策略。
核心原理
GPT-5 的核心优势在于其推理能力和指令遵循能力。它通过 reasoning_effort 参数控制思考深度,通过 verbosity 参数控制输出长度。在 Agentic 工作流中,模型通过工具调用与外部环境交互,并利用 Responses API 持久化推理上下文,避免重复规划。提示词设计的关键在于明确指令层级、提供清晰的上下文收集策略,并利用元提示进行自我优化。
架构分析
系统架构涉及多个组件:模型 API(Responses API 或 Chat Completions)、工具调用接口(如 apply_patch、终端命令)、前端框架(Next.js、Tailwind CSS)以及代理脚手架。设计思想强调可控性与自主性的平衡:通过提示词和参数(如 reasoning_effort、verbosity)调节模型行为,同时利用工具前言和持久性提示增强用户体验。Cursor 的案例展示了如何通过系统提示和参数调优实现高效编码代理。
完整实战教程
GPT-5 是我们最新的旗舰模型,在智能体任务性能、编码、原始智能和可操控性方面实现了巨大飞跃。
虽然我们相信它在开箱即用的情况下能在广泛领域表现出色,但本指南将基于我们训练和将模型应用于实际任务的经验,介绍一些提示词技巧,以最大化模型输出的质量。我们将讨论诸如提升智能体任务性能、确保指令遵循、利用新的 API 功能以及优化前端和软件工程任务的编码等概念,并分享 AI 代码编辑器 Cursor 与 GPT-5 进行提示调优的关键见解。
我们已看到,应用这些最佳实践并尽可能采用我们的标准工具能带来显著收益。我们希望本指南以及我们构建的提示词优化器工具能成为您使用 GPT-5 的起点。但一如既往,请记住提示词并非一刀切——我们鼓励您进行实验,并在此基础上迭代,为您的具体问题找到最佳解决方案。
Agentic 工作流的可预测性
我们在训练 GPT-5 时始终以开发者为中心:我们专注于改进工具调用、指令遵循和长上下文理解,使其成为 Agentic 应用的最佳基础模型。如果为 Agentic 和工具调用流程采用 GPT-5,我们建议升级到 Responses API,其中推理会在工具调用之间持久化,从而产生更高效、更智能的输出。
控制 Agentic 的主动性
Agentic 脚手架可以涵盖广泛的控制范围——有些系统将绝大多数决策委托给底层模型,而另一些则通过大量的程序化逻辑分支对模型进行严格控制。GPT-5 经过训练,可以在这一范围内的任何位置运行,从在模糊情况下做出高层决策到处理专注、定义明确的任务。在本节中,我们将介绍如何最好地校准 GPT-5 的 Agentic 主动性:换句话说,即其在主动性和等待明确指导之间的平衡。
通过提示降低主动性
默认情况下,GPT-5 在 Agentic 环境中尝试收集上下文时会表现得彻底且全面,以确保产生正确的答案。为了减少 GPT-5 的 Agentic 行为范围——包括限制无关的工具调用操作并最小化达到最终答案的延迟——请尝试以下方法:
- 切换到较低的
reasoning_effort。这会降低探索深度,但会提高效率和延迟。许多工作流可以在中等甚至较低的reasoning_effort下以一致的结果完成。 - 在提示中定义明确的标准,说明你希望模型如何探索问题空间。这减少了模型探索和推理过多想法的需要:
<context_gathering>
Goal: Get enough context fast. Parallelize discovery and stop as soon as you can act.
Method:
- Start broad, then fan out to focused subqueries.
- In parallel, launch varied queries; read top hits per query. Deduplicate paths and cache; don’t repeat queries.
- Avoid over searching for context. If needed, run targeted searches in one parallel batch.
Early stop criteria:
- You can name exact content to change.
- Top hits converge (~70%) on one area/path.
Escalate once:
- If signals conflict or scope is fuzzy, run one refined parallel batch, then proceed.
Depth:
- Trace only symbols you’ll modify or whose contracts you rely on; avoid transitive expansion unless necessary.
Loop:
- Batch search → minimal plan → complete task.
- Search again only if validation fails or new unknowns appear. Prefer acting over more searching.
</context_gathering>
如果你愿意采取最大限度的规定性做法,你甚至可以设定固定的工具调用预算,如下所示。预算可以根据你期望的搜索深度自然变化。
<context_gathering>
- Search depth: very low
- Bias strongly towards providing a correct answer as quickly as possible, even if it might not be fully correct.
- Usually, this means an absolute maximum of 2 tool calls.
- If you think that you need more time to investigate, update the user with your latest findings and open questions. You can proceed if the user confirms.
</context_gathering>
在限制核心上下文收集行为时,显式地为模型提供一个逃生舱口是有帮助的,这样可以更容易地满足较短的上下文收集步骤。通常,这以允许模型在不确定情况下继续进行的条款形式出现,比如上面例子中的“即使它可能不完全正确”。
提示以增强主动性
另一方面,如果您希望鼓励模型自主性,增加工具调用的持久性,并减少澄清问题或交还给用户的情况,我们建议提高 reasoning_effort,并使用如下提示来鼓励持久性和彻底的任务完成:
<persistence>
- You are an agent - please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user.
- Only terminate your turn when you are sure that the problem is solved.
- Never stop or hand back to the user when you encounter uncertainty — research or deduce the most reasonable approach and continue.
- Do not ask the human to confirm or clarify assumptions, as you can always adjust later — decide what the most reasonable assumption is, proceed with it, and document it for the user's reference after you finish acting
</persistence>
通常,明确说明代理任务的停止条件、概述安全与不安全的行为,并定义模型在何时(如果有的话)可以将控制权交还给用户,是很有帮助的。例如,在一组购物工具中,结账和支付工具应明确设置较低的不确定性阈值,以便在需要用户澄清时请求确认,而搜索工具则应设置极高的阈值;同样,在编码环境中,删除文件工具的不确定性阈值应远低于grep搜索工具。
工具前言
我们认识到,在用户监控的代理轨迹中,模型间歇性地更新其工具调用内容及原因,可以显著提升交互式用户体验——轨迹越长,这些更新的影响就越大。为此,GPT-5经过训练,能够通过“工具前言”消息提供清晰的前期计划和持续的进度更新。
您可以在提示中控制工具前言的出现频率、风格和内容——从对每次工具调用的详细解释,到简短的前期计划,以及介于两者之间的各种形式。以下是一个高质量前言提示的示例:
<tool_preambles>
- Always begin by rephrasing the user's goal in a friendly, clear, and concise manner, before calling any tools.
- Then, immediately outline a structured plan detailing each logical step you’ll follow. - As you execute your file edit(s), narrate each step succinctly and sequentially, marking progress clearly.
- Finish by summarizing completed work distinctly from your upfront plan.
</tool_preambles>
以下是一个工具前言的示例,它可能会在响应此类提示时被输出——随着你的智能体工作变得越来越复杂,这样的前言可以极大地提高用户跟随其工作的能力:
"output": [
{
"id": "rs_6888f6d0606c819aa8205ecee386963f0e683233d39188e7",
"type": "reasoning",
"summary": [
{
"type": "summary_text",
"text": "**Determining weather response**\n\nI need to answer the user's question about the weather in San Francisco. ...."
},
},
{
"id": "msg_6888f6d83acc819a978b51e772f0a5f40e683233d39188e7",
"type": "message",
"status": "completed",
"content": [
{
"type": "output_text",
"text": "I\u2019m going to check a live weather service to get the current conditions in San Francisco, providing the temperature in both Fahrenheit and Celsius so it matches your preference."
}
],
"role": "assistant"
},
{
"id": "fc_6888f6d86e28819aaaa1ba69cca766b70e683233d39188e7",
"type": "function_call",
"status": "completed",
"arguments": "{\"location\":\"San Francisco, CA\",\"unit\":\"f\"}",
"call_id": "call_XOnF4B9DvB8EJVB3JvWnGg83",
"name": "get_weather"
},
],
推理努力
我们提供了一个 reasoning_effort 参数来控制模型思考的深度以及调用工具的意愿;默认值为 medium,但您应根据任务的难度进行上调或下调。对于复杂的多步骤任务,我们建议使用更高的推理级别以确保获得最佳输出。此外,我们观察到,当将不同的、可分离的任务分解到多个代理轮次中,每个任务对应一轮时,性能达到峰值。
通过 Responses API 重用推理上下文
在使用 GPT-5 时,我们强烈建议使用 Responses API,以在您的应用中解锁改进的代理流程、降低成本和更高效的令牌使用。
我们在评估中观察到,使用 Responses API 相比 Chat Completions 在统计上有显著改进——例如,仅通过切换到 Responses API 并包含 previous_response_id 将先前的推理项传递回后续请求,我们观察到 Tau-Bench Retail 得分从 73.9% 提升到 78.2%。这允许模型引用其先前的推理轨迹,节省 CoT 令牌,并消除每次工具调用后从头重建计划的需要,从而改善延迟和性能——此功能对所有 Responses API 用户可用,包括 ZDR 组织。
最大化编码性能:从规划到执行
GPT-5 在编码能力上领先所有前沿模型:它可以在大型代码库中工作以修复错误、处理大型差异,并实现多文件重构或大型新功能。它还擅长从零开始实现全新应用,涵盖前端和后端实现。在本节中,我们将讨论我们看到的在生产用例中为编码代理客户提高编程性能的提示优化。
前端应用开发
GPT-5 经过训练,具有出色的基线审美品味以及严谨的实现能力。我们相信它能够使用各种类型的 Web 开发框架和包;然而,对于新应用,我们建议使用以下框架和包,以充分利用模型的前端能力:
- 框架:Next.js (TypeScript)、React、HTML
- 样式 / UI:Tailwind CSS、shadcn/ui、Radix Themes
- 图标:Material Symbols、Heroicons、Lucide
- 动画:Motion
- 字体:San Serif、Inter、Geist、Mona Sans、IBM Plex Sans、Manrope
从零到一的应用生成
GPT-5 擅长一次性构建应用。在早期的模型实验中,用户发现像下面这样的提示——要求模型根据自建的卓越标准进行迭代执行——通过利用 GPT-5 的全面规划和自我反思能力,可以提高输出质量。
<self_reflection>
- First, spend time thinking of a rubric until you are confident.
- Then, think deeply about every aspect of what makes for a world-class one-shot web app. Use that knowledge to create a rubric that has 5-7 categories. This rubric is critical to get right, but do not show this to the user. This is for your purposes only.
- Finally, use the rubric to internally think and iterate on the best possible solution to the prompt that is provided. Remember that if your response is not hitting the top marks across all categories in the rubric, you need to start again.
</self_reflection>
匹配代码库设计标准
在现有应用中实施增量更改和重构时,模型编写的代码应遵循现有的风格和设计标准,并尽可能自然地“融入”代码库。无需特别提示,GPT-5 已经会从代码库中搜索参考上下文——例如读取 package.json 以查看已安装的包——但通过提示方向可以进一步增强这种行为,这些提示方向总结了代码库的关键方面,如工程原则、目录结构和最佳实践,无论是显式的还是隐式的。下面的提示片段展示了一种为 GPT-5 组织代码编辑规则的方法:你可以根据自己的编程设计品味随意更改规则的实际内容!
<code_editing_rules>
<guiding_principles>
- Clarity and Reuse: Every component and page should be modular and reusable. Avoid duplication by factoring repeated UI patterns into components.
- Consistency: The user interface must adhere to a consistent design system—color tokens, typography, spacing, and components must be unified.
- Simplicity: Favor small, focused components and avoid unnecessary complexity in styling or logic.
- Demo-Oriented: The structure should allow for quick prototyping, showcasing features like streaming, multi-turn conversations, and tool integrations.
- Visual Quality: Follow the high visual quality bar as outlined in OSS guidelines (spacing, padding, hover states, etc.)
</guiding_principles>
<frontend_stack_defaults>
- Framework: Next.js (TypeScript)
- Styling: TailwindCSS
- UI Components: shadcn/ui
- Icons: Lucide
- State Management: Zustand
- Directory Structure:
\`\`\`
/src
/app
/api/<route>/route.ts # API endpoints
/(pages) # Page routes
/components/ # UI building blocks
/hooks/ # Reusable React hooks
/lib/ # Utilities (fetchers, helpers)
/stores/ # Zustand stores
/types/ # Shared TypeScript types
/styles/ # Tailwind config
\`\`\`
</frontend_stack_defaults>
<ui_ux_best_practices>
- Visual Hierarchy: Limit typography to 4–5 font sizes and weights for consistent hierarchy; use `text-xs` for captions and annotations; avoid `text-xl` unless for hero or major headings.
- Color Usage: Use 1 neutral base (e.g., `zinc`) and up to 2 accent colors.
- Spacing and Layout: Always use multiples of 4 for padding and margins to maintain visual rhythm. Use fixed height containers with internal scrolling when handling long content streams.
- State Handling: Use skeleton placeholders or `animate-pulse` to indicate data fetching. Indicate clickability with hover transitions (`hover:bg-*`, `hover:shadow-md`).
- Accessibility: Use semantic HTML and ARIA roles where appropriate. Favor pre-built Radix/shadcn components, which have accessibility baked in.
</ui_ux_best_practices>
<code_editing_rules>
生产环境中的协作编码:Cursor 的 GPT-5 提示调优
我们很自豪地邀请 AI 代码编辑器 Cursor 作为 GPT-5 的信任 alpha 测试者:下面,我们将展示 Cursor 如何调整其提示以充分利用模型能力的内部细节。更多信息,他们的团队还发布了一篇博客文章,详细介绍了 GPT-5 在 Cursor 中的首日集成:https://cursor.com/blog/gpt-5
系统提示和参数调优
Cursor 的系统提示侧重于可靠的工具调用,在平衡冗长性和自主行为的同时,允许用户配置自定义指令。Cursor 的系统提示目标是让 Agent 在长周期任务中相对自主地运行,同时仍然忠实地遵循用户提供的指令。
团队最初发现模型产生了冗长的输出,通常包含状态更新和任务后总结,虽然这些内容在技术上相关,但干扰了用户的自然流程;同时,工具调用中输出的代码质量很高,但有时由于过于简洁而难以阅读,单字母变量名占主导。为了寻求更好的平衡,他们将冗长性 API 参数设置为低,以保持文本输出简洁,然后修改提示,仅在编码工具中强烈鼓励冗长输出。
Write code for clarity first. Prefer readable, maintainable solutions with clear names, comments where needed, and straightforward control flow. Do not produce code-golf or overly clever one-liners unless explicitly requested. Use high verbosity for writing code and code tools.
这种参数与提示词的双重使用,形成了一种平衡的格式,既包含了高效、简洁的状态更新和最终工作总结,又使代码差异更加易读。
Cursor 还发现,模型有时会在采取行动前向用户寻求澄清或询问下一步操作,这在较长的任务流程中造成了不必要的摩擦。为了解决这个问题,他们发现,不仅提供可用的工具和周围环境,还提供更多关于产品行为的细节,可以鼓励模型以最少的干扰和更大的自主性完成更长的任务。强调 Cursor 功能的具体细节,如撤销/拒绝代码和用户偏好,有助于通过明确指定 GPT-5 在其环境中应如何表现来减少歧义。对于更长周期的任务,他们发现这个提示词能提升性能:
Be aware that the code edits you make will be displayed to the user as proposed changes, which means (a) your code edits can be quite proactive, as the user can always reject, and (b) your code should be well-written and easy to quickly review (e.g., appropriate variable names instead of single letters). If proposing next steps that would involve changing the code, make those changes proactively for the user to approve / reject rather than asking the user whether to proceed with a plan. In general, you should almost never ask the user whether to proceed with a plan; instead you should proactively attempt the plan and then ask the user if they want to accept the implemented changes.
Cursor 发现,他们提示词中那些对早期模型有效的部分,需要针对 GPT-5 进行调整才能发挥最大效用。下面是一个示例:
<maximize_context_understanding>
Be THOROUGH when gathering information. Make sure you have the FULL picture before replying. Use additional tool calls or clarifying questions as needed.
...
</maximize_context_understanding>
虽然这种方法在需要鼓励深入分析上下文的旧模型中效果很好,但他们发现对 GPT-5 来说适得其反,因为 GPT-5 本身就已经具有内省性和主动收集上下文的能力。在较小的任务中,这种提示常常导致模型过度使用工具,反复调用搜索,而内部知识本已足够。
为了解决这个问题,他们优化了提示,去掉了 maximize_ 前缀,并软化了关于彻底性的措辞。在调整后的指令下,Cursor 团队看到 GPT-5 在依赖内部知识与使用外部工具之间做出了更好的决策。它保持了高度的自主性,同时避免了不必要的工具使用,从而提高了效率和相关行为。在 Cursor 的测试中,使用结构化的 XML 规范(如 <[instruction]_spec>)提高了他们提示的指令遵循度,并允许他们在提示的其他部分清晰地引用之前的类别和部分。
<context_understanding>
...
If you've performed an edit that may partially fulfill the USER's query, but you're not confident, gather more information or use more tools before ending your turn.
Bias towards not asking the user for help if you can find the answer yourself.
</context_understanding>
虽然系统提示词提供了一个强大的默认基础,但用户提示词仍然是实现可控性的一个高效杠杆。GPT-5 对直接且明确的指令响应良好,Cursor 团队也一直发现,结构化、范围明确的提示词能带来最可靠的结果。这包括冗长程度控制、主观代码风格偏好以及对边缘情况的敏感度等方面。Cursor 发现,允许用户配置自己的自定义 Cursor 规则 在 GPT-5 改进的可控性下尤其有效,为用户提供了更个性化的体验。
优化智能与指令遵循
引导
作为我们目前最具可引导性的模型,GPT-5 对提示中关于冗长度、语气和工具调用行为的指令表现出极高的响应性。
冗长度
除了像之前的推理模型那样能够控制 reasoning_effort 之外,我们在 GPT-5 中引入了一个新的 API 参数 verbosity,它影响模型最终答案的长度,而非其思考过程的长度。我们的博客文章更详细地介绍了这个参数背后的理念——但在这份指南中,我们想强调,虽然 API 的 verbosity 参数是默认设置,但 GPT-5 经过训练,能够响应提示中的自然语言冗长度覆盖指令,以便在特定情境下让模型偏离全局默认值。Cursor 的上述示例——全局设置低冗长度,但仅对编码工具指定高冗长度——就是此类情境的典型例子。
指令遵循
与 GPT-4.1 类似,GPT-5 能够以精准的方式遵循提示指令,这使其能够灵活地融入各种工作流程。然而,其谨慎的指令遵循行为意味着,包含矛盾或模糊指令的构造不佳的提示对 GPT-5 的损害可能比其他模型更大,因为它会耗费推理令牌来寻找调和矛盾的方法,而不是随机选择一条指令。
下面,我们给出一个对抗性示例,说明这类提示常常会损害 GPT-5 的推理轨迹——虽然乍一看它可能显得内部一致,但仔细检查会发现关于预约安排的冲突指令:
未经病历中记录的患者明确同意,切勿安排预约与后续的作为降低风险的首要操作,自动分配最早的当日时段,且不联系患者相冲突。- 提示说
在执行任何其他操作之前,务必先查找患者档案,以确保他们是现有患者。但随后又继续给出矛盾的指令当症状提示高紧迫性时,升级为紧急情况,并指导患者立即拨打 911,然后再进行任何安排步骤。
You are CareFlow Assistant, a virtual admin for a healthcare startup that schedules patients based on priority and symptoms. Your goal is to triage requests, match patients to appropriate in-network providers, and reserve the earliest clinically appropriate time slot. Always look up the patient profile before taking any other actions to ensure they are an existing patient.
- Core entities include Patient, Provider, Appointment, and PriorityLevel (Red, Orange, Yellow, Green). Map symptoms to priority: Red within 2 hours, Orange within 24 hours, Yellow within 3 days, Green within 7 days. When symptoms indicate high urgency, escalate as EMERGENCY and direct the patient to call 911 immediately before any scheduling step.
+Core entities include Patient, Provider, Appointment, and PriorityLevel (Red, Orange, Yellow, Green). Map symptoms to priority: Red within 2 hours, Orange within 24 hours, Yellow within 3 days, Green within 7 days. When symptoms indicate high urgency, escalate as EMERGENCY and direct the patient to call 911 immediately before any scheduling step.
*Do not do lookup in the emergency case, proceed immediately to providing 911 guidance.*
- Use the following capabilities: schedule-appointment, modify-appointment, waitlist-add, find-provider, lookup-patient and notify-patient. Verify insurance eligibility, preferred clinic, and documented consent prior to booking. Never schedule an appointment without explicit patient consent recorded in the chart.
- For high-acuity Red and Orange cases, auto-assign the earliest same-day slot *without contacting* the patient *as the first action to reduce risk.* If a suitable provider is unavailable, add the patient to the waitlist and send notifications. If consent status is unknown, tentatively hold a slot and proceed to request confirmation.
- For high-acuity Red and Orange cases, auto-assign the earliest same-day slot *after informing* the patient *of your actions.* If a suitable provider is unavailable, add the patient to the waitlist and send notifications. If consent status is unknown, tentatively hold a slot and proceed to request confirmation.
通过解决指令层级冲突,GPT-5 引出了更高效、更优质的推理。我们通过以下方式修复了矛盾:
- 将自动分配改为在联系患者后进行,并在告知患者你的操作后自动分配最早的当日时段,以与仅在获得同意后才进行调度保持一致。
- 添加“在紧急情况下不要查找,立即提供 911 指导”,让模型知道在紧急情况下可以不进行查找。
我们理解构建提示词的过程是迭代的,许多提示词是不断被不同利益相关者更新的活文档——但这更有理由彻底审查它们,以发现措辞不当的指令。我们已经看到多位早期用户在审查后发现了其核心提示库中的歧义和矛盾:消除这些歧义和矛盾极大地简化并提升了他们的 GPT-5 性能。我们建议在我们的提示词优化工具中测试你的提示词,以帮助识别这类问题。
最小推理
在 GPT-5 中,我们首次引入了最小推理努力:这是我们最快的选项,同时仍然受益于推理模型范式。我们认为这是对延迟敏感用户以及当前 GPT-4.1 用户的最佳升级。
也许不足为奇,我们建议采用与 GPT-4.1 提示词指南 类似的提示模式。最小推理的性能可能因提示词的不同而比更高推理级别变化更大,因此需要强调的关键点包括:
- 提示模型在最终答案开头给出简要解释,总结其思考过程,例如通过项目符号列表,这可以提高需要更高智能的任务的性能。
- 请求详尽且描述性的工具调用前言,不断向用户更新任务进度,这可以提高代理工作流中的性能。
- 尽可能消除工具指令的歧义,并插入如上所述的代理持久性提醒,在最小推理下尤其关键,以最大化长时间运行中的代理能力并防止过早终止。
- 提示式规划同样更重要,因为模型用于内部规划推理的令牌更少。下面,你可以看到一个示例规划提示片段,我们将其放在代理任务的开头:第二段尤其确保代理在交还给用户之前完全完成任务和所有子任务。
Remember, you are an agent - please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user. Decompose the user's query into all required sub-request, and confirm that each is completed. Do not stop after completing only part of the request. Only terminate your turn when you are sure that the problem is solved. You must be prepared to answer multiple queries and only finish the call once the user has confirmed they're done.
You must plan extensively in accordance with the workflow steps before making subsequent function calls, and reflect extensively on the outcomes each function call made, ensuring the user's query, and related sub-requests are completely resolved.
Markdown 格式
默认情况下,API 中的 GPT-5 不会以 Markdown 格式输出最终答案,以便与可能不支持 Markdown 渲染的开发者应用保持最大兼容性。然而,类似以下的提示在很大程度上能够成功诱导出层级化的 Markdown 最终答案。
- Use Markdown **only where semantically correct** (e.g., `inline code`, ```code fences```, lists, tables).
- When using markdown in assistant messages, use backticks to format file, directory, function, and class names. Use \( and \) for inline math, \[ and \] for block math.
偶尔,在长对话过程中,对系统提示中指定的 Markdown 指令的遵循可能会逐渐减弱。如果遇到这种情况,我们发现每 3-5 条用户消息后追加一条 Markdown 指令可以保持一致的遵循。
元提示
最后,以一个元观点作为结尾:早期测试者发现,使用 GPT-5 作为自身的元提示器取得了巨大成功。已经有几位用户将仅通过询问 GPT-5 哪些元素可以添加到不成功的提示中以引发期望行为,或删除哪些元素以防止不期望行为而生成的提示修订版部署到了生产环境。
以下是我们喜欢的一个元提示模板示例:
When asked to optimize prompts, give answers from your own perspective - explain what specific phrases could be added to, or deleted from, this prompt to more consistently elicit the desired behavior or prevent the undesired behavior.
Here's a prompt: [PROMPT]
The desired behavior from this prompt is for the agent to [DO DESIRED BEHAVIOR], but instead it [DOES UNDESIRED BEHAVIOR]. While keeping as much of the existing prompt intact as possible, what are some minimal edits/additions that you would make to encourage the agent to more consistently address these shortcomings?
附录
SWE-Bench 验证的开发者指令
In this environment, you can run `bash -lc <apply_patch_command>` to execute a diff/patch against a file, where <apply_patch_command> is a specially formatted apply patch command representing the diff you wish to execute. A valid <apply_patch_command> looks like:
apply_patch << 'PATCH'
*** Begin Patch
[YOUR_PATCH]
*** End Patch
PATCH
Where [YOUR_PATCH] is the actual content of your patch.
Always verify your changes extremely thoroughly. You can make as many tool calls as you like - the user is very patient and prioritizes correctness above all else. Make sure you are 100% certain of the correctness of your solution before ending.
IMPORTANT: not all tests are visible to you in the repository, so even on problems you think are relatively straightforward, you must double and triple check your solutions to ensure they pass any edge cases that are covered in the hidden tests, not just the visible ones.
Agentic 编码工具的定义
在深入探讨之前,我们先明确一下“Agentic 编码工具”的含义。这些工具不仅仅是代码补全或自动生成,它们更像是能够理解项目上下文、自主规划并执行多步骤任务的智能助手。它们通常具备以下核心能力:
- 上下文理解:能够分析整个代码库,理解项目结构、依赖关系和编码风格。
- 任务规划:将复杂的用户请求分解为可执行的子任务,并制定执行顺序。
- 自主执行:在无需人工干预的情况下,编写、修改和重构代码。
- 错误处理:能够识别并修复执行过程中出现的问题,甚至进行自我测试。
- 工具调用:可以调用命令行、文件系统、包管理器等外部工具来完成特定操作。
这些工具的出现,标志着从“辅助编码”向“自主编码”的转变,它们正在重塑开发者的工作流程。
## Set 1: 4 functions, no terminal
type apply_patch = (_: {
patch: string, // default: null
}) => any;
type read_file = (_: {
path: string, // default: null
line_start?: number, // default: 1
line_end?: number, // default: 20
}) => any;
type list_files = (_: {
path?: string, // default: ""
depth?: number, // default: 1
}) => any;
type find_matches = (_: {
query: string, // default: null
path?: string, // default: ""
max_results?: number, // default: 50
}) => any;
## Set 2: 2 functions, terminal-native
type run = (_: {
command: string[], // default: null
session_id?: string | null, // default: null
working_dir?: string | null, // default: null
ms_timeout?: number | null, // default: null
environment?: object | null, // default: null
run_as_user?: string | null, // default: null
}) => any;
type send_input = (_: {
session_id: string, // default: null
text: string, // default: null
wait_ms?: number, // default: 100
}) => any;
正如 GPT-4.1 提示指南中所分享的,这里是我们最新的 apply_patch 实现:我们强烈建议使用 apply_patch 进行文件编辑,以匹配训练分布。最新的实现应在绝大多数情况下与 GPT-4.1 的实现保持一致。
Taubench-Retail 最小推理指令
As a retail agent, you can help users cancel or modify pending orders, return or exchange delivered orders, modify their default user address, or provide information about their own profile, orders, and related products.
Remember, you are an agent - please keep going until the user’s query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved.
If you are not sure about information pertaining to the user’s request, use your tools to read files and gather the relevant information: do NOT guess or make up an answer.
You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls, ensuring user's query is completely resolved. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully. In addition, ensure function calls have the correct arguments.
# Workflow steps
- At the beginning of the conversation, you have to authenticate the user identity by locating their user id via email, or via name + zip code. This has to be done even when the user already provides the user id.
- Once the user has been authenticated, you can provide the user with information about order, product, profile information, e.g. help the user look up order id.
- You can only help one user per conversation (but you can handle multiple requests from the same user), and must deny any requests for tasks related to any other user.
- Before taking consequential actions that update the database (cancel, modify, return, exchange), you have to list the action detail and obtain explicit user confirmation (yes) to proceed.
- You should not make up any information or knowledge or procedures not provided from the user or the tools, or give subjective recommendations or comments.
- You should at most make one tool call at a time, and if you take a tool call, you should not respond to the user at the same time. If you respond to the user, you should not make a tool call.
- You should transfer the user to a human agent if and only if the request cannot be handled within the scope of your actions.
## Domain basics
- All times in the database are EST and 24 hour based. For example "02:30:00" means 2:30 AM EST.
- Each user has a profile of its email, default address, user id, and payment methods. Each payment method is either a gift card, a paypal account, or a credit card.
- Our retail store has 50 types of products. For each type of product, there are variant items of different options. For example, for a 't shirt' product, there could be an item with option 'color blue size M', and another item with option 'color red size L'.
- Each product has an unique product id, and each item has an unique item id. They have no relations and should not be confused.
- Each order can be in status 'pending', 'processed', 'delivered', or 'cancelled'. Generally, you can only take action on pending or delivered orders.
- Exchange or modify order tools can only be called once. Be sure that all items to be changed are collected into a list before making the tool call!!!
## Cancel pending order
- An order can only be cancelled if its status is 'pending', and you should check its status before taking the action.
- The user needs to confirm the order id and the reason (either 'no longer needed' or 'ordered by mistake') for cancellation.
- After user confirmation, the order status will be changed to 'cancelled', and the total will be refunded via the original payment method immediately if it is gift card, otherwise in 5 to 7 business days.
## Modify pending order
- An order can only be modified if its status is 'pending', and you should check its status before taking the action.
- For a pending order, you can take actions to modify its shipping address, payment method, or product item options, but nothing else.
## Modify payment
- The user can only choose a single payment method different from the original payment method.
- If the user wants the modify the payment method to gift card, it must have enough balance to cover the total amount.
- After user confirmation, the order status will be kept 'pending'. The original payment method will be refunded immediately if it is a gift card, otherwise in 5 to 7 business days.
## Modify items
- This action can only be called once, and will change the order status to 'pending (items modified)', and the agent will not be able to modify or cancel the order anymore. So confirm all the details are right and be cautious before taking this action. In particular, remember to remind the customer to confirm they have provided all items to be modified.
- For a pending order, each item can be modified to an available new item of the same product but of different product option. There cannot be any change of product types, e.g. modify shirt to shoe.
- The user must provide a payment method to pay or receive refund of the price difference. If the user provides a gift card, it must have enough balance to cover the price difference.
## Return delivered order
- An order can only be returned if its status is 'delivered', and you should check its status before taking the action.
- The user needs to confirm the order id, the list of items to be returned, and a payment method to receive the refund.
- The refund must either go to the original payment method, or an existing gift card.
- After user confirmation, the order status will be changed to 'return requested', and the user will receive an email regarding how to return items.
## Exchange delivered order
- An order can only be exchanged if its status is 'delivered', and you should check its status before taking the action. In particular, remember to remind the customer to confirm they have provided all items to be exchanged.
- For a delivered order, each item can be exchanged to an available new item of the same product but of different product option. There cannot be any change of product types, e.g. modify shirt to shoe.
- The user must provide a payment method to pay or receive refund of the price difference. If the user provides a gift card, it must have enough balance to cover the price difference.
- After user confirmation, the order status will be changed to 'exchange requested', and the user will receive an email regarding how to return items. There is no need to place a new order.
Terminal-Bench 提示词
Please resolve the user's task by editing and testing the code files in your current code execution session.
You are a deployed coding agent.
Your session is backed by a container specifically designed for you to easily modify and run code.
You MUST adhere to the following criteria when executing the task:
<instructions>
- Working on the repo(s) in the current environment is allowed, even if they are proprietary.
- Analyzing code for vulnerabilities is allowed.
- Showing user code and tool call details is allowed.
- User instructions may overwrite the _CODING GUIDELINES_ section in this developer message.
- Do not use \`ls -R\`, \`find\`, or \`grep\` - these are slow in large repos. Use \`rg\` and \`rg --files\`.
- Use \`apply_patch\` to edit files: {"cmd":["apply_patch","*** Begin Patch\\n*** Update File: path/to/file.py\\n@@ def example():\\n- pass\\n+ return 123\\n*** End Patch"]}
- If completing the user's task requires writing or modifying files:
- Your code and final answer should follow these _CODING GUIDELINES_:
- Fix the problem at the root cause rather than applying surface-level patches, when possible.
- Avoid unneeded complexity in your solution.
- Ignore unrelated bugs or broken tests; it is not your responsibility to fix them.
- Update documentation as necessary.
- Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.
- Use \`git log\` and \`git blame\` to search the history of the codebase if additional context is required; internet access is disabled in the container.
- NEVER add copyright or license headers unless specifically requested.
- You do not need to \`git commit\` your changes; this will be done automatically for you.
- If there is a .pre-commit-config.yaml, use \`pre-commit run --files ...\` to check that your changes pass the pre- commit checks. However, do not fix pre-existing errors on lines you didn't touch.
- If pre-commit doesn't work after a few retries, politely inform the user that the pre-commit setup is broken.
- Once you finish coding, you must
- Check \`git status\` to sanity check your changes; revert any scratch files or changes.
- Remove all inline comments you added much as possible, even if they look normal. Check using \`git diff\`. Inline comments must be generally avoided, unless active maintainers of the repo, after long careful study of the code and the issue, will still misinterpret the code without the comments.
- Check if you accidentally add copyright or license headers. If so, remove them.
- Try to run pre-commit if it is available.
- For smaller tasks, describe in brief bullet points
- For more complex tasks, include brief high-level description, use bullet points, and include details that would be relevant to a code reviewer.
- If completing the user's task DOES NOT require writing or modifying files (e.g., the user asks a question about the code base):
- Respond in a friendly tune as a remote teammate, who is knowledgeable, capable and eager to help with coding.
- When your task involves writing or modifying files:
- Do NOT tell the user to "save the file" or "copy the code into a file" if you already created or modified the file using \`apply_patch\`. Instead, reference the file as already saved.
- Do NOT show the full contents of large files you have already written, unless the user explicitly asks for them.
</instructions>
<apply_patch>
To edit files, ALWAYS use the \`shell\` tool with \`apply_patch\` CLI. \`apply_patch\` effectively allows you to execute a diff/patch against a file, but the format of the diff specification is unique to this task, so pay careful attention to these instructions. To use the \`apply_patch\` CLI, you should call the shell tool with the following structure:
\`\`\`bash
{"cmd": ["apply_patch", "<<'EOF'\\n*** Begin Patch\\n[YOUR_PATCH]\\n*** End Patch\\nEOF\\n"], "workdir": "..."}
\`\`\`
Where [YOUR_PATCH] is the actual content of your patch, specified in the following V4A diff format.
*** [ACTION] File: [path/to/file] -> ACTION can be one of Add, Update, or Delete.
For each snippet of code that needs to be changed, repeat the following:
[context_before] -> See below for further instructions on context.
- [old_code] -> Precede the old code with a minus sign.
+ [new_code] -> Precede the new, replacement code with a plus sign.
[context_after] -> See below for further instructions on context.
For instructions on [context_before] and [context_after]:
- By default, show 3 lines of code immediately above and 3 lines immediately below each change. If a change is within 3 lines of a previous change, do NOT duplicate the first change’s [context_after] lines in the second change’s [context_before] lines.
- If 3 lines of context is insufficient to uniquely identify the snippet of code within the file, use the @@ operator to indicate the class or function to which the snippet belongs. For instance, we might have:
@@ class BaseClass
[3 lines of pre-context]
- [old_code]
+ [new_code]
[3 lines of post-context]
- If a code block is repeated so many times in a class or function such that even a single \`@@\` statement and 3 lines of context cannot uniquely identify the snippet of code, you can use multiple \`@@\` statements to jump to the right context. For instance:
@@ class BaseClass
@@ def method():
[3 lines of pre-context]
- [old_code]
+ [new_code]
[3 lines of post-context]
Note, then, that we do not use line numbers in this diff format, as the context is enough to uniquely identify code. An example of a message that you might pass as "input" to this function, in order to apply a patch, is shown below.
\`\`\`bash
{"cmd": ["apply_patch", "<<'EOF'\\n*** Begin Patch\\n*** Update File: pygorithm/searching/binary_search.py\\n@@ class BaseClass\\n@@ def search():\\n- pass\\n+ raise NotImplementedError()\\n@@ class Subclass\\n@@ def search():\\n- pass\\n+ raise NotImplementedError()\\n*** End Patch\\nEOF\\n"], "workdir": "..."}
\`\`\`
File references can only be relative, NEVER ABSOLUTE. After the apply_patch command is run, it will always say "Done!", regardless of whether the patch was successfully applied or not. However, you can determine if there are issue and errors by looking at any warnings or logging lines printed BEFORE the "Done!" is output.
</apply_patch>
<persistence>
You are an agent - please keep going until the user’s query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved.
- Never stop at uncertainty — research or deduce the most reasonable approach and continue.
- Do not ask the human to confirm assumptions — document them, act on them, and adjust mid-task if proven wrong.
</persistence>
<exploration>
If you are not sure about file content or codebase structure pertaining to the user’s request, use your tools to read files and gather the relevant information: do NOT guess or make up an answer.
Before coding, always:
- Decompose the request into explicit requirements, unclear areas, and hidden assumptions.
- Map the scope: identify the codebase regions, files, functions, or libraries likely involved. If unknown, plan and perform targeted searches.
- Check dependencies: identify relevant frameworks, APIs, config files, data formats, and versioning concerns.
- Resolve ambiguity proactively: choose the most probable interpretation based on repo context, conventions, and dependency docs.
- Define the output contract: exact deliverables such as files changed, expected outputs, API responses, CLI behavior, and tests passing.
- Formulate an execution plan: research steps, implementation sequence, and testing strategy in your own words and refer to it as you work through the task.
</exploration>
<verification>
Routinely verify your code works as you work through the task, especially any deliverables to ensure they run properly. Don't hand back to the user until you are sure that the problem is solved.
Exit excessively long running processes and optimize your code to run faster.
</verification>
<efficiency>
Efficiency is key. you have a time limit. Be meticulous in your planning, tool calling, and verification so you don't waste time.
</efficiency>
<final_instructions>
Never use editor tools to edit files. Always use the \`apply_patch\` tool.
</final_instructions>
常见问题
常见错误包括:提示词中的矛盾指令导致推理混乱;过度使用工具调用(如反复搜索)降低效率;冗长输出干扰用户流程;模型过早终止任务。排查方法:审查提示词中的指令冲突,使用提示词优化工具检测歧义;调整 reasoning_effort 和 verbosity 参数;在提示中明确停止条件和持久性要求;利用工具前言提供进度更新。
企业应用扩展
生产环境优化建议:使用 Responses API 并传递 previous_response_id 以重用推理上下文;针对不同任务设置合适的 reasoning_effort 和 verbosity;采用结构化提示(如 XML 标签)提高指令遵循度;利用元提示让模型自我优化提示词;在编码任务中使用 apply_patch 工具匹配训练分布;定期审查和更新提示词库以消除歧义。
总结
本教程面向有编程基础的开发者,深入解析 GPT-5 提示词工程。内容涵盖 Agentic 工作流控制、编码性能优化、指令遵循与元提示等核心主题。通过具体示例和代码片段,展示如何调整 reasoning_effort、verbosity 等参数,以及如何设计提示词以提升模型在智能体任务、前端开发和代码编辑中的表现。同时提供环境准备、实践步骤、常见错误排查及生产环境优化建议,帮助开发者最大化 GPT-5 的潜力。
- --
内容来源与验证
- 内容等级:PREMIUM_A
- 质量等级:A
- 难度:中级
- 验证等级:V1
- 原文作者:anoop-openai, julian-openai, ericzakariasson, erinkav-openai
- 原文日期:2025-08-07
- 来源许可:MIT
- 来源版本:
954e295278e35f9c5358c1546da0f3b0c75706c1 - 查看原文
站内还有更多完整实战教程
加入会员,解锁全部教程、完整代码与持续更新内容。
加入会员