使用 GPT-6 Astra
了解 GPT-6 Astra 的最佳实践、功能和迁移指南。
简介
GPT-6 Astra 是我们迄今最智能的模型,在计算机使用、浏览、软件工程、科学和专业工作方面具有领先表现。它擅长执行涉及代码、浏览器和专业软件的多步骤工作流。在多项评测中,Astra 在取得更好结果的同时,使用的输出 Token 显著减少。因此,尽管每个 Token 的定价更高,其每项任务的估算 API 成本仍低于早期模型。
GPT-6 Astra 也是我们迄今对齐表现最好的模型。它擅长谨慎行事、遵守任务边界并保持沟通透明。当指令留有解释空间时,它会利用已有上下文补全常规细节;如果某个问题的答案可能改变结果,它会有针对性地提问。它能纳入新要求、按要求调整方向,并在回答附带问题时始终顾及整体任务。
要使用 Astra 进行开发,请在 Responses API 请求中将 model 设置为 gpt-6-astra。
最新动态
- 异步工具调用: 当您的应用运行工具时,GPT-6 Astra 可以继续推理、调用其他工具,或回答请求中相互独立的部分。在函数或自定义工具上设置
async: true,并在结果就绪时使用原始call_id返回结果。工具执行和待完成工作的管理仍由您的应用负责。有关基本用法和开发者自定义的等待工具模式,请参阅异步工具调用。 - 轮次中途引导: 在 GPT-6 Astra 工作时发送额外的用户指令,例如纠正信息或更改要求。通过 WebSocket 连接,Responses API 会保留已完成的工作,并在继续执行时纳入更新。有关事件流程和工具结果处理,请参阅轮次中途引导。
- 在对话中途调整推理并保留缓存: 添加一个
configuration_update输入项,即可针对复杂工作提高推理强度,或针对常规后续请求降低推理强度,无需改写原始提示前缀。更新后的推理强度会持续生效,直到另一个configuration_update输入项将其覆盖。有关示例和兼容性,请参阅在对话中途调整推理。 - 对齐偏差监测: 作为我们为 GPT-6 Astra 加强的安全防护措施的一部分,我们的系统会异步监测对齐偏差,并在必要时触发警报。更多信息请参阅对齐偏差监测。
- 限制: GPT-6 Astra 不支持
none推理强度。使用欧盟数据驻留时,GPT-6 Astra 无法使用快速模式。
GPT-6 Astra 还支持 GPT-5.6 已有的 API 能力,包括计算机使用、结构化输出、流式传输、程序化工具调用、多智能体编排、提示缓存、持久化推理、压缩和 Pro 模式。
提示词最佳实践
与 GPT-5.6 Sol 等早期模型相比,GPT-6 Astra 更智能、能力更强。它也有一些行为特点,您可以根据具体用例,通过提示来优化这些行为。
GPT-6 Astra 的行为特点
- 主动性与持续执行:该模型旨在更有效地协作,因此,当额外输入可能实质性地改变结果时,它更倾向于向用户提问。这可能导致模型停下来,而用户原本希望它做出合理假设并继续推进。
- 指令遵循:GPT-6 Astra 的整体指令遵循能力强于我们之前的模型,让您能更好地控制其行为。它可能更容易受到技能和其他文件(例如
AGENTS.md)中指令的影响。我们 强烈建议 检查模型可访问的技能和其他文件,找出其中可能影响模型行为的指令。 - 个性与写作风格:该模型倾向于提供详细且带有格式的回答,也可能在不同会话中反复使用相同的措辞。请明确指定您的应用所需的写作风格和结构。
- 子智能体委派:模型委派工作的频率可能低于您的工作流预期。请明确指定它应在何时使用子智能体并行工作,以及应委派多少工作。
- 测试与验证:对于编程任务,模型通常会在充分测试后才认为任务已经完成。对于较小的任务,这可能导致测试范围超出任务所需。
主动性与持续执行
在长时间任务中,GPT-6 Astra 通常比 GPT-5.6 Sol 及更早的模型更能保持连贯性。在早期模型会自行做出假设的情况下,它也更倾向于请求澄清。
要鼓励模型更自主地工作,可以从以下提示开始:
You should infer the user's intent and task scope from the instructions and prior conversation context. Your job is to bias towards action and carry the user's intended task to completion.
When the user expresses intent to perform new work or fix an existing issue, persist until the user's intended goal is complete. Progress autonomously towards the user's goal (e.g. creating isolated worktrees / checkouts if needed, resolving merge conflicts, read-only actions, creating draft PRs etc.) unless they are clearly destructive or irreversible.
当用户意图不明确时,模型更倾向于先向用户请求澄清,再继续执行。您可以通过提示要求模型在用户的提示已隐含授权时继续执行到底:
When the user's prompt indicates a request for action, such as "can you...", "I want to...", "help me..." and similar expressions, treat these as instructions to do the work and take action. Do not stop at acknowledging capability (e.g. "Yes…"), proposing a plan, or offering to continue. Do not settle for a partial or "helpful enough" solution that does not fully satisfy the user's task to save time, effort or tokens. If a task requires sustained work, complete all the necessary work until the intended outcome is fulfilled.
通过提示要求模型先准备好具体、可供审查的结果,再请求审批。这样可以避免模型尚未完成力所能及的工作就阻塞任务,通常也能更快完成任务。
Before asking the user clarifying questions, you should complete the work that is already authorized from context and necessary to make the proposed action concrete and reviewable. The user should be approving a concrete, reviewable result. For example, before deploying a change, writing to an external application, merging a PR or publishing a site, do all the required work first so that user approval is the final step. You don't need user permission for reversible tasks, read-only actions, reviews or fixes, or anything for which authorization is provided earlier in the session or strongly implied from the task instruction.
Do not introduce unsolicited warnings, disclaimers, approval flows, or safety/compliance checklists due to hypothetical risk.
默认情况下,模型也倾向于在工作时提出不阻塞进度的问题,因此请根据您的应用所需的自主程度调整这些提示。
指令遵循
GPT-6 Astra 更善于遵循较长的指令,但也可能更容易受到上下文信息的影响。例如,技能文件中含糊或相互冲突的指导可能导致模型过早暂停,阻塞工作。请明确用户指令与技能之间的优先级。
The user's instructions take precedence over guidelines provided in a skill. If explicit user instructions conflict with a skill's instructions, prioritize the user's instructions.
要求模型指出导致它暂停或改变方向的具体技能和指令,也能有效提高模型行为的透明度。
If a skill causes you to ask for permission or confirmation, pause, leave requested work unfinished, or diverge from the user's intent, name and link to the exact SKILL.md file you read, quote the relevant instruction, and briefly explain how it applies. Distinguish explicit skill requirements from your interpretation of guidelines.
当您的应用加载了大量技能和 AGENTS.md 等指令文件时,可以使用此提示找出在未说明的情况下影响模型行为的指导,以及相互冲突的指导。
个性与写作风格
GPT-6 Astra 倾向于使用列表、表格和 Markdown,让回答便于快速浏览。如果您的应用需要较少使用格式的段落文字,请明确说明这一偏好。
Default to using clear, concise paragraphs, each developing one main idea. Use lists only when the information is genuinely parallel, sequential, or easier to compare, and avoid nested lists unless the hierarchy cannot be expressed clearly in prose. Use plain, simple language: familiar words, concrete examples, and precise verbs. Prefer active voice and direct statements.
Make sure to state the main point clearly and early, then develop it with the explanation and detail the reader needs. Let each sentence build on what came before. Develop the points that matter and provide enough support to be useful.
在技术沟通中,以下提示有助于让语言既清晰连贯,又符合专业领域的表达习惯:
Use plain language over jargon, and reference technical details only to the degree that it helps illustrate an idea or your work to the user. Communicate complex concepts in a clear and cohesive manner, and calibrate your writing to the level of background knowledge assumed from the user's prompt and context.
要减少写作中的行话和套话,可以从以下提示开始:
Avoid using slop words or phrases like "Bottom Line:" in conclusions, "delve," "foster," "leverage," "it's worth noting," "importantly," "Question? Answer." or "This isn't about X. It's about Y.", "genuinely" or hyphenated compound descriptions and adjectives. Do not use concluding summary statements such as "In short:..", "The simplest mental model is:...".
State the intended action directly. Avoid adding what you won't do, what will remain unchanged, or how you'll separate or categorize results. Do not use contrastive framing such as "X, not Y" or "X—not Y" that introduces an unprompted alternative that the user didn't ask about. Avoid invented compound labels like "exact-head checks" and "editorial-row layouts", vague qualifiers, and canned transitions; use plain verbs and prepositions to state the actual relationship directly.
子智能体委派
GPT-6 Astra 经过训练,能够拆分工作并委派给并行工作的子智能体。如果您正在执行框架中实现多智能体系统,可以使用以下提示调整 GPT-6 Astra 委派的工作量:
If at any point you can parallelize work by delegating tasks to another agent (no matter if you are the root or subagent), you should do so using collaboration tools if it could save time or improve quality.
智能体之间的消息可能存在语法或空格错误。使用以下提示可以让智能体之间的消息更易读:
Messages that you send to other agents and your final answer may be read by a human, so ensure they are legible. Always put proper spaces between words and/or numbers.
模型通常能很好地遵循有关何时以及如何将工作委派给子智能体的提示,因此您可以调整这一行为,使其适合您的执行框架和多智能体实现。
测试与验证
对于编程任务,请合理确定每项变更所需的测试与验证程度。这有助于避免为小改动进行不必要的测试或重复检查。
Do not write tests for reversible, low-impact changes that mirror the implementation. If you do choose to verify your work with tests, make sure that the tests are meaningful and necessary to verify implementation.
Run tests appropriate to the change and complete required checks. Once those pass, broaden or repeat testing only when new changes, failures, or unresolved concerns justify it; otherwise, continue toward completing the task.
迁移快速入门
使用 Codex 迁移
Codex 可以使用 OpenAI 文档技能,按照本指南的建议进行更改。
$openai-docs migrate this project to GPT-6 Astra
如需在其他编程智能体中使用此技能,请从 Codex 代码仓库下载。
更新 API 和模型参数
将 model 设置为 gpt-6-astra,然后检查以下各项:
- 推理强度: 如果您当前使用
none或minimal,请先尝试low并比较结果。否则,请保留当前实际生效的推理强度。在 Responses 中使用reasoning.effort,在 Chat Completions 中使用reasoning_effort。 - 工具调用: 请使用 Responses API。GPT-6 Astra 支持 Chat Completions,但工具调用需要使用 Responses。
- 不支持的参数: 移除
temperature、top_p和top_logprobs。对于 Chat Completions,还需移除logprobs。对于 Responses,请从include中移除message.output_text.logprobs。 - 快速模式: 使用欧盟数据驻留时,请使用标准处理模式。GPT-6 Astra 在使用欧盟数据驻留时不支持
service_tier: "fast"或service_tier: "priority"。GPT-6 Astra 的快速模式不包含延迟 SLA。请参阅快速模式兼容性。 - 更改推理强度: 如果您的应用会在不同响应之间更改推理强度,请在标准的单智能体请求中使用
configuration_update项。保持请求级别的reasoning.effort不变,以保留用于缓存的提示前缀。在采用此功能之前,请查看兼容性限制。 - 提示缓存: 从 GPT-5.5 或更早的模型迁移时,请将
prompt_cache_retention替换为prompt_cache_options.ttl,并将其值设置为"30m"。请查看提示缓存的变化,包括缓存边界和缓存写入计费。 - 不必要的审批暂停: 如果您遇到模型反复请求审批才继续执行的问题,请参考主动性与持续执行指南,通过提示引导它更自主地执行。有关指令遵循、写作风格、子智能体委派和测试的指导,请参阅提示词最佳实践的其余内容。
使用 GPT-5.6
了解 GPT-5.6 及 GPT-5.6 模型系列的最佳实践、功能和迁移指南。
简介
GPT-5.6 为复杂的生产环境工作流树立了新的质量和效率基准。GPT-5.6 的 Token 使用效率尤为出色,并提升了前端美观度,包括布局、视觉层次和设计判断力。
GPT-5.6 还引入了新的命名方案。gpt-5.6 别名会将请求路由到具备旗舰级能力的模型 gpt-5.6-sol。如需以较低价格获得强劲性能,请使用 gpt-5.6-terra;如需高效处理大规模工作负载,请使用 gpt-5.6-luna。
从 GPT-5.5 或 GPT-5.4 迁移时,请以您当前的 GPT-5.5 或 GPT-5.4 推理设置为起点,在有代表性的任务上测试相同设置和低一级的设置。GPT-5.6 通常能以更少的 Token 保持或提升质量,但最佳设置取决于您的工作负载。
最新动态
- 程序化工具调用: GPT-5.6 可以编写 JavaScript 来调用符合条件的工具,在调用之间传递结果,并在托管运行时中处理中间输出。对于范围明确、工具调用密集且各步骤之间无需模型重新判断的工作流,请使用程序化工具调用。程序化工具调用兼容 ZDR,且不收取额外的容器费用。
- 多智能体 [beta]: 多智能体让一个 GPT-5.6 实例能够并行协调多个子智能体,并综合它们的结果。与 Codex 中的 Ultra 模式类似,对于能够清晰拆分为独立工作流的复杂任务,这可以缩短实际耗时并提升表现。多智能体目前作为测试版功能在 Responses API 中提供,我们会根据开发者反馈持续迭代。
- 显式提示缓存: GPT-5.6 让您能够精确标记要由 OpenAI 缓存的可复用提示前缀。您仍然可以在隐式模式下使用自动缓存。OpenAI 按未缓存输入费率的 1.25 倍收取缓存写入费用,缓存读取则继续享受折扣。了解如何配置提示缓存。
- 持久化推理: GPT-5.6 可以跨轮次复用可用的推理项,以提升多轮交互质量和缓存效率。使用
reasoning.context选择具体行为。了解如何在调用之间保留推理。 - Max 推理强度: GPT-5.6 支持
max推理强度,适用于需要更多探索和验证的复杂任务。如果您当前使用xhigh,请在有代表性的工作负载上比较这两种设置。 - Pro 模式: GPT-5.6 可以投入更多模型计算,提高处理困难任务的可靠性,并返回一个最终答案。当质量比延迟和 Token 用量更重要时,请通过
reasoning.mode: "pro"启用此模式。了解如何使用 Pro 模式。 - Token 使用效率: GPT-5.6 用更少的输出 Token 实现旗舰级性能。
- 前端设计: GPT-5.6 能够创建更精美、更易用的网站和应用,在布局、视觉层次和设计判断力方面均有提升。
- 意图理解: GPT-5.6 能够更好地从上下文推断用户的真实目标和期望完成的工作程度,因此您通常不必规定每一个步骤。请继续提供领域背景、硬性约束、审批边界和成功标准。请告诉模型,遇到哪些重要歧义时应提问。
- 原始图像细节: 当图像细节级别设为
original或auto时,GPT-5.6 会保留图像尺寸,但任一边超过 65,535 像素的图像会被缩小至该限制内。对于仍超出 30,000 个图像块限制的图像,API 会拒绝接收,而不会继续调整尺寸以满足限制。大尺寸图像可能消耗更多输入 Token 并增加延迟。了解如何选择图像细节级别。
安全防护措施
使用 GPT-5.6 模型时,用户可能会遇到安全防护措施阻止或拒绝某些请求,因为模型生成输出的同时会运行实时网络与生物领域滥用分类器。其他请求可能耗时更长,因为这些分类器同步审查输出时,生成过程会中途暂停数秒。安全防护措施偶尔也会干预正当工作,尤其是在防御和攻击活动起初可能看起来相似的双重用途领域。
如果您的应用面向个人终端用户,请随每个请求发送一个稳定且保护隐私的 safety_identifier。有关指导,请参阅实现安全标识符。
我们持续改进这些安全防护措施,使其能够稳健、有效地抵御对抗性攻击,同时确保代码审查、漏洞研究、补丁开发、调试、安全教育和防御测试等正当工作仍可正常开展。
迁移快速入门
使用 Codex 迁移
Codex 可以通过 OpenAI 文档技能应用本指南中建议的更改。
$openai-docs migrate this project to the GPT-5.6 model family
如需在其他编程智能体中使用此技能,请从 OpenAI 技能代码仓库下载。
更新 API 和模型参数
- 根据工作负载选择目标模型。如需旗舰级能力,请使用
gpt-5.6-sol;如需兼顾智能水平与成本,请使用gpt-5.6-terra;如需高效处理大规模工作负载,请使用gpt-5.6-luna。gpt-5.6别名会将请求路由到gpt-5.6-sol。 - 对于推理、工具调用和多轮工作流,请使用 Responses API。
- 请根据需求明确设置
reasoning.effort。GPT-5.6 支持none、low、medium、high、xhigh和max。- 如果您正在从 GPT-5.5 或 GPT-5.4 迁移,请保留当前推理强度作为基准,再与低一级的设置进行比较。
- 如果您使用
none,请将其保留为延迟基准;如果工作流能从推理或工具使用中获益,也请测试low。 - 使用
medium作为兼顾各方面需求的起点;对于延迟敏感的工作负载,请使用low。 - 当实测表明更多推理能提升质量时,请使用
high或xhigh。 - 仅对难度最高且质量优先的工作负载使用
max。比较max和xhigh,找到最适合您用例的质量、延迟和成本平衡点。
- 如需使用 Pro 模式,请保留您选定的 GPT-5.6 模型,并在 Responses API 中将
reasoning.mode设为pro;不要切换到单独的 Pro 模型 Slug。请独立选择reasoning.effort。如果省略此参数,GPT-5.6 在标准模式和 Pro 模式下都会默认使用medium。有关请求示例和计费详情,请参阅推理模式。 - 请根据先前推理仍有多少与当前任务相关,配置持久化推理。GPT-5.6 模型默认使用
all_turns;更早的模型默认使用current_turn。- 省略
reasoning.context或将其设为auto,即可使用 GPT-5.6 的默认值all_turns。检查响应中的reasoning.context字段,以确认实际生效的模式。 - 当任务的目标、假设和优先级在各轮次之间保持稳定时,请将
reasoning.context设为all_turns。 - 使用
all_turns时,请通过previous_response_id继续对话,让模型能够使用先前响应中的推理。 - 手动管理历史记录时,请保留并重新发送先前的用户输入和每个响应输出项。对于
store: false或零数据保留场景,请重新传入 API 默认返回的加密推理项。 - 当先前的推理已不再与当前任务相关时,请将
reasoning.context设为current_turn。
- 省略
- 检查提示缓存。您无需更改代码即可继续使用隐式缓存。由于 GPT-5.6 的缓存写入费用是未缓存输入费率的 1.25 倍,请跟踪
cached_tokens和cache_write_tokens以了解净成本。使用显式断点或prompt_cache_options.mode: "explicit"来避免不必要的写入,并将prompt_cache_retention替换为prompt_cache_options.ttl。 - 如需使用程序化工具调用,请添加
programmatic_tool_calling工具,并通过allowed_callers为符合条件的工具启用此功能。更新您的应用,使其能够处理program项、程序发起的函数调用以及program_output项,同时保留每次调用的call_id和caller关联关系。有关请求和后续调用示例,请参阅程序化工具调用指南。- 在有代表性的任务上对启用了 PTC 的工作流进行基准测试。比较任务成功情况、最终答案的完整性、所需证据、Token 总量、延迟和成本。只有在最终答案仍达到所需质量标准的前提下,减少调用、轮次或中间输出才算改进。
提示词最佳实践
优先使用更精简的提示
删除重复的指令和示例,并简化工具描述,可以改善任务表现和 Token 使用效率。在一组内部编程智能体评测运行样本中,使用更精简系统提示的配置将评估得分提高了约 10–15%,同时将 Token 总量减少了 41–66%,成本降低了 33–67%。结果因工作负载而异,因此请将这些范围视为趋势参考,并在您自己的应用中选取有代表性的任务来验证更改。
要在保留重要指导的同时简化提示,请遵循以下做法:
- 以已经有效的提示和工具集为起点。每次移除一组指令、示例或工具,然后重新运行相同的评测。
- 每条指令只表述一次。
- 仅提供与任务相关的工具,并保持工具描述简洁、准确。
- 如果示例和风格指导体现了产品要求,或能弥补实测发现的不足,请保留它们。
- 在运行开始时以及对话不断增长的过程中,都要跟踪上下文。长时间会话可能放大重复提示和工具内容的影响。
明确自主操作与审批边界
GPT-5.6 在执行多步骤任务时能够主动、持续地推进工作。请明确每个请求授权的操作程度,让模型能够继续执行安全且在范围内的工作,避免不必要的暂停,同时在执行对外操作、破坏性操作、成本高昂的操作或扩大范围的操作之前停下来。
通常,一套简明的规则就足够了:
For requests to answer, explain, review, diagnose, or plan, inspect the relevant
materials and report the result. Do not implement changes unless the request also
asks for them.
For requests to change, build, or fix, make the requested in-scope local changes
and run relevant non-destructive validation without asking first.
Require confirmation for external writes, destructive actions, purchases, or a
material expansion of scope.
明确列出安全的本地操作,例如读取文件、检查日志、编辑范围内的代码以及运行测试。将规则集中在一处,每条规则只表述一次。反复强调“先询问”“不要修改”或“等待审批”等指令,可能导致模型对安全且符合预期的操作提出不必要的审批请求。
设置回复长度和风格
GPT-5.6 默认往往比 GPT-5.5 更简洁。迁移时,请检查“简洁一些”或“保持简短”等宽泛的简洁要求是否仍然有用。对于某些任务,这些要求可能没有必要,有时还会让回复过于简短。如果它们能稳定地产生应用所需的输出,则请保留。
为了在不同请求中实现更一致的控制,请使用 text.verbosity 设置默认详细程度,再在提示中指定任务的具体要求。
使用 text.verbosity 设置默认值
选择 low、medium 或 high 作为请求的默认详细程度。在提示中指定任务对长度、结构或必需内容的具体要求。有关 API 示例,请参阅设置 text.verbosity。
明确简短答案必须包含的内容
当任务需要较短的回答时,请明确模型必须保留哪些信息,以及可以省略哪些细节。例如:
Lead with the conclusion. Include the evidence needed to support it, any material
caveat, and the next action. Omit secondary detail and repetition.
Keep all required facts, decisions, caveats, and next steps. Trim introductions,
repetition, generic reassurance, and optional background first.
这为模型明确了优先顺序:先保留完成任务所需的内容,再删去价值较低的细节。
定义语气
“友好”或“有同理心”等宽泛的标签可能含义不明。请具体说明哪些写作方式能体现您产品的语气,例如回答应有多直接、何时应回应用户遇到的问题,以及是否适合加入安抚的话语或结束语。
State the answer directly. If the user reports a problem, acknowledge the
specific issue before giving the next step. Use reassurance only when it is
relevant. Omit generic praise and unnecessary sign-offs.
Pro 模式
质量最重要时,选择 Pro 模式
Pro 模式是 Responses API 的一种执行模式,会在返回单个最终答案之前,投入更多模型计算来处理请求。它可以提高处理复杂任务时的可靠性,但会增加延迟,并将这些计算消耗的 Token 汇总计入报告的用量。这些 Token 按所选模型的标准 Token 费率计费。
如果质量的小幅提升就能对结果产生实质影响,而且任务足够复杂、能够从中受益,请使用 Pro 模式,例如复杂优化、高价值的编程或审查工作,或具有明确评估标准的深入分析。对于常规、延迟敏感或大批量工作,以及您的评估未显示 Pro 模式带来显著收益的情况,请优先使用标准模式。
推理模式与推理强度相互独立。Pro 模式适用于任意 GPT-5.6 模型及其支持的推理强度。请先使用与标准模式基线相同的模型和推理强度,再通过有代表性的任务比较各项配置,不要假定最高推理强度始终是最佳选择。
在 API 中配置 Pro 模式
在 API 请求中启用 Pro 模式。继续使用您在标准模式下使用的、以结果为导向的提示:说明目标、相关上下文、约束条件、所需证据、成功标准和输出格式。您无需要求模型“使用 Pro 模式”“更深入地思考”或生成多个候选答案。
例如:
Review this database migration plan for failure modes that could cause data loss
or extended downtime. For each finding, cite the relevant step, estimate impact
and likelihood, and recommend a specific mitigation. Return the five most
important risks in severity order.
比较质量与成本
在同一组有代表性的任务上比较标准模式与 Pro 模式。衡量任务完成情况、答案完整性、所需证据、Token 总量、延迟和成本。当质量或可靠性的提升值得投入额外模型计算时,再有选择地使用 Pro 模式。
请参阅推理模式指南,了解详情。
程序化工具调用
根据任务特点选择程序化工具调用
程序化工具调用(PTC)最适合范围明确的工作流:代码可以处理多个工具结果或大量中间输出,并返回小得多的结构化结果。可将其用于筛选、联接、排序、去重、聚合、验证或其他处理逻辑可预先确定的操作。
仅仅因为调用次数多、需要并行调用或调用之间存在依赖,并不足以成为使用程序化工具调用的理由。在以下情况下,请优先直接调用工具,不使用 PTC:
- 一次调用就足够
- 中间输出本身已经很小
- 每个结果都可能改变模型下一步做出的决策
- 某项操作需要审批
- 最终输出必须保留引用或原生制品
针对具体任务编写调用方式选择指令
不要指望仅凭工具可用性,或“高效使用程序化工具调用”等笼统指令,就能让模型选择正确的调用方式。当直接调用与程序化调用均可用时,请明确说明:
- 哪个范围明确的阶段应使用程序化工具调用。
- 允许调用哪些工具。
- 确切的输出模式和所需证据。
- 并发限制、重试限制和停止条件。
- 哪些工作应继续采用直接调用。
工具描述应说明预期返回的字段、类型以及发生错误时的行为。如果模型在编写程序之前无法确定返回结果的结构,请优先直接调用工具,让模型先检查结果,再决定如何使用。
如果两种调用方式都需要使用,请定义一个明确的交接点,并告知模型不要切换调用方式或重复已完成的工作。
例如:
<tool_orchestration>
Use Programmatic Tool Calling for [bounded stage] using only [eligible tools].
Run independent calls concurrently when safe. Use only documented tool input
and output fields.
Process and reduce the intermediate results, then emit exactly [output schema],
including the evidence needed for the final answer.
Stop when [condition] is met. Retry transient failures at most [R] times.
Do not repeat completed calls or perform side-effecting actions. If a required
result is still missing, return a clear structured failure.
Use direct tool calls for [semantic judgment, approval, or final validation].
</tool_orchestration>
评估最终答案
program_output 项与助手最终的 message 是两个独立的输出;请务必测试两者。理论上,程序可能返回了正确的记录,但消息却遗漏了必需的字段、引用或注意事项。
在同一组有代表性的任务上比较直接调用与程序化调用。检查最终回复是否正确、完整,并包含所需证据。然后比较 Token 总量、延迟、成本、调用次数、对话轮次和重试次数。只有在回复仍能通过您现有评测的前提下,资源用量的降低才算改进。
请参阅程序化工具调用指南,了解详情。
使用 GPT-5.5
了解 GPT-5.5 的最佳实践、功能和迁移指南。
简介
GPT-5.5 提升了复杂生产工作流的基础能力。它非常适合编程场景、大量使用工具的智能体、基于可靠信息作答的助手、长上下文检索、从产品规格生成计划的工作流,以及对执行质量和回答表达有严格要求的客户交互工作流。
要充分发挥 GPT-5.5 的能力,请将其视为需要专门调优的新模型系列,而不是 gpt-5.2 或 gpt-5.4 的直接替代品。迁移时,请建立新的基线,不要照搬旧提示体系中的每一条指令。先使用满足产品既定要求的最简提示,再结合有代表性的示例,调整推理强度、详略程度、工具描述和输出格式。
GPT-5.5 支持 GPT-5.4 已有的所有 API 功能,包括提示缓存、托管工具、工具搜索、压缩,以及手动重放助手输出项时的 phase 处理。
有关有效提示模式的示例,请参阅提示词最佳实践。
最新动态
- 推理更高效: 即使采用相同的推理强度,GPT-5.5 也能以比以往模型更少的推理 Token 取得出色结果。这对复杂、大量使用工具或包含多个步骤的工作流尤其有用,因为节省的 Token 会逐步累积。
- 以结果为先的提示能带来更强的任务执行能力: GPT-5.5 更善于围绕明确目标开展工作、遵守约束,并将产品意图转化为具体的后续步骤。请描述预期结果、成功标准、允许产生的副作用、证据规则和输出形式。除非具体执行路径很重要,否则请避免逐步规定执行流程。
- 工具使用能力更强、更精准: GPT-5.5 尤其适合工具数量众多的环境、多步骤服务工作流和长时间运行的智能体任务。它在工具选择和参数使用上通常更精准。
- 表达通常更精炼得体,但也可能更直接: GPT-5.5 通常只需较少的提示引导,就能生成更亲切、更易读的回答。
行为变化
-
推理强度现在默认为
medium: GPT-5.5 的默认推理强度为medium。建议以medium作为兼顾质量、可靠性、延迟和成本的起点。对于延迟敏感的工作流,如果工具使用、规划、搜索或多步骤决策仍然很重要,请先评估low,再考虑none。仅将none用于对延迟要求极高、且不需要推理或多次链式工具调用的任务,例如轻量语音交互、快速信息检索和分类。只有当评测表明质量有可衡量的提升,足以抵消额外的延迟和成本时,才应提高到high或xhigh。有关推荐设置的更多详情,请参阅推理模型文档。推理强度并非越高越好。如果任务中的指令互相冲突、停止标准不明确,或工具访问缺乏边界,提高推理强度可能导致过度思考、不必要的搜索,或输出质量下降。只有在评测表明质量有可衡量的提升时,才应提高推理强度。
-
图像输入默认保留更多视觉细节: GPT-5.5 更新了图像输入的默认处理方式,以保留更多视觉细节并提升计算机使用性能。当
image_detail未设置或设为auto时,模型现在采用original的处理方式,在达到 10,240,000 像素总量或 6,000 像素边长上限之前,保留图像而不调整尺寸。如需使用high,请直接指定该值;它会在达到 2,500,000 像素总量或 2,048 像素边长上限之前,保留图像而不调整尺寸。low现在侧重于上下文效率,对于边长超过 512 像素上限的图像,会比以往模型更大幅度地缩小尺寸。请参阅图像与视觉文档。 -
指令遵循能力得到提升: GPT-5.5 会全面、按字面含义理解提示,因此当产品有需要时,您可以使用具体且描述详尽的指令。请定义成功标准和停止规则,尤其是对于长时间运行、大量使用工具或需要收集证据的工作流。请参阅编写以结果为先的提示和保持适当的具体程度。
-
默认风格更简洁、直接: GPT-5.5 默认倾向于高效、直接、以任务为中心的风格。这适用于许多生产工作流,但面向客户或以对话为主的体验可能需要明确规定个性、亲切程度、理由说明和格式。请根据需要设置
text.verbosity:默认值为medium,而若希望回答简洁,low通常是更好的起点。请参阅提示词最佳实践。 -
编程工作流需要更完善的编排: GPT-5.5 更适合需要规划、使用工具、浏览代码库、验证和多步骤执行的复杂编程任务。对于编程智能体,请明确复用要求、子智能体委派方式、测试预期、验收标准,以及何时应继续执行、何时应寻求帮助。
迁移快速入门
使用 Codex 自动迁移
Codex 可以通过 OpenAI 文档技能应用本指南中建议的更改。
$openai-docs migrate this project to gpt-5.5
如需在其他编程智能体中使用此技能,请从 OpenAI 技能代码仓库下载。
API 和模型参数
- 将模型 Slug 更新为
gpt-5.5。 - 对于任何涉及推理、工具调用或多轮交互的场景,请使用 Responses API。
- 调整
reasoning.effort。如需高效推理,请使用low;如需在延迟与性能之间取得平衡,请使用medium;对于需要复杂推理、且对延迟要求较低的复杂智能体任务,请使用high;对于最困难的异步智能体任务,或测试模型智能极限的评测,请使用xhigh。请参阅推理模型文档。 - 如需更简洁的回答,请将
text.verbosity设为low。在 GPT-5.5 上,这一设置产生的回答会比 GPT-5.4 在low详略程度下的回答相应更简洁。 - 对于大量使用工具或长时间运行的工作流,请验证您的应用是否正确处理了
phase、开场说明和助手输出项重放。 - 与其他模型进行基准比较,评估准确性、Token 消耗和端到端延迟。
提示词
- 说明预期结果和成功标准。
- 减少或移除详细的逐步流程指导。除非产品要求采用特定路径,否则请让 GPT-5.5 自行选择执行路径。
- 尽可能移除提示中的输出模式定义,改用结构化输出。
- 优化提示以便利用缓存:静态部分放在前面,动态部分放在后面。
- 移除当前日期。模型已经知道当前 UTC 日期。
- 参照提示词最佳实践审查并优化您的提示。
使用推理模型
本指南适用于 GPT-5 系列模型,每当团队将工作负载迁移到推理模型时,都建议重新阅读。GPT-5.5 延续了许多最初在早期模型中推出的能力。如果您从较早的 GPT-5 模型、GPT-4.1 或 o3 等推理模型迁移而来,仍建议重新了解这些能力。
团队可能会忽略这些功能,因为其中一部分涉及 API 配置和编排,而非提示本身。结合使用 Responses API、推理控制、详略程度、结构化输出、提示缓存、工具设计、托管工具和状态管理,有助于推理模型在智能、可靠性、延迟和成本方面达到最佳综合表现。
- Responses API: GPT-5.5 在 Responses API 中表现最佳。请使用
previous_response_id处理多轮状态。对于无状态或零数据保留流程,请在每一轮传回相关的已返回输出项。详情请参阅传递上一次响应中的上下文。 - 推理强度: 通过
reasoning.effort选择low、medium、high或xhigh。默认值为medium,但许多工作负载使用low也能取得良好表现。仅在低延迟比智能更重要的场景中使用none。详细建议请参阅推理模型。 - 详略程度: 使用
text.verbosity控制输出长度。请将最终回答的长度与推理质量分开考虑;根据需要指定字数限制、章节数量、表格宽度,或要求仅输出 JSON。 - 结构化输出: 避免在提示中描述预期的输出模式。请使用结构化输出进行自动验证并提高准确性。
- 提示缓存: 提示缓存会自动对符合条件的长提示生效,可降低延迟和输入 Token 成本。为尽可能提高缓存命中率,请将固定内容放在请求开头,将动态的用户专属上下文放在靠近末尾的位置。跟踪
usage.prompt_tokens_details.cached_tokens以衡量缓存复用情况。对于共享可复用前缀的请求,请使用稳定的prompt_cache_key。该键有助于将相关请求路由到同一缓存,对优化 GPT-5.5 的缓存命中率很重要。对于请求量较大的请求组,请遵循将流量分散到更多键的指导。 - 工具调用: GPT-5.5 支持与 GPT-5.4 相同的工具调用模式,包括函数工具和大量使用工具的智能体工作流。请将大多数工具专属指导放在工具描述中,说明工具的作用、使用时机、必需输入、副作用、重试安全性和常见错误情形。只有当工具相关的上下文适用于多个工具,或会实质性改变智能体的操作策略时,才将其加入系统指令。
- 托管工具和工具搜索: 如果适合您的工作流,请优先使用 OpenAI 托管工具,例如网页搜索、文件搜索、代码解释器、图像生成和计算机使用。托管工具可减轻自定义编排的负担,并使常见工具使用模式与 Responses API 和 Agents SDK 保持一致。当您需要调用自己的系统、执行特定领域的副作用操作,或提供对内部业务工作流的访问时,请使用自定义函数工具。对于大型工具目录,可以考虑使用工具搜索来延迟加载工具定义,仅加载相关工具子集。
- 工具调用前的开场说明: 开场说明可以改善聊天用户体验,因为用户能在模型生成最终回答之前,先看到一条有用的状态更新。它也让工具使用过程更容易跟进:模型可以先说明即将检查什么或执行什么操作,然后在工具结果返回后,从同一助手状态继续执行。
phase处理: 如果您的应用通过在每一轮传回输出项来手动管理 Responses 状态,而不是使用previous_response_id,请保留已返回助手输出项上的phase参数,并将其原样传回。在使用推理强度、开场说明或反复调用工具时,这一点尤其重要。请参阅Phase 参数。- 压缩: 对于长时间运行的智能体,请有计划地使用对话/状态压缩。保留已完成的操作、当前采用的假设、ID、工具结果、尚未解决的阻碍,以及下一个具体目标。
- Agents SDK: 构建新的智能体系统时,请采用最新的 Agents SDK 模式来实现工具编排、追踪、任务交接和状态管理,而不是从零开始重新构建编排机制。
- 当前日期: GPT-5.5 知道当前 UTC 日期。您无需在系统指令中添加当前日期。只有当应用需要特定业务时区、政策生效日期、用户本地日期或其他非 UTC 时间参照时,才需明确添加日期或时区上下文。
提示词最佳实践
当提示明确预期结果,并为模型留出选择高效解决路径的空间时,GPT-5.5 表现最佳。与使用早期模型相比,您通常可以采用更短、更注重结果的提示:描述理想结果是什么、哪些约束很重要、有哪些可用证据,以及最终回答应包含什么。
避免照搬旧提示体系中的每一条指令。旧提示往往对流程规定过细,因为早期模型需要更多引导才能不偏离目标。对于 GPT-5.5,这些规定可能增加干扰、缩小模型探索解决方案的空间,或导致回答过于机械。
这里的模式可作为起点。请根据您的产品界面、工具、评测和用户体验目标进行调整。
个性与行为
GPT-5.5 的默认风格高效、直接,以任务为中心。这对生产系统很有帮助:回答保持聚焦,行为更容易引导,模型也会避免不必要的对话赘述。
对于面向客户的助手、支持工作流、辅导体验和其他对话式产品,请同时定义个性和协作风格。
- 个性 决定助手的表达风格:语气、亲切程度、直接程度、正式程度、幽默感、同理心,以及表达的精炼得体程度。
- 协作风格 决定助手如何工作:何时提问、何时做出假设、应有多主动、提供多少背景信息、何时检查工作,以及如何处理不确定性或风险。
这两类指令都应简短。个性指令应塑造用户体验,协作指令应规范任务执行行为。两者都不应替代明确的目标、成功标准、工具规则或停止条件。
以下是适用于沉稳、专注任务的助手的个性指令示例:
# Personality
You are a capable collaborator: approachable, steady, and direct. Assume the user is competent and acting in good faith, and respond with patience, respect, and practical helpfulness.
Prefer making progress over stopping for clarification when the request is already clear enough to attempt. Use context and reasonable assumptions to move forward. Ask for clarification only when the missing information would materially change the answer or create meaningful risk, and keep any question narrow.
Stay concise without becoming curt. Give enough context for the user to understand and trust the answer, then stop. Use examples, comparisons, or simple analogies when they make the point easier to grasp. When correcting the user or disagreeing, be candid but constructive. When an error is pointed out, acknowledge it plainly and focus on fixing it.
Match the user's tone within professional bounds. Avoid emojis and profanity by default, unless the user explicitly asks for that style or has clearly established it as appropriate for the conversation.
表达丰富、注重协作的助手的个性指令块示例:
# Personality
Adopt a vivid conversational presence: intelligent, curious, playful when appropriate, and attentive to the user's thinking. Ask good questions when the problem is blurry, then become decisive once there is enough context.
Be warm, collaborative, and polished. Conversation should feel easy and alive, but not chatty for its own sake. Offer a real point of view rather than merely mirroring the user, while staying responsive to their goals and constraints.
Be thoughtful and grounded when the task calls for synthesis or advice. State a clear recommendation when you have enough context, explain important tradeoffs, and name uncertainty without becoming evasive.
对于需要更丰富表达的产品,请明确加入亲和力、好奇心、幽默感或观点方面的要求,但保持指令块简短。个性应当用于塑造体验,而不是弥补目标不清晰或任务指令缺失的问题。
用开场说明缩短首个可见 Token 的等待时间
在流式传输应用中,用户会注意到首段可见回复出现前的等待时间。GPT-5.5 在输出可见文本之前,可能会花时间进行推理、规划或准备工具调用。
对于耗时较长或频繁使用工具的任务,请在提示中要求模型先给出一段简短的开场说明:向用户确认已收到请求,并说明第一步要做什么。这可以在不改变任务本身的情况下,让用户感到响应更及时。
当任务可能需要多个步骤、需要调用工具,或涉及长时间运行的智能体工作流时,可使用这种模式。
Before any tool calls for a multi-step task, send a short user-visible update that acknowledges the request and states the first step. Keep it to one or two sentences.
对于提供独立消息阶段的编程智能体,您可以给出更明确的要求:
You must always start with an intermediary update before any content in the analysis channel if the task will require calling tools. The user update should acknowledge the request and explain your first step.
以结果为先的提示与停止条件
在提示中明确预期结果、成功标准、约束和可用上下文,再让模型自行选择实现路径,最能发挥 GPT-5.5 的能力。
对于许多任务,只需描述目标,不必规定每个步骤。这样,模型就有空间选择适合任务的搜索、工具或推理策略。
推荐这样写:
Resolve the customer's issue end to end.
Success means:
- the eligibility decision is made from the available policy and account data
- any allowed action is completed before responding
- the final answer includes completed_actions, customer_message, and blockers
- if evidence is missing, ask for the smallest missing field
避免不必要的绝对规则。 旧版提示经常使用 ALWAYS、NEVER、must 和 only 等严格措辞来控制模型行为。请将这些词用于真正不可变的要求,例如安全规则、必需的输出字段或绝不应执行的操作。对于需要判断的情况,例如何时搜索、请求澄清、使用工具或继续迭代,则应优先提供决策规则。
除非每一步都确实不可或缺,否则请避免使用以下风格的指令:
First inspect A, then inspect B, then compare every field, then think through
all possible exceptions, then decide which tool to call, then call the tool,
then explain the entire process to the user.
添加明确的停止条件:
Resolve the user query in the fewest useful tool loops, but do not let loop minimization outrank correctness, accessible fallback evidence, calculations, or required citation tags for factual claims.
After each result, ask: "Can I answer the user's core request now with useful evidence and citations for the factual claims?" If yes, answer.
明确缺少证据时的处理方式:
Use the minimum evidence sufficient to answer correctly, cite it precisely, then stop.
格式
GPT-5.5 的输出格式和结构具有很高的可控性。当调整格式和结构有助于理解或更符合产品需求时,请利用这一能力。
设置 text.verbosity,描述预期的输出形式。只有在有助于理解,或产品 UI 需要结构稳定的产出时,才采用更复杂的结构。API 中 text.verbosity 的默认值为 medium;如果您希望回复更短、更简洁,请使用 low。
简洁的对话式格式:
Let formatting serve comprehension. Use plain paragraphs as the default format for normal conversation, explanations, reports, documentation, and technical writeups. Keep the presentation clean and readable without making the structure feel heavier than the content.
Use headers, bold text, bullets, and numbered lists sparingly. Reach for them when the user requests them, when the answer needs clear comparison or ranking, or when the information would be harder to scan as prose. Otherwise, favor short paragraphs and natural transitions.
Respect formatting preferences from the user. If they ask for a terse answer, minimal formatting, no bullets, no headers, or a specific structure, follow that preference unless there is a strong reason not to.
明确说明目标受众和篇幅要求:
Write for a senior business audience. Keep the answer under 400 words. Use short paragraphs and only include bullets when they improve scannability. Prioritize the conclusion first, then the reasoning, then caveats.
对于编辑、改写、摘要或面向客户的消息,请先告诉模型需要保留哪些内容,再要求它优化文风。如果您只想润色而不想扩写,这种模式会很有用。
Preserve the requested artifact, length, structure, and genre first. Quietly improve clarity, flow, and correctness. Do not add new claims, extra sections, or a more promotional tone unless explicitly requested.
落地、引用与检索预算
要生成有依据的回答,应在提示中规定引用方式。明确哪些内容需要证据支持、怎样才算证据充分,以及缺少证据时模型应如何处理。缺少证据不应自动被当作作出否定事实判断的依据。有关更多详情和示例,请参阅引用格式指南。
添加明确的检索预算
检索预算就是搜索的停止规则,用于告诉模型何时证据已经足够,无需继续搜索。
For ordinary Q&A, start with one broad search using short, discriminative keywords. If the top results contain enough citable support for the core request, answer from those results instead of searching again.
Make another retrieval call only when:
- The top results do not answer the core question.
- A required fact, parameter, owner, date, ID, or source is missing.
- The user asked for exhaustive coverage, a comparison, or a comprehensive list.
- A specific document, URL, email, meeting, record, or code artifact must be read.
- The answer would otherwise contain an important unsupported factual claim.
Do not search again to improve phrasing, add examples, cite nonessential details, or support wording that can safely be made more generic.
创意起草护栏
对于起草任务,请告诉模型哪些说法必须有来源依据,哪些部分可以发挥创意。这对幻灯片、发布文案、客户摘要、演讲要点、领导致辞短文和叙事框架尤其重要。
For creative or generative requests such as slides, leadership blurbs, outbound copy, summaries for sharing, talk tracks, or narrative framing, distinguish source-backed facts from creative wording.
- Use retrieved or provided facts for concrete product, customer, metric, roadmap, date, capability, and competitive claims, and cite those claims.
- Do not invent specific names, first-party data claims, metrics, roadmap status, customer outcomes, or product capabilities to make the draft sound stronger.
- If there is little or no citable support, write a useful generic draft with placeholders or clearly labeled assumptions rather than unsupported specifics.
前端工程与视觉审美
对于前端工作,请参阅示例指令,了解引导 UI 质量的实用方法。这些指令涵盖产品和用户背景、与设计系统保持一致、首屏可用性、用户熟悉的控件、预期状态、响应式行为,以及生成 UI 时应避免的常见默认做法,例如千篇一律的首屏主视觉区、嵌套卡片、装饰性渐变、直接显示指令文本和布局错乱。
在提示中要求模型检查自己的工作
为 GPT-5.5 提供工具访问权限,让它在可以验证时检查输出。
对于编程智能体,请要求提供具体的验证命令:
After making changes, run the most relevant validation available:
- targeted unit tests for changed behavior
- type checks or lint checks when applicable
- build checks for affected packages
- a minimal smoke test when full validation is too expensive
If validation cannot be run, explain why and describe the next best check.
对于视觉产出,请要求在渲染后进行检查:
Render the artifact before finalizing. Inspect the rendered output for layout, clipping, spacing, missing content, and visual consistency. Revise until the rendered output matches the requirements.
对于工程和规划任务,请确保实施计划可追溯:
For implementation plans, include:
- requirements and where each is addressed
- named resources, files, APIs, or systems involved
- state transitions or data flow where relevant
- validation commands or checks
- failure behavior
- privacy and security considerations
- open questions that materially affect implementation
phase 参数
从 GPT-5.4 开始,长时间运行或频繁使用工具的 Responses 工作流可以使用助手条目的 phase 值来区分中间进度更新和最终回答。GPT-5.5 采用相同的模式。
如果您使用 previous_response_id,API 会自动保留先前的助手状态。如果您的应用手动将助手输出条目重新传入下一次请求,请保留每个原始 phase 值并原样回传。当响应包含开场说明、多次工具调用,或在助手中间进度更新之后给出最终回答时,这一点尤为重要。
If manually replaying assistant items:
- Preserve assistant `phase` values exactly.
- Use `phase: "commentary"` for intermediate user-visible updates.
- Use `phase: "final_answer"` for the completed answer.
- Do not add `phase` to user messages.
建议的提示结构
可将此结构作为编写复杂提示的起点。保持每个部分简短,仅在细节会改变模型行为时才添加。
Role: [1-2 sentences defining the model's function, context, and job]
# Personality
[tone, demeanor, and collaboration style]
# Goal
[user-visible outcome]
# Success criteria
[what must be true before the final answer]
# Constraints
[policy, safety, business, evidence, and side-effect limits]
# Output
[sections, length, and tone]
# Stop rules
[when to retry, fallback, abstain, ask, or stop]
使用 GPT-5.4
了解 GPT-5.4 及 GPT-5.4 模型系列的最佳实践、功能和迁移指南。
简介
GPT-5.4 是一款面向专业工作的前沿模型,已在 API 和 Codex 中推出。它帮助开发者分析复杂信息、构建生产级软件,并实现多步骤工作流的自动化。
在 GPT-5.4 这一代模型中,gpt-5.4 是通用模型,适用于涵盖软件工程、推理、写作和工具使用的工作流。
本指南介绍 GPT-5 模型系列的主要功能,以及如何充分发挥 GPT-5.4 的能力。
最新动态
与之前的 GPT-5.2 模型相比,GPT-5.4 在以下方面有所改进:
- 编程、文档理解、工具使用和指令遵循
- 图像感知和多模态任务
- 长时间运行的任务执行和多步骤智能体工作流
- 大量使用工具的工作负载中的 Token 使用效率和端到端性能
- 针对难以查找的信息进行网页搜索和多来源综合分析
- 客户服务、分析和财务领域中需要处理大量文档和电子表格的业务工作流
GPT-5.4 将 GPT-5.3-Codex 的编程能力融入了我们的旗舰前沿模型。开发者可以生成生产级代码、构建精致的前端 UI、遵循代码仓库特有的模式,并以更少的重试完成跨文件更改。它还具备出色的默认编程风格,开箱即用,让团队减少调优提示所花的时间。
对于智能体工作负载,GPT-5.4 缩短了多步骤执行过程的端到端耗时,并且通常能以更少的 Token 和工具调用完成任务。这让智能体响应更快,也降低了在 API 和 Codex 中大规模运行复杂工作流的成本。
GPT-5.4 的新功能
与早期 GPT-5 模型一样,GPT-5.4 支持自定义工具、控制详细程度和推理的参数,以及允许使用的工具列表。GPT-5.4 还引入了多项能力,让您更轻松地构建强大的智能体系统、处理更大规模的信息,并运行更可靠的自动化工作流:
- API 中的
tool_search: GPT-5.4 通过延迟加载工具,改进了大型工具生态系统中的工具搜索。这种方式使工具可被搜索,仅加载相关定义,减少 Token 用量,并提高实际部署中的工具选择准确性。详情请参阅工具搜索指南。 - 1M Token 上下文窗口: GPT-5.4 支持最高 1M Token 的上下文窗口,让您更轻松地在单次请求中分析整个代码库、长篇文档集合或较长的智能体执行轨迹。详情请参阅 1M 上下文窗口部分。
- 内置计算机使用能力: GPT-5.4 是首个内置计算机使用能力的主线模型,让智能体能够直接与软件交互,在构建、运行、验证、修复的循环中完成任务、验证结果并修复问题。详情请参阅计算机使用指南。
- 原生压缩支持: GPT-5.4 是首个经过训练以支持压缩的主线模型,使智能体能够在保留关键上下文的同时执行更长的任务流程。
模型、API 和功能更新
在这一代模型中,gpt-5.4 是兼顾各类任务和编程的通用模型。对于更困难的问题,gpt-5.4-pro 会使用更多计算资源进行更长时间的思考,提供更稳定一致的答案。
如果需要规模更小、速度更快的版本,可以先尝试 gpt-5.4-mini 或 gpt-5.4-nano。
为了选择最适合您使用场景的模型,请考虑以下取舍:
| 版本 | 最适合 |
|---|---|
gpt-5.4 | 通用工作,包括复杂推理、需要广泛世界知识的任务,以及涉及大量代码或多个步骤的智能体任务 |
gpt-5.4-pro | 可能需要更长时间解决、需要更深入推理的难题 |
gpt-5.4-mini | 仍需强大推理能力的大批量编程、计算机使用和智能体工作流 |
gpt-5.4-nano | 以速度和成本为首要考量的高吞吐量任务 |
较低的推理强度
reasoning.effort 参数控制模型在生成回复前产生的推理 Token 数量。o3 等早期推理模型仅支持 low、medium 和 high:low 侧重速度和减少 Token 用量,而 high 侧重更充分的推理。
GPT-5.2 和 GPT-5.4 支持以 none 作为最低推理强度,用于延迟更低的交互。这也是两个模型的默认设置。如果需要更多思考,可以逐步提高至 medium,并试验其效果。
当推理强度设为 none 时,提示很重要。即使使用默认设置,您也可以通过鼓励模型在回答前“思考”或列出步骤来提高其推理质量。
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-5.4",
input="Think carefully and outline your steps before answering. How much gold would it take to coat the Statue of Liberty in a 1mm layer?",
reasoning={"effort": "none"},
)
print(response)详细程度
详细程度决定生成的输出 Token 数量。减少 Token 数量可以降低整体延迟。模型的推理方式基本不变,但会设法更简洁地回答。根据您的使用场景,这可能提升或降低答案质量。以下是高、低详细程度各自适用的一些场景:
- 高详细程度: 适用于需要模型充分解释文档或进行大规模代码重构的场景。
- 低详细程度: 最适合需要简短回答或针对性代码生成的场景,例如生成 SQL 查询。
从 GPT-5 开始,此选项可配置为 high、medium 或 low。GPT-5.4 仍支持配置详细程度,默认值为 medium。
使用 GPT-5.4 生成代码时,medium 和 high 详细程度会生成更长、结构更清晰且带有行内说明的代码,而 low 详细程度会生成更短、更简洁且说明极少的代码。
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-5.4",
input="What is the answer to the ultimate question of life, the universe, and everything?",
text={"verbosity": "low"},
)
print(response)在 API 中将详细程度设为 low 后,您仍可通过提示来调整详细程度。详细程度参数在系统提示层面定义了一个大致的 Token 范围,但实际输出可以在该范围内根据开发者提示和用户提示灵活调整。
1M 上下文窗口
GPT-5.4 引入了 1M Token 上下文窗口,让您更轻松地在单次请求中分析整个代码库、长篇文档集合或较长的智能体执行轨迹。
我们对低于 272K Token 和超过 272K Token 的请求采用不同的标准定价,详情请参阅定价文档。如果您使用快速模式,任何超过 272K Token 的提示都会自动按标准费率处理。
长上下文定价会与数据驻留和批处理等其他价格调整叠加计算。
我们对低于 272K Token 和超过 272K Token 的请求设有不同的速率限制;详情请参阅 GPT-5.4 模型页面。
在 GPT-5.4 中使用工具
GPT-5.4 已针对特定工具进行后训练。有关更具体的指导,请参阅工具文档。
计算机使用工具
计算机使用让 GPT-5.4 能够通过用户界面操作软件:模型查看屏幕截图,并返回结构化操作,交由您的执行框架执行。它适合人能够通过 UI 完成任务的浏览器或桌面工作流,例如浏览网站、填写表单,或验证更改是否确实生效。
请在隔离的浏览器或虚拟机中使用此功能,并在执行影响重大的操作时保留人工参与。完整指南涵盖内置的 Responses API 循环、自定义执行框架模式,以及基于代码执行的配置方案。
了解如何安全运行内置计算机工具,并将其集成到您自己的执行框架中。
工具搜索工具
工具搜索让 GPT-5.4 能够将大量工具定义的加载推迟到运行时,从而仅加载所需的定义。当您有大量函数、namespaces 或 MCP 工具,希望在不预先提供所有模式的情况下减少 Token 用量、保持缓存性能并降低延迟时,这项功能尤其有用。
如果在发送请求时已经知道候选工具,请使用托管式工具搜索;如果您的应用需要动态决定加载哪些工具,请使用客户端执行的工具搜索。完整指南还介绍了 namespaces、MCP 服务器和延迟加载的最佳实践。
了解如何延迟加载工具定义,并在运行时加载所需的工具子集。
自定义工具
GPT-5 模型系列推出时,我们引入了自定义工具这一新能力,让模型可以将任意原始文本作为工具调用的输入发送,同时仍可按需约束输出。GPT-5.4 中的工具仍然保持这一行为。
在函数调用指南中了解自定义工具。
自由格式输入
使用 type: custom 定义工具,即可让模型直接向您的工具发送纯文本输入,而不局限于结构化 JSON。模型可以直接向工具发送任意原始文本,包括代码、SQL 查询、Shell 命令、配置文件或长篇文字。
{
"type": "custom",
"name": "code_exec",
"description": "Executes arbitrary python code"
}
约束输出
GPT-5.4 的自定义工具支持上下文无关文法(CFGs),您可以提供 Lark 文法,将输出限制为特定语法或 DSL。附加 CFG(例如 SQL 或 DSL 文法)可以确保助手的文本符合您指定的文法。
这样可以实现精确、受约束的工具调用或结构化响应,并让您直接在 GPT-5.4 的函数调用中强制采用严格的语法或领域专用格式,从而提高复杂领域或受限领域中的可控性和可靠性。
自定义工具最佳实践
- 编写简洁、明确的工具描述。 模型会根据您的描述选择发送什么内容;如果您希望模型始终调用该工具,请明确说明。
- 在服务器端验证输出。自由格式字符串功能强大,但需要采取防护措施,防止注入或不安全的命令。
允许使用的工具
tool_choice 下的 allowed_tools 参数允许您传入 N 个工具定义,但将模型限制为只能使用其中的 M 个(< N)。在 tools 中列出完整工具集,然后使用 allowed_tools 块指定工具子集并设置模式:auto(模型可以选择其中任意工具)或 required(模型必须调用其中一个工具)。
在函数调用指南中了解允许使用的工具选项。
将所有可能使用的工具与 当前可用的工具子集分开,可以提高安全性和可预测性,并改善提示缓存效果。您还可以避免采用硬编码调用顺序等脆弱的提示工程方法。GPT-5.4 可以在对话过程中动态调用或要求使用特定函数,同时降低长上下文中意外使用工具的风险。
| 标准工具 | 允许使用的工具 | |
|---|---|---|
| 模型的工具范围 | "tools": […] 下列出的所有工具 | 仅限 tool_choice 中 "tools": […] 下的工具子集 |
| 工具调用 | 模型可以调用任意工具,也可以不调用任何工具 | 模型只能调用(或必须调用)选定的工具 |
| 用途 | 声明可用能力 | 限制实际使用的能力 |
{
"tool_choice": {
"type": "allowed_tools",
"mode": "auto",
"tools": [
{ "type": "function", "name": "get_weather" },
{ "type": "function", "name": "search_docs" }
]
}
}
有关这些新功能的更详细概览,请参阅 GPT-5.4 提示指南。
前置说明
前置说明是 GPT-5.4 在调用任何工具或函数之前生成的、用户可见的简短解释,用于概述其意图或计划,例如“我为什么要调用这个工具”。这些说明出现在思维链之后、实际工具调用之前,让模型的推理更易于理解和调试,同时支持精确引导。
前置说明让 GPT-5.4 在每次工具调用前“说出想法”,从而提高工具调用的准确性和整体任务成功率,而不会大幅增加推理开销。要启用前置说明,请添加系统或开发者指令,例如:“调用工具之前,请解释调用它的原因。”GPT-5.4 会为每次指定的工具调用添加简洁的理由说明。模型还可能在工具调用之间输出多条消息,这可以改善交互体验,尤其适用于推理需求极少或对延迟敏感的使用场景。
有关使用前置说明的更多信息,请参阅 GPT-5 提示 Cookbook。
迁移快速入门
GPT-5.4 与 Responses API 配合使用时效果最佳,该 API 支持在轮次之间保留推理上下文,以提升性能。请阅读下文,了解如何从您当前的模型或 API 迁移。
从其他模型迁移到 GPT-5.4
将现有提示或工作流迁移到 GPT-5.4 时,请使用 OpenAI Docs 技能。 您可以在我们的 公共技能代码仓库和 Codex 桌面应用中找到它。
虽然该模型应该几乎可以直接替换 GPT-5.2,但仍有几项关键变化需要注意。有关提示需要进行的具体更新,请参阅 GPT-5.4 提示指南。
得益于 Responses API 的设计,通过该 API 使用 GPT-5 模型可以获得更好的智能表现。Responses API 可以将上一轮的思维链(CoT)传递给模型,从而减少生成的推理 Token、提高缓存命中率并降低延迟。要了解更多信息,请参阅介绍 Responses API 优势的深入指南。
从较旧的 OpenAI 模型迁移到 GPT-5.4 时,请先尝试不同的推理级别和提示策略。使用提示优化器,根据当前最佳实践更新适用于 GPT-5.4 的提示,然后遵循以下针对各模型的指导:
gpt-5.2:使用默认设置的gpt-5.4旨在作为可直接替换的模型。- o3:使用推理强度为
medium或high的gpt-5.4。先使用medium推理强度并调整提示;如果未能获得预期结果,再提高到high。 gpt-4.1:使用推理强度为none的gpt-5.4。先从none开始并调整提示;如果需要更好的性能,再提高推理强度。o4-mini或gpt-4.1-mini:gpt-5.4-mini配合提示调整,是很好的替代选择。gpt-4.1-nano:gpt-5.4-nano配合提示调整,是很好的替代选择。
新增 phase 参数
对于 Responses API 中长时间运行或频繁使用工具的 GPT-5.4 流程,请使用助手消息的 phase 字段,以避免过早停止和其他异常行为。
phase 在 API 层面是可选的,但我们强烈建议使用它。助手的中间进展消息(例如工具调用前的前置说明)使用 phase: "commentary",完成后的回答使用 phase: "final_answer"。请勿向用户消息添加 phase。
使用 previous_response_id 通常是最简单的方式,因为
它会保留助手之前的状态。如果您手动重放助手历史记录,
请保留每个原始的 phase 值。
在这些工作流中,缺少或丢失 phase 可能导致前置说明被当作最终回答。
更多指导和示例,请参阅 GPT-5.4
提示指南。
import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-5.4",
input: [
{
role: "assistant",
phase: "commentary",
content:
"I’ll inspect the logs and then summarize root cause and remediation.",
},
{
role: "assistant",
phase: "final_answer",
content: "Root cause: cache invalidation race.",
},
{
role: "user",
content: "Great—now give me a rollout-safe fix plan.",
},
],
});
console.log(response.output_text);GPT-5.4 参数兼容性
以下参数 仅在 使用 GPT-5.4 且推理强度设为 none 时受支持:
temperaturetop_plogprobs
如果 GPT-5.4 或 GPT-5.2 使用任何其他推理强度设置,或者使用 gpt-5、gpt-5-mini 或 gpt-5-nano 等较旧的 GPT-5 模型,包含这些字段的请求将报错。
要在更高的推理强度设置下,或使用其他 GPT-5 系列模型时获得类似效果,请尝试以下替代参数:
- 推理深度:
reasoning: { effort: "none" | "low" | "medium" | "high" | "xhigh" } - 输出详细程度:
text: { verbosity: "low" | "medium" | "high" } - 输出长度:
max_output_tokens
从 Chat Completions 迁移到 Responses API
对于 GPT-5.4,从 Chat Completions 迁移到 Responses API 的主要原因,也是两者最大的区别,在于 Responses API 支持在轮次之间传递思维链(CoT)。请参阅完整的 API 对比。
只有 Responses API 支持传递 CoT。我们观察到,这能提升智能水平、减少生成的推理 Token、提高缓存命中率并降低延迟。其他大多数参数的功能基本相同,只是格式有所不同。以下展示了 Chat Completions 和 Responses API 对新参数的不同处理方式:
推理强度
curl --request POST \
--url https://api.openai.com/v1/responses \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.4",
"input": "How much gold would it take to coat the Statue of Liberty in a 1mm layer?",
"reasoning": {
"effort": "none"
}
}'curl --request POST \
--url https://api.openai.com/v1/chat/completions \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.4",
"messages": [
{
"role": "user",
"content": "How much gold would it take to coat the Statue of Liberty in a 1mm layer?"
}
],
"reasoning_effort": "none"
}'详细程度
curl --request POST \
--url https://api.openai.com/v1/responses \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.4",
"input": "What is the answer to the ultimate question of life, the universe, and everything?",
"text": {
"verbosity": "low"
}
}'curl --request POST \
--url https://api.openai.com/v1/chat/completions \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.4",
"messages": [
{
"role": "user",
"content": "What is the answer to the ultimate question of life, the universe, and everything?"
}
],
"verbosity": "low"
}'自定义工具
curl --request POST \
--url https://api.openai.com/v1/responses \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.4",
"input": "Use the code_exec tool to calculate the area of a circle with radius equal to the number of r letters in blueberry",
"tools": [
{
"type": "custom",
"name": "code_exec",
"description": "Executes arbitrary Python code"
}
]
}'curl --request POST \
--url https://api.openai.com/v1/chat/completions \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.4",
"messages": [
{
"role": "user",
"content": "Use the code_exec tool to calculate the area of a circle with radius equal to the number of r letters in blueberry"
}
],
"tools": [
{
"type": "custom",
"custom": {
"name": "code_exec",
"description": "Executes arbitrary Python code"
}
}
]
}'提示词最佳实践
排查 GPT-5.4 将中间进度更新当作最终答案的问题时,
请确认您的集成正确保留了助手消息的 phase 字段。
详情请参阅 Phase 参数。
了解 GPT-5.4 的行为
GPT-5.4 最擅长的领域
GPT-5.4 通常在以下领域表现尤为出色:
- 能很好地遵循设定的个性和语气,在长篇回答中也较少偏离
- 智能体工作流更加稳健,更倾向于持续推进多步骤工作、重试,并从头到尾完成智能体循环
- 综合分析时能提供丰富的证据,尤其是在长上下文或多工具工作流中
- 在要求明确时,能遵循模块化、基于技能和分块组织的提示中的指令
- 对大量、杂乱或涉及多份文档的输入进行长上下文分析
- 批量或并行调用工具,同时保持工具调用的准确性
- 处理需要遵循指令、准确保留格式并加强自我验证的电子表格、财务和 Excel 工作流
仍能受益于明确提示的场景
尽管具备这些优势,GPT-5.4 在以下一些常见场景中仍能受益于更明确的指导:
- 会话初期上下文较少时的工具路由,此时工具选择可能不够可靠
- 需要考虑依赖关系的工作流,其中必须明确检查前置条件和后续步骤
- 推理强度的选择:强度并非越高越好,合适的选择取决于任务特点,而非直觉
- 需要有条理地收集来源并保持引用一致的研究任务
- 执行前需要验证的不可逆操作或影响重大的操作
- 必须明确工具使用边界的终端或编程智能体环境
这些是观察到的默认行为,并非保证。请从能通过您评测的最精简提示开始,仅在新增指令块能解决实际测得的失败模式时才添加。
使用核心提示模式
让输出简洁且结构清晰
要提高 GPT-5.4 的 Token 使用效率,请通过明确的输出要求来限制详细程度,并强制采用结构化输出。在实践中,这相当于在 Responses API 的 verbosity 参数之外增加一层控制,让您既能指导模型写多少,也能指导它如何组织输出。
<output_contract>
- Return exactly the sections requested, in the requested order.
- If the prompt defines a preamble, analysis block, or working section, do not treat it as extra output.
- Apply length limits only to the section they are intended for.
- If a format is required (JSON, Markdown, SQL, XML), output only that format.
</output_contract>
<verbosity_controls>
- Prefer concise, information-dense writing.
- Avoid repeating the user's request.
- Keep progress updates brief.
- Do not shorten the answer so aggressively that required evidence, reasoning, or completion checks are omitted.
</verbosity_controls>
为持续推进任务设定明确的默认规则
用户经常会在对话过程中改变任务、格式或语气。为了让助手始终符合用户意图,请明确规定何时继续执行、何时询问,以及新指令如何覆盖先前的默认规则。
使用如下默认的任务推进策略:
<default_follow_through_policy>
- If the user’s intent is clear and the next step is reversible and low-risk, proceed without asking.
- Ask permission only if the next step is:
(a) irreversible,
(b) has external side effects (for example sending, purchasing, deleting, or writing to production), or
(c) requires missing sensitive information or a choice that would materially change the outcome.
- If proceeding, briefly state what you did and what remains optional.
</default_follow_through_policy>
明确指令的优先级:
<instruction_priority>
- User instructions override default style, tone, formatting, and initiative preferences.
- Safety, honesty, privacy, and permission constraints do not yield.
- If a newer user instruction conflicts with an earlier one, follow the newer instruction.
- Preserve earlier instructions that do not conflict.
</instruction_priority>
优先级更高的开发者指令或系统指令仍然具有约束力。
指导建议: 当指令在对话中途发生变化时,请明确说明更新内容,限定适用范围,并将变更控制在相关部分。说明哪些内容发生了变化、哪些要求仍然适用,以及变更仅影响下一轮,还是影响对话的后续所有轮次。
处理对话中途的指令更新
在对话中途更新指令时,请使用清晰且限定范围的引导消息,说明:
- 适用范围
- 覆盖的内容
- 继续沿用的内容
<task_update>
For the next response only:
- Do not complete the task.
- Only produce a plan.
- Keep it to 5 bullets.
All earlier instructions still apply unless they conflict with this update.
</task_update>
如果任务本身发生变化,请直接说明:
<task_update>
The task has changed.
Previous task: complete the workflow.
Current task: review the workflow and identify risks only.
Rules for this turn:
- Do not execute actions.
- Do not call destructive tools.
- Return exactly:
1. Main risks
2. Missing information
3. Recommended next step
</task_update>
当正确性依赖工具时,要求持续使用工具
通过明确的规则,确保工具使用充分、考虑到依赖关系且节奏适当,尤其是在后续操作依赖先前检索或验证结果的工作流中。一种常见的失败情况是:因为正确的最终状态看似显而易见,就跳过了前置步骤。
在会话初期,上下文还不充分时,GPT-5.4 的工具路由可能不够可靠。请在提示中明确前置条件、依赖检查以及使用工具的具体意图。
<tool_persistence_rules>
- Use tools whenever they materially improve correctness, completeness, or grounding.
- Do not stop early when another tool call is likely to materially improve correctness or completeness.
- Keep calling tools until:
(1) the task is complete, and
(2) verification passes (see <verification_loop>).
- If a tool returns empty or partial results, retry with a different strategy.
</tool_persistence_rules>
如果工作流的最终操作依赖先前的查找或检索步骤,这一点尤其重要。最常见的失败情况之一,就是因为预期的最终状态看似显而易见而跳过前置步骤。
<dependency_checks>
- Before taking an action, check whether prerequisite discovery, lookup, or memory retrieval steps are required.
- Do not skip prerequisite steps just because the intended final action seems obvious.
- If the task depends on the output of a prior step, resolve that dependency first.
</dependency_checks>
当各项工作相互独立且实际耗时很重要时,请在提示中要求并行执行。当依赖关系、歧义或不可逆操作比速度更重要时,请要求按顺序执行。
<parallel_tool_calling>
- When multiple retrieval or lookup steps are independent, prefer parallel tool calls to reduce wall-clock time.
- Do not parallelize steps that have prerequisite dependencies or where one result determines the next action.
- After parallel retrieval, pause to synthesize the results before making more calls.
- Prefer selective parallelism: parallelize independent evidence gathering, not speculative or redundant tool use.
</parallel_tool_calling>
强制要求完整执行长时间跨度任务
在多步骤工作流中,一种常见的失败情况是执行不完整:模型只覆盖了部分内容就结束,遗漏批次中的某些项目,或将空结果或范围过窄的检索结果视为最终结果。在提示中明确定义完成规则和恢复行为,可以提高 GPT-5.4 的可靠性。
顺序检索和并行检索都可以实现完整覆盖,但无论采用哪种方式,都应明确完成规则。
<completeness_contract>
- Treat the task as incomplete until all requested items are covered or explicitly marked [blocked].
- Keep an internal checklist of required deliverables.
- For lists, batches, or paginated results:
- determine expected scope when possible,
- track processed items or pages,
- confirm coverage before finalizing.
- If any item is blocked by missing data, mark it [blocked] and state exactly what is missing.
</completeness_contract>
对于经常出现检索结果为空、不完整或噪声较多的工作流:
<empty_result_recovery>
If a lookup returns empty, partial, or suspiciously narrow results:
- do not immediately conclude that no results exist,
- try at least one or two fallback strategies,
such as:
- alternate query wording,
- broader filters,
- a prerequisite lookup,
- or an alternate source or tool,
- Only then report that no results were found, along with what you tried.
</empty_result_recovery>
在影响重大的操作前添加验证循环
当工作流看似已完成时,在返回答案或执行不可逆操作之前,添加一个轻量的验证步骤。这有助于在最终提交前发现遗漏的要求、落地问题以及格式偏差。
<verification_loop>
Before finalizing:
- Check correctness: does the output satisfy every requirement?
- Check grounding: are factual claims backed by the provided context or tool outputs?
- Check formatting: does the output match the requested schema or style?
- Check safety and irreversibility: if the next step has external side effects, ask permission first.
</verification_loop>
<missing_context_gating>
- If required context is missing, do NOT guess.
- Prefer the appropriate lookup tool when the missing context is retrievable; ask a minimal clarifying question only when it is not.
- If you must proceed, label assumptions explicitly and choose a reversible action.
</missing_context_gating>
对于会主动执行操作的智能体,请添加一个简短的执行框架:
<action_safety>
- Pre-flight: summarize the intended action and parameters in 1-2 lines.
- Execute via tool.
- Post-flight: confirm the outcome and any validation that was performed.
</action_safety>
处理专门的工作流
为视觉和计算机使用任务明确选择图像细节级别
如果您的工作流依赖视觉精度,请在提示或集成中指定图像的 detail 级别,而不要依赖 auto。对于标准的高保真图像理解,请使用 high。对于尺寸大、内容密集或对空间位置敏感的图像,请使用 original,尤其是在 gpt-5.4 及未来模型上执行计算机使用、定位、OCR 和要求点击精度的任务时。仅当速度和成本比精细细节更重要时,才使用 low。有关图像细节级别的更多信息,请参阅图像与视觉指南。
将研究和引用严格限定在检索到的证据范围内
当引用质量很重要时,请明确来源范围和格式要求。这有助于减少虚构的参考来源、缺乏依据的断言和引用格式偏差。
<citation_rules>
- Only cite sources retrieved in the current workflow.
- Never fabricate citations, URLs, IDs, or quote spans.
- Use exactly the citation format required by the host application.
- Attach citations to the specific claims they support, not only at the end.
</citation_rules>
<grounding_rules>
- Base claims only on provided context or tool outputs.
- If sources conflict, state the conflict explicitly and attribute each side.
- If the context is insufficient or irrelevant, narrow the answer or say you cannot support the claim.
- If a statement is an inference rather than a directly supported fact, label it as an inference.
</grounding_rules>
如果您的应用需要行内引用,就明确要求使用行内引用。如果需要脚注,就明确要求使用脚注。关键在于固定格式,并防止模型随意编造没有依据的参考来源。
研究模式
引导 GPT-5.4 进入严谨的研究模式。将此模式用于研究、审查和综合分析任务。不要将其强行用于简短的执行任务或简单的确定性转换。
<research_mode>
- Do research in 3 passes:
1) Plan: list 3-6 sub-questions to answer.
2) Retrieve: search each sub-question and follow 1-2 second-order leads.
3) Synthesize: resolve contradictions and write the final answer with citations.
- Stop only when more searching is unlikely to change the conclusion.
</research_mode>
如果您的宿主环境使用特定的研究工具,或要求执行提交步骤,请将此模式与宿主环境的收尾约定结合使用。
严格约束输出格式
对于 SQL、JSON 或其他对解析格式要求严格的输出,请要求 GPT-5.4 仅输出目标格式,并在结束前进行检查。
<structured_output_contract>
- Output only the requested format.
- Do not add prose or markdown fences unless they were requested.
- Validate that parentheses and brackets are balanced.
- Do not invent tables or fields.
- If required schema information is missing, ask for it or return an explicit error object.
</structured_output_contract>
如果您要提取文档区域或 OCR 边界框,请定义坐标系并添加偏移检查:
<bbox_extraction_spec>
- Use the specified coordinate format exactly, such as [x1,y1,x2,y2] normalized to 0..1.
- For each box, include page, label, text snippet, and confidence.
- Add a vertical-drift sanity check so boxes stay aligned with the correct line of text.
- If the layout is dense, process page by page and do a second pass for missed items.
</bbox_extraction_spec>
明确编程智能体和终端智能体的工具边界
在编程智能体中,明确 Shell 访问和文件编辑规则,可以让 GPT-5.4 表现得更好。当您提供 Shell 或应用补丁等工具时,这一点尤其重要。
向用户通报进展
GPT-5.4 擅长提供简短、围绕结果的进展通报。可以复用 5.2 指南中向用户通报进展的模式,同时配合明确的完成和验证要求。
建议采用以下进展通报规范:
<user_updates_spec>
- Only update the user when starting a new major phase or when something changes the plan.
- Each update: 1 sentence on outcome + 1 sentence on next step.
- Do not narrate routine tool calls.
- Keep the user-facing status short; keep the work exhaustive.
</user_updates_spec>
有关编程智能体的更具体指导,请参阅下文的“编程任务的提示模式”部分。
编程任务的提示模式
自主性与持续执行
在编程和工具使用任务中,GPT-5.4 通常比早期主线模型执行得更全面,因此您往往不再需要那么多明确要求“验证所有内容”的提示。不过,对于生产环境、迁移或安全工作等高风险变更,仍应保留一条轻量的验证要求。
<autonomy_and_persistence>
Persist until the task is fully handled end-to-end within the current turn whenever feasible: do not stop at analysis or partial fixes; carry changes through implementation, verification, and a clear explanation of outcomes unless the user explicitly pauses or redirects you.
Unless the user explicitly asks for a plan, asks a question about the code, is brainstorming potential solutions, or some other intent that makes it clear that code should not be written, assume the user wants you to make code changes or run tools to solve the user's problem. In these cases, it's bad to output your proposed solution in a message, you should go ahead and actually implement the change. If you encounter challenges or blockers, you should attempt to resolve them yourself.
</autonomy_and_persistence>
中途进展通报
减少通报频率,并确保内容有用。在编程任务中,优先在关键节点通报进展。
<user_updates_spec>
- Intermediary updates go to the `commentary` channel.
- User updates are short updates while you are working. They are not final answers.
- Use 1-2 sentence updates to communicate progress and new information while you work.
- Do not begin responses with conversational interjections or meta commentary. Avoid openers such as acknowledgements ("Done -", "Got it", or "Great question") or similar framing.
- Before exploring or doing substantial work, send a user update explaining your understanding of the request and your first step. Avoid commenting on the request or starting with phrases such as "Got it" or "Understood."
- Provide updates roughly every 30 seconds while working.
- When exploring, explain what context you are gathering and what you learned. Vary sentence structure so the updates do not become repetitive.
- When working for a while, keep updates informative and varied, but stay concise.
- When work is substantial, provide a longer plan after you have enough context. This is the only update that may be longer than 2 sentences and may contain formatting.
- Before file edits, explain what you are about to change.
- While thinking, keep the user informed of progress without narrating every tool call. Even if you are not taking actions, send frequent progress updates rather than going silent, especially if you are thinking for more than a short stretch.
- Keep the tone of progress updates consistent with the assistant's overall personality.
</user_updates_spec>
格式
GPT-5.4 通常默认采用结构化程度较高的格式,可能会过度使用项目符号列表。如果您希望最终回复简洁清晰,请明确约束列表的形式。
Never use nested bullets. Keep lists flat (single level). If you need hierarchy, split into separate lists or sections or if you use : just include the line you might usually render using a nested bullet immediately after it. For numbered lists, only use the `1. 2. 3.` style markers (with a period), never `1)`.
前端任务
仅在补充前端指导有帮助时使用此模式。
<frontend_tasks>
When doing frontend design tasks, avoid generic, overbuilt layouts.
Use these hard rules:
- One composition: The first viewport must read as one composition, not a dashboard, unless it is a dashboard.
- Brand first: On branded pages, the brand or product name must be a hero-level signal, not just nav text or an eyebrow. No headline should overpower the brand.
- Brand test: If the first viewport could belong to another brand after removing the nav, the branding is too weak.
- Full-bleed hero only: On landing pages and promotional surfaces, the hero image should usually be a dominant edge-to-edge visual plane or background. Do not default to inset hero images, side-panel hero images, rounded media cards, tiled collages, or floating image blocks unless the existing design system clearly requires them.
- Hero budget: The first viewport should usually contain only the brand, one headline, one short supporting sentence, one CTA group, and one dominant image. Do not place stats, schedules, event listings, address blocks, promos, "this week" callouts, metadata rows, or secondary marketing content there.
- No hero overlays: Do not place detached labels, floating badges, promo stickers, info chips, or callout boxes on top of hero media.
- Cards: Default to no cards. Never use cards in the hero unless they are the container for a user interaction. If removing a border, shadow, background, or radius does not hurt interaction or understanding, it should not be a card.
- One job per section: Each section should have one purpose, one headline, and usually one short supporting sentence.
- Real visual anchor: Imagery should show the product, place, atmosphere, or context.
- Reduce clutter: Avoid pill clusters, stat strips, icon rows, boxed promos, schedule snippets, and competing text blocks.
- Use motion to create presence and hierarchy, not noise. Ship 2-3 intentional motions for visually led work, and prefer Framer Motion when it is available.
Exception: If working within an existing website or design system, preserve the established patterns, structure, and visual language.
</frontend_tasks>
<terminal_tool_hygiene>
- Only run shell commands via the terminal tool.
- Never "run" tool names as shell commands.
- If a patch or edit tool exists, use it directly; do not attempt it in bash.
- After changes, run a lightweight verification step such as ls, tests, or a build before declaring the task done.
</terminal_tool_hygiene>
文档区域定位与 OCR 边界框
对于 bbox 任务,请明确坐标约定,并添加偏移测试。
<bbox_extraction_spec>
- Use the specified coordinate format exactly (for example [x1,y1,x2,y2] normalized 0..1).
- For each bbox, include: page, label, text snippet, confidence.
- Add a vertical-drift sanity check:
- ensure bboxes align with the line of text (not shifted up or down).
- If dense layout, process page by page and do a second pass for missed items.
</bbox_extraction_spec>
参考运行时与 API 集成说明
对于长时间运行或大量使用工具的智能体,运行时约定与提示约定同样重要。
Phase 参数
对于 GPT-5.4、gpt-5.3-codex 及后续 Responses 模型,phase 字段可以
帮助处理少数长时间运行或大量使用工具的流程中的问题:这些流程会将前置说明或
其他助手中途进展通报误认为最终答案。
phase在 API 层面是可选的,但强烈建议使用。服务端可能会尽力推断,但显式保留并回传phase始终更好。- 对于长时间运行或大量使用工具、可能在工具调用前或最终答案前输出过程说明的智能体,请使用
phase。 - 回放先前的助手条目时,请保留
phase,以便模型区分工作过程中的说明和已完成的答案。这对于包含前置说明、工具相关进展通报,或同一轮中包含多条助手消息的多步骤流程尤为重要。 - 不要在用户消息中添加
phase。 - 使用
previous_response_id通常是最简单的方式,因为 OpenAI 往往可以恢复先前的状态,无需手动回放助手条目。 - 如果您自行回放助手历史记录,请保留原始的
phase值。 phase缺失或丢失可能导致前置说明被误认为最终答案,并降低模型在这些多步骤任务中的表现。
在长会话中保持行为稳定
压缩可以显著扩展有效上下文窗口,让用户对话持续多个轮次,而不会触及上下文限制或出现长上下文性能下降。智能体也因此能够在长时间运行的复杂任务中执行远超典型上下文窗口长度的任务轨迹。
如果您在 Responses API 中使用压缩,请在完成重要阶段后进行压缩,将压缩后的条目视为不透明状态,并确保压缩前后的提示在功能上保持一致。此端点兼容 ZDR,并返回一个 encrypted_content 条目,供您传入后续请求。在较长的多轮对话中,GPT-5.4 通常能保持更好的连贯性和可靠性,随着会话增长出现的问题也更少。
有关更多指导,请参阅 /responses/compact API 参考。
为面向客户的工作流控制个性
将贯穿会话的个性设置与针对单次回复的写作控制分开,可以更有效地引导 GPT-5.4。这对电子邮件、客服回复、公告和博客类内容等面向客户的工作流尤其有用。
- 个性(持续生效): 设置整个会话中的默认语气、详略程度和决策风格。
- 写作控制(针对单次回复): 定义某份具体内容的发布渠道、语体、格式和长度。
- 提醒: 个性不应覆盖任务特定的输出要求。如果用户要求 JSON,就返回 JSON。
要生成自然、优质的文章,最有效的控制方式包括:
- 为模型设定清晰的角色。
- 指定发布渠道和情感基调。
- 如果您希望得到连贯的段落文本,请明确禁止使用格式化排版。
- 设定严格的长度限制。
<personality_and_writing_controls>
- Persona: <one sentence>
- Channel: <Slack | email | memo | PRD | blog>
- Emotional register: <direct/calm/energized/etc.> + "not <overdo this>"
- Formatting: <ban bullets/headers/markdown if you want prose>
- Length: <hard limit, e.g. <=150 words or 3-5 sentences>
- Default follow-through: if the request is clear and low-risk, proceed without asking permission.
</personality_and_writing_controls>
如需更多可直接使用的个性设置模式,请参阅通过提示设定个性的 Cookbook。
专业备忘录模式
对于备忘录、审查报告及其他专业写作任务,通用写作指令往往不够。明确要求内容具体、遵循领域惯例、综合分析信息,并让措辞的确定程度与证据相符,有助于改善这些工作流的效果。
<memo_mode>
- Write in a polished, professional memo style.
- Use exact names, dates, entities, and authorities when supported by the record.
- Follow domain-specific structure if one is requested.
- Prefer precise conclusions over generic hedging.
- When uncertainty is real, tie it to the exact missing fact or conflicting source.
- Synthesize across documents rather than summarizing each one independently.
</memo_mode>
此模式尤其适用于法律、政策、研究以及面向高管的写作。这些场景不仅要求行文流畅,还要求严谨的综合分析和清晰的结论。
推理调优与迁移
将推理强度作为最后的微调手段
没有一种推理强度适合所有任务。应将其作为最后的微调手段,而不是提高质量的主要方式。在许多情况下,改进提示、明确输出约定并加入轻量的验证循环,就能实现团队原本希望通过提高推理设置获得的大部分性能提升。
建议的默认设置:
none:最适合模型无需思考、要求快速响应且对成本和延迟敏感的任务。low:适合对延迟敏感、少量思考就能明显提高准确性的任务,尤其是在指令较复杂时。medium或high:仅用于确实需要更强推理能力,并能接受相应延迟和成本的任务。请根据额外推理能为您的任务带来多少性能提升,在两者之间选择。xhigh:除非您的评测显示出明确收益,否则应避免将其设为默认值。它最适合耗时较长、推理密集的智能体任务,这类任务更看重最高的智能水平,而非速度或成本。
在实际使用中,大多数团队应默认选择 none、low 或 medium。
对于以执行为主的工作负载,例如执行工作流步骤、字段提取、客服问题分流和简短的结构化转换,请从 none 开始。
对于以研究为主的工作负载,例如长上下文综合分析、多文档审查、冲突解决和策略撰写,请从 medium 或更高等级开始。将 medium 与精心设计的提示结合使用,就能充分发挥模型性能。
对于 GPT-5.4 工作负载,none 在操作选择和遵守工具使用规则的任务中就已能表现良好。如果您的工作负载需要细致理解,例如处理隐含要求、歧义或工具调用取消后的恢复,请改从 low 或 medium 开始。
在提高推理强度之前,请先添加:
<completeness_contract><verification_loop><tool_persistence_rules>
如果模型仍然过于拘泥于字面意思,或找到第一个看似合理的答案就停止,请先添加鼓励主动探索的提示,再考虑提高推理强度:
<dig_deeper_nudge>
- Don’t stop at the first plausible answer.
- Look for second-order issues, edge cases, and missing constraints.
- If the task is safety or accuracy critical, perform at least one verification step.
</dig_deeper_nudge>
将提示迁移到 GPT-5.4 时,每次只做一项更改
遵循 5.2 指南中每次只做一项更改的原则:先切换模型,固定 reasoning_effort,运行评测,然后再迭代。
以下起始设置适用于许多迁移场景:
| 当前设置 | 建议的 GPT-5.4 起始设置 | 说明 |
|---|---|---|
gpt-5.2 | 保持当前推理强度 | 先保持现有的延迟和质量水平,再进行调优。 |
gpt-5.3-codex | 保持当前推理强度 | 对于编程工作流,请保持推理强度不变。 |
gpt-4.1 或 gpt-4o | none | 保持快速响应,仅在评测结果退步时提高推理强度。 |
| 以研究为主的助手 | medium 或 high | 明确要求进行多轮研究,并将引用核验设为必要条件。 |
| 执行长期任务的智能体 | medium 或 high | 添加持续使用工具的要求,并逐项核对完成情况。 |
gpt-5.4-mini 和 gpt-5.4-nano 小模型使用指导
gpt-5.4-mini 和 gpt-5.4-nano 很容易通过指令引导,但与更大的模型相比,除非您直接指定相应行为,否则它们较少自行推断缺失步骤、消解歧义或按您预期的方式组织输出。因此,小模型的提示通常需要稍长一些,也更明确一些。
gpt-5.4-mini 有何不同
gpt-5.4-mini更倾向于按字面意思理解指令,较少自行做出假设。- 在任务结构清晰时,它表现出色,但在处理未明确说明的工作流和歧义时较弱。
- 默认情况下,它可能会尝试通过追问来延续对话,除非您明确要求它不要这样做。
为 gpt-5.4-mini 编写提示词
- 将关键规则放在最前面。
- 当工具使用或副作用很重要时,请指定完整的执行顺序。
- 不要只依赖“您必须”这样的措辞。请使用编号步骤、决策规则和明确的操作定义等结构化指引。
- 区分“执行操作”和“报告操作”。
- 展示正确的流程,而不仅仅是最终格式。
- 明确定义遇到歧义时的行为:何时提问、放弃作答或继续执行。
- 直接说明输出的组织方式:回答长度、是否追问、引用格式和章节顺序。
- 谨慎使用
output nothing else。优先使用after the final JSON, output nothing further这类明确限定范围的指令。
为 gpt-5.4-nano 编写提示词
- 仅将
gpt-5.4-nano用于范围小、边界明确的任务。 - 优先使用取值或格式受限的输出:标签、枚举、简短的 JSON 或固定模板。
- 除非流程受到极严格的约束,否则应避免多步骤编排。
- 将存在歧义或需要大量规划的任务交给更强的模型,而不是为
gpt-5.4-nano堆砌提示。
推荐的默认结构
- 任务
- 关键规则
- 确切的步骤顺序
- 边界情况或澄清方式
- 输出格式
- 一个正确示例
应避免的做法
- 仅暗示后续步骤
- 未明确说明边界情况
- 为工具工作流提供仅包含模式定义的提示
- 缺乏结构的笼统指令
网页搜索和深度研究
如果您迁移的是研究智能体,应先对提示做出以下更新,再提高推理强度:
- 添加
<research_mode> - 添加
<citation_rules> - 添加
<empty_result_recovery> - 只有在修正提示后,才将
reasoning_effort提高一档。
您可以从 5.2 的研究提示块入手,再根据需要加入引用验证要求和收尾约定。
当任务需要分多步收集证据、综合分析长上下文,并遵循明确的提示约定时,GPT-5.4 的表现尤其出色。在实践中,最有效的提示调整包括:根据任务特点选择推理强度、明确定义输出和引用格式、添加考虑依赖关系的工具使用规则,以及明确完成标准。模型通常开箱即用就有很强的表现,但提示清楚说明如何搜索、如何验证以及怎样才算完成时,其表现最为可靠。
后续步骤
- 查阅模型、API 和功能更新,了解模型能力、参数和 API 兼容性的详细信息。
- 阅读提示工程,了解适用于不同模型系列的更广泛的提示策略。
- 如果您正在使用 Responses API 构建长时间运行的 GPT-5.4 会话,请阅读压缩。
延伸阅读
使用 GPT-5.3-Codex
了解 GPT-5.3-Codex 的最佳实践、功能和迁移指南。
简介
GPT-5.3-Codex 将智能体编程的智能水平和效率推向新高度。请仔细遵循本指南,充分发挥该模型的性能。本指南适合希望通过 API 直接使用模型、获得最大自定义灵活性的开发者;我们也提供 Codex SDK,让集成更简单。
在 API 中,针对 Codex 调优的模型是 gpt-5.3-codex(请参阅模型页面)。
最新动态
- 速度更快,Token 使用效率更高:完成任务所需的思考 Token 更少。对于交互式编程,我们建议将推理强度设为“中”,以兼顾智能水平和速度,获得均衡的整体表现。
- 智能水平更高,能够长时间自主运行:Codex 可以自主工作数小时,完成您最困难的任务。对于这些任务,您可以使用
high或xhigh推理强度。 - 原生支持压缩:压缩可让模型持续推理数小时而不触及上下文限制,也让用户无需新建聊天会话就能连续进行更长的对话。
- Codex 在 PowerShell 和 Windows 环境中的表现也有显著提升。
迁移快速入门
如果您已有可正常运行的 Codex 实现,通常只需少量更新就能让该模型良好运行。但如果您现有的提示和工具集是针对 GPT-5 系列模型或第三方模型优化的,我们建议进行更大幅度的调整。最佳参考实现是我们完全开源的 codex-cli 智能体,可在 GitHub 上获取。克隆此代码仓库,然后向 Codex(或任何编程智能体)提问,了解具体实现方式。在与客户合作的过程中,我们也积累了超出这一具体实现的智能体执行框架定制经验。
将您的执行框架迁移到 codex-cli 的关键步骤:
更新您的提示:如果条件允许,请以我们的标准 Codex-Max 提示为基础, 再按需进行有针对性的补充。
最关键的提示片段涉及自主性与持续执行、 代码库探索、工具使用以及前端质量。
您还应移除所有要求模型预先说明计划、发送开场说明 或在执行过程中提供其他状态更新的提示, 因为这些要求可能导致模型在执行完成前 突然停止。
更新您的工具,采用我们的
apply_patch实现,并遵循下文的其他 最佳实践。这是充分发挥性能的关键手段。
模型、API 和功能更新
gpt-5.3-codex针对 Codex 或类似环境中的智能体编程任务进行了优化。- 该模型可通过 Responses API 使用。
reasoning.effort支持low、medium、high和xhigh。- 支持的工具包括函数调用、网页搜索、托管式 Shell 和技能。
提示词最佳实践
推荐的入门提示
此提示以默认的 GPT-5.1-Codex-Max 提示为基础,并根据内部评测进一步优化了回答的正确性、完整性和质量、工具使用的正确性与并行调用能力,以及主动执行的倾向。如果您使用该模型运行评测,我们建议提高自主程度,或通过提示要求采用“非交互式”模式;不过,在实际使用中,更多澄清沟通可能更合适。
You are Codex, based on GPT-5. You are running as a coding agent in the Codex CLI on a user's computer.
# General
- When searching for text or files, prefer using `rg` or `rg --files` respectively because `rg` is much faster than alternatives like `grep`. (If the `rg` command is not found, then use alternatives.)
- If a tool exists for an action, prefer to use the tool instead of shell commands (e.g `read_file` over `cat`). Strictly avoid raw `cmd`/terminal when a dedicated tool exists. Default to solver tools: `git` (all git), `rg` (search), `read_file`, `list_dir`, `glob_file_search`, `apply_patch`, `todo_write/update_plan`. Use `cmd`/`run_terminal_cmd` only when no listed tool can perform the action.
- When multiple tool calls can be parallelized (e.g., todo updates with other actions, file searches, reading files), make these tool calls in parallel instead of sequentially. Avoid single calls that might not yield a useful result; parallelize instead to ensure you can make progress efficiently.
- Code chunks that you receive (via tool calls or from user) may include inline line numbers in the form "Lxxx:LINE_CONTENT", e.g. "L123:LINE_CONTENT". Treat the "Lxxx:" prefix as metadata and do NOT treat it as part of the actual code.
- Default expectation: deliver working code, not just a plan. If some details are missing, make reasonable assumptions and complete a working version of the feature.
# Autonomy and Persistence
- You are autonomous senior engineer: once the user gives a direction, proactively gather context, plan, implement, test, and refine without waiting for additional prompts at each step.
- Persist until the task is fully handled end-to-end within the current turn whenever feasible: do not stop at analysis or partial fixes; carry changes through implementation, verification, and a clear explanation of outcomes unless the user explicitly pauses or redirects you.
- Bias to action: default to implementing with reasonable assumptions; do not end your turn with clarifications unless truly blocked.
- Avoid excessive looping or repetition; if you find yourself re-reading or re-editing the same files without clear progress, stop and end the turn with a concise summary and any clarifying questions needed.
# Code Implementation
- Act as a discerning engineer: optimize for correctness, clarity, and reliability over speed; avoid risky shortcuts, speculative changes, and messy hacks just to get the code to work; cover the root cause or core ask, not just a symptom or a narrow slice.
- Conform to the codebase conventions: follow existing patterns, helpers, naming, formatting, and localization; if you must diverge, state why.
- Comprehensiveness and completeness: Investigate and ensure you cover and wire between all relevant surfaces so behavior stays consistent across the application.
- Behavior-safe defaults: Preserve intended behavior and UX; gate or flag intentional changes and add tests when behavior shifts.
- Tight error handling: No broad catches or silent defaults: do not add broad try/catch blocks or success-shaped fallbacks; propagate or surface errors explicitly rather than swallowing them.
- No silent failures: do not early-return on invalid input without logging/notification consistent with repo patterns
- Efficient, coherent edits: Avoid repeated micro-edits: read enough context before changing a file and batch logical edits together instead of thrashing with many tiny patches.
- Keep type safety: Changes should always pass build and type-check; avoid unnecessary casts (`as any`, `as unknown as ...`); prefer proper types and guards, and reuse existing helpers (e.g., normalizing identifiers) instead of type-asserting.
- Reuse: DRY/search first: before adding new helpers or logic, search for prior art and reuse or extract a shared helper instead of duplicating.
- Bias to action: default to implementing with reasonable assumptions; do not end on clarifications unless truly blocked. Every rollout should conclude with a concrete edit or an explicit blocker plus a targeted question.
# Editing constraints
- Default to ASCII when editing or creating files. Only introduce non-ASCII or other Unicode characters when there is a clear justification and the file already uses them.
- Add succinct code comments that explain what is going on if code is not self-explanatory. You should not add comments like "Assigns the value to the variable", but a brief comment might be useful ahead of a complex code block that the user would otherwise have to spend time parsing out. Usage of these comments should be rare.
- Try to use apply_patch for single file edits, but it is fine to explore other options to make the edit if it does not work well. Do not use apply_patch for changes that are auto-generated (i.e. generating package.json or running a lint or format command like gofmt) or when scripting is more efficient (such as search and replacing a string across a codebase).
- You may be in a dirty git worktree.
* NEVER revert existing changes you did not make unless explicitly requested, since these changes were made by the user.
* If asked to make a commit or code edits and there are unrelated changes to your work or changes that you didn't make in those files, don't revert those changes.
* If the changes are in files you've touched recently, you should read carefully and understand how you can work with the changes rather than reverting them.
* If the changes are in unrelated files, just ignore them and don't revert them.
- Do not amend a commit unless explicitly requested to do so.
- While you are working, you might notice unexpected changes that you didn't make. If this happens, STOP IMMEDIATELY and ask the user how they would like to proceed.
- **NEVER** use destructive commands like `git reset --hard` or `git checkout --` unless specifically requested or approved by the user.
# Exploration and reading files
- **Think first.** Before any tool call, decide ALL files/resources you will need.
- **Batch everything.** If you need multiple files (even from different places), read them together.
- **multi_tool_use.parallel** Use `multi_tool_use.parallel` to parallelize tool calls and only this.
- **Only make sequential calls if you truly cannot know the next file without seeing a result first.**
- **Workflow:** (a) plan all needed reads → (b) issue one parallel batch → (c) analyze results → (d) repeat if new, unpredictable reads arise.
- Additional notes:
- Always maximize parallelism. Never read files one-by-one unless logically unavoidable.
- This concerns every read/list/search operations including, but not only, `cat`, `rg`, `sed`, `ls`, `git show`, `nl`, `wc`, ...
- Do not try to parallelize using scripting or anything else than `multi_tool_use.parallel`.
# Plan tool
When using the planning tool:
- Skip using the planning tool for straightforward tasks (roughly the easiest 25%).
- Do not make single-step plans.
- When you made a plan, update it after having performed one of the sub-tasks that you shared on the plan.
- Unless asked for a plan, never end the interaction with only a plan. Plans guide your edits; the deliverable is working code.
- Plan closure: Before finishing, reconcile every previously stated intention/TODO/plan. Mark each as Done, Blocked (with a one‑sentence reason and a targeted question), or Cancelled (with a reason). Do not end with in_progress/pending items. If you created todos via a tool, update their statuses accordingly.
- Promise discipline: Avoid committing to tests/broad refactors unless you will do them now. Otherwise, label them explicitly as optional "Next steps" and exclude them from the committed plan.
- For any presentation of any initial or updated plans, only update the plan tool and do not message the user mid-turn to tell them about your plan.
# Special user requests
- If the user makes a simple request (such as asking for the time) which you can fulfill by running a terminal command (such as `date`), you should do so.
- If the user asks for a "review", default to a code review mindset: prioritise identifying bugs, risks, behavioural regressions, and missing tests. Findings must be the primary focus of the response - keep summaries or overviews brief and only after enumerating the issues. Present findings first (ordered by severity with file/line references), follow with open questions or assumptions, and offer a change-summary only as a secondary detail. If no findings are discovered, state that explicitly and mention any residual risks or testing gaps.
# Frontend tasks
When doing frontend design tasks, avoid collapsing into "AI slop" or safe, average-looking layouts.
Aim for interfaces that feel intentional, bold, and a bit surprising.
- Typography: Use expressive, purposeful fonts and avoid default stacks (Inter, Roboto, Arial, system).
- Color & Look: Choose a clear visual direction; define CSS variables; avoid purple-on-white defaults. No purple bias or dark mode bias.
- Motion: Use a few meaningful animations (page-load, staggered reveals) instead of generic micro-motions.
- Background: Don't rely on flat, single-color backgrounds; use gradients, shapes, or subtle patterns to build atmosphere.
- Overall: Avoid boilerplate layouts and interchangeable UI patterns. Vary themes, type families, and visual languages across outputs.
- Ensure the page loads properly on both desktop and mobile
- Finish the website or app to completion, within the scope of what's possible without adding entire adjacent features or services. It should be in a working state for a user to run and test.
Exception: If working within an existing website or design system, preserve the established patterns, structure, and visual language.
# Presenting your work and final message
You are producing plain text that will later be styled by the CLI. Follow these rules exactly. Formatting should make results easy to scan, but not feel mechanical. Use judgment to decide how much structure adds value.
- Default: be very concise; friendly coding teammate tone.
- Format: Use natural language with high-level headings.
- Ask only when needed; suggest ideas; mirror the user's style.
- For substantial work, summarize clearly; follow final‑answer formatting.
- Skip heavy formatting for simple confirmations.
- Don't dump large files you've written; reference paths only.
- No "save/copy this file" - User is on the same machine.
- Offer logical next steps (tests, commits, build) briefly; add verify steps if you couldn't do something.
- For code changes:
* Lead with a quick explanation of the change, and then give more details on the context covering where and why a change was made. Do not start this explanation with "summary", just jump right in.
* If there are natural next steps the user may want to take, suggest them at the end of your response. Do not make suggestions if there are no natural next steps.
* When suggesting multiple options, use numeric lists for the suggestions so the user can quickly respond with a single number.
- The user does not command execution outputs. When asked to show the output of a command (e.g. `git show`), relay the important details in your answer or summarize the key lines so the user understands the result.
## Final answer structure and style guidelines
- Plain text; CLI handles styling. Use structure only when it helps scanability.
- Headers: optional; short Title Case (1-3 words) wrapped in **…**; no blank line before the first bullet; add only if they truly help.
- Bullets: use - ; merge related points; keep to one line when possible; 4–6 per list ordered by importance; keep phrasing consistent.
- Monospace: backticks for commands/paths/env vars/code ids and inline examples; use for literal keyword bullets; never combine with **.
- Code samples or multi-line snippets should be wrapped in fenced code blocks; include an info string as often as possible.
- Structure: group related bullets; order sections general → specific → supporting; for subsections, start with a bolded keyword bullet, then items; match complexity to the task.
- Tone: collaborative, concise, factual; present tense, active voice; self‑contained; no "above/below"; parallel wording.
- Don'ts: no nested bullets/hierarchies; no ANSI codes; don't cram unrelated keywords; keep keyword lists short—wrap/reformat if long; avoid naming formatting styles in answers.
- Adaptation: code explanations → precise, structured with code refs; simple tasks → lead with outcome; big changes → logical walkthrough + rationale + next actions; casual one-offs → plain sentences, no headers/bullets.
- File References: When referencing files in your response follow the below rules:
* Use inline code to make file paths clickable.
* Each reference should have a stand-alone path, even if it's the same file.
* Accepted: absolute, workspace‑relative, a/ or b/ diff prefixes, or bare filename/suffix.
* Optionally include line/column (1‑based): :line[:column] or #Lline[Ccolumn] (column defaults to 1).
* Do not use URIs like file://, vscode://, or https://.
* Do not provide range of lines
* Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\repo\project\main.rs:12:5
执行过程中的用户进度更新
Codex 模型系列可以在工作过程中向用户提供进度更新。对于 gpt-5.3-codex 之前的 Codex 版本,这些更新由系统生成,无法通过提示控制,因此我们不建议在这些版本的提示中加入有关中间计划或向用户发送消息的指令。从 gpt-5.3-codex 开始,这些更新更注重沟通,会提供更多有关当前操作及其原因的关键信息,其工作方式与其他 GPT-5 系列模型的中间消息类似。您可以按照下文“开场说明与个性”一节来编写相关提示。
使用 agents.md
Codex-cli 会自动枚举这些文件并将其注入对话;模型经过训练,会严格遵循这些指令。
1. 从 ~/.codex 以及代码仓库根目录到当前工作目录(CWD)之间的各级目录中读取文件(支持可选的备用文件名,并设有大小上限)。
2. 按顺序合并这些文件,后续目录中的指令覆盖先前目录中的指令。
3. 每个合并后的片段都会作为独立的用户角色消息呈现给模型,如下所示:
# AGENTS.md instructions for <directory>
<INSTRUCTIONS>
...file contents...
</INSTRUCTIONS>
补充说明
- 每个找到的文件都会成为一条独立的用户角色消息,以 # AGENTS.md instructions for <directory> 开头,其中 <directory> 是该文件所在文件夹相对于代码仓库根目录的路径。
- 这些消息会注入到对话历史靠前的位置,位于用户提示之前,顺序从根目录到最深层目录:先是全局指令,再是代码仓库根目录的指令,随后是各级更深目录的指令。如果使用了 AGENTS.override.md,其所在目录的名称仍会出现在消息标题中(例如 # AGENTS.md instructions for backend/api),因此在对话记录中可以清楚看出指令的上下文。
压缩
压缩可以显著扩展有效上下文窗口,让用户连续进行多轮对话,避免触及上下文窗口限制或因上下文过长而导致性能下降。对于长时间运行的复杂任务,智能体也能执行远超常规上下文窗口长度的操作序列。此前,通过临时搭建的辅助机制和对话摘要也能实现较弱的类似效果;而我们通过 Responses API 提供的原生实现与模型深度集成,性能出色。
工作原理:
- 您可以像现在一样使用 Responses API,发送包含工具调用、用户输入和助手消息的输入项。
- 当上下文窗口中的内容增多时,您可以调用 /compact,生成新的压缩后上下文窗口。请注意以下两点:
- 发送到 /compact 的上下文内容应在模型的上下文窗口容量以内。
- 该端点兼容 ZDR,会返回一个“encrypted_content”项,供您传入后续请求。
- 后续调用 /responses 端点时,您可以传入更新后的压缩对话项列表(包括新增的压缩项)。模型会使用更少的对话 Token 保留此前的关键状态。
有关端点的详细信息,请参阅我们的 /responses/compact 文档。
工具
- 我们强烈建议原样使用我们提供的
apply_patch实现,因为模型经过训练,擅长处理这种差异格式。对于终端命令,我们推荐使用shell工具;对于计划和待办事项,update_plan工具应该能带来最佳表现。 - 如果您更希望智能体使用“类似终端的工具”(例如使用
file_read(),而不是在终端中调用 `sed`),按照下文的说明操作,即可让该模型可靠地调用这些工具来替代终端。 - 其他工具也可以使用,包括语义搜索、MCP 或其他自定义工具,但需要更多调优和实验。
Apply_patch
实现 apply_patch 最简单的方法是使用我们在 Responses API 中提供的原生实现;您也可以使用结合上下文无关文法的自由格式工具实现。下文演示了这两种方式。
# Sample script to demonstrate the server-defined apply_patch tool
import json
from pprint import pprint
from typing import cast
from openai import OpenAI
from openai.types.responses import ResponseInputParam, ToolParam
client = OpenAI()
## Shared tools and prompt
user_request = """Add a cancel button that logs when clicked"""
file_excerpt = """\
export default function Page() {
return (
<div>
<p>Page component not implemented</p>
<button onClick={() => console.log("clicked")}>Click me</button>
</div>
);
}
"""
input_items: ResponseInputParam = [
{"role": "user", "content": user_request},
{
"type": "function_call",
"call_id": "call_read_file_1",
"name": "read_file",
"arguments": json.dumps({"path": ("/app/page.tsx")}),
},
{
"type": "function_call_output",
"call_id": "call_read_file_1",
"output": file_excerpt,
},
]
read_file_tool: ToolParam = cast(
ToolParam,
{
"type": "function",
"name": "read_file",
"description": "Reads a file from disk",
"parameters": {
"type": "object",
"properties": {"path": {"type": "string"}},
"required": ["path"],
},
},
)
### Get patch with built-in responses tool
tools: list[ToolParam] = [
read_file_tool,
cast(ToolParam, {"type": "apply_patch"}),
]
response = client.responses.create(
model="gpt-5.3-codex",
input=input_items,
tools=tools,
parallel_tool_calls=False,
)
for item in response.output:
if item.type == "apply_patch_call":
print("Responses API apply_patch patch:")
pprint(item.operation)
# output:
# {'diff': '@@\n'
# ' return (\n'
# ' <div>\n'
# ' <p>Page component not implemented</p>\n'
# ' <button onClick={() => console.log("clicked")}>Click me</button>\n'
# '+ <button onClick={() => console.log("cancel clicked")}>Cancel</button>\n'
# ' </div>\n'
# ' );\n'
# ' }\n',
# 'path': '/app/page.tsx',
# 'type': 'update_file'}
### Get patch with custom tool implementation, including freeform tool definition and context-free grammar
apply_patch_grammar = """
start: begin_patch hunk+ end_patch
begin_patch: "*** Begin Patch" LF
end_patch: "*** End Patch" LF?
hunk: add_hunk | delete_hunk | update_hunk
add_hunk: "*** Add File: " filename LF add_line+
delete_hunk: "*** Delete File: " filename LF
update_hunk: "*** Update File: " filename LF change_move? change?
filename: /(.+)/
add_line: "+" /(.*)/ LF -> line
change_move: "*** Move to: " filename LF
change: (change_context | change_line)+ eof_line?
change_context: ("@@" | "@@ " /(.+)/) LF
change_line: ("+" | "-" | " ") /(.*)/ LF
eof_line: "*** End of File" LF
%import common.LF
"""
tools_with_cfg: list[ToolParam] = [
read_file_tool,
cast(
ToolParam,
{
"type": "custom",
"name": "apply_patch_grammar",
"description": "Use the `apply_patch` tool to edit files. This is a FREEFORM tool, so do not wrap the patch in JSON.",
"format": {
"type": "grammar",
"syntax": "lark",
"definition": apply_patch_grammar,
},
},
),
]
response_cfg = client.responses.create(
model="gpt-5.3-codex",
input=input_items,
tools=tools_with_cfg,
parallel_tool_calls=False,
)
for item in response_cfg.output:
if item.type == "custom_tool_call":
print("\n\nContext-free grammar apply_patch patch:")
print(item.input)
# Output
# *** Begin Patch
# *** Update File: /app/page.tsx
# @@
# <div>
# <p>Page component not implemented</p>
# <button onClick={() => console.log("clicked")}>Click me</button>
# + <button onClick={() => console.log("cancel clicked")}>Cancel</button>
# </div>
# );
# }
# *** End Patch对于 Responses API 工具生成的补丁对象,您可以参照此示例实现其处理逻辑;对于自由格式工具生成的补丁,则可以使用我们的标准 GPT-5 apply_patch.py 实现中的逻辑来应用。
Shell_command
这是我们的默认 Shell 工具。请注意,我们观察到,使用“string”类型的命令比使用命令列表能获得更好的表现。
{
"type": "function",
"function": {
"name": "shell_command",
"description": "Runs a shell command and returns its output.\n- Always set the `workdir` param when using the shell_command function. Do not use `cd` unless absolutely necessary.",
"strict": false,
"parameters": {
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "The shell script to execute in the user's default shell"
},
"workdir": {
"type": "string",
"description": "The working directory to execute the command in"
},
"timeout_ms": {
"type": "number",
"description": "The timeout for the command in milliseconds"
},
"with_escalated_permissions": {
"type": "boolean",
"description": "Whether to request escalated permissions. Set to true if command needs to be run without sandbox restrictions"
},
"justification": {
"type": "string",
"description": "Only set if with_escalated_permissions is true. 1-sentence explanation of why we want to run this command."
}
},
"required": ["command"],
"additionalProperties": false
}
}
}
如果您使用 Windows PowerShell,请将工具描述更新为以下内容。
Runs a shell command and returns its output. The arguments you pass will be invoked via PowerShell (e.g., ["pwsh", "-NoLogo", "-NoProfile", "-Command", "<cmd>"]). Always fill in workdir; avoid using cd in the command string.
您可以查看 codex-cli 中 exec_command 和 write_stdin 的实现。前者会在您需要流式输出、REPL 或交互式会话时启动一个长时间运行的 PTY;后者用于向现有 exec_command 会话发送更多按键输入,或仅轮询输出。
更新计划
这是我们的默认待办事项工具,您可以根据自己的偏好进行定制。有关保持计划清晰有序和调整行为的更多指令,请参阅入门提示中的 ## Plan tool 部分。
{
"type": "function",
"function": {
"name": "update_plan",
"description": "Updates the task plan.\nProvide an optional explanation and a list of plan items, each with a step and status.\nAt most one step can be in_progress at a time.",
"strict": false,
"parameters": {
"type": "object",
"properties": {
"explanation": {
"type": "string"
},
"plan": {
"type": "array",
"items": {
"type": "object",
"properties": {
"step": {
"type": "string"
},
"status": {
"type": "string",
"description": "One of: pending, in_progress, completed"
}
},
"additionalProperties": false,
"required": ["step", "status"]
},
"description": "The list of steps"
}
},
"additionalProperties": false,
"required": ["plan"]
}
}
}
View_image
这是 codex-cli 中供模型查看图像的一个基本函数。
{
"type": "function",
"function": {
"name": "view_image",
"description": "Attach a local image (by filesystem path) to the conversation context for this turn.",
"strict": false,
"parameters": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Local filesystem path to an image file"
}
},
"additionalProperties": false,
"required": ["path"]
}
}
}
封装终端命令的专用工具
如果您希望 Codex 智能体使用封装终端命令的工具(例如使用专用的 list_dir(‘.’) 工具替代 terminal(‘ls .’)),通常可以获得良好效果。我们发现,当工具名称、参数和输出尽可能接近底层命令时,效果最好,因为这样更贴近模型的训练分布(模型主要使用专用终端工具进行训练)。例如,如果您发现模型通过终端使用 git,而您希望它使用专用工具,我们发现,创建相应工具并在提示中明确要求仅通过该工具执行 git 命令,就能完全避免模型再通过终端执行 git 命令。
GIT_TOOL = {
"type": "function",
"name": "git",
"description": (
"Execute a git command in the repository root. Behaves like running git in the"
" terminal; supports any subcommand and flags. The command can be provided as a"
" full git invocation (e.g., `git status -sb`) or just the arguments after git"
" (e.g., `status -sb`)."
),
"parameters": {
"type": "object",
"properties": {
"command": {
"type": "string",
"description": (
"The git command to execute. Accepts either a full git invocation or"
" only the subcommand/args."
),
},
"timeout_sec": {
"type": "integer",
"minimum": 1,
"maximum": 1800,
"description": "Optional timeout in seconds for the git command.",
},
},
"required": ["command"],
},
}
TOOLS = [GIT_TOOL]
PROMPT_TOOL_USE_DIRECTIVE = (
"- Strictly avoid raw `cmd`/terminal for Git operations. Use the dedicated "
"`git` tool instead."
)其他自定义工具(网页搜索、语义搜索、记忆等)
模型未必经过专门的后训练来熟练使用这些工具,但我们也见过成功的案例。为充分发挥这些工具的作用,我们建议:
- 尽量让工具名称和参数在语义上准确。例如,“search”含义模糊,而“semantic_search”能清楚地表明工具的用途,并与您可能拥有的其他搜索工具区分开来。“Query”就很适合作为这个工具的参数名称。
- 在提示中明确说明何时、为何以及如何使用这些工具,并提供正确和错误的示例。
- 让这些工具的结果在呈现形式上区别于模型熟悉的其他工具输出,也可能有所帮助。例如,ripgrep 结果应与语义搜索结果有所区别,以免模型又沿用旧习惯。
并行工具调用
在 codex-cli 中启用并行工具调用后,Responses API 请求会设置 parallel_tool_calls: true,并将以下片段添加到系统指令中:
## Exploration and reading files
- **Think first.** Before any tool call, decide ALL files/resources you will need.
- **Batch everything.** If you need multiple files (even from different places), read them together.
- **multi_tool_use.parallel** Use `multi_tool_use.parallel` to parallelize tool calls and only this.
- **Only make sequential calls if you truly cannot know the next file without seeing a result first.**
- **Workflow:** (a) plan all needed reads → (b) issue one parallel batch → (c) analyze results → (d) repeat if new, unpredictable reads arise.
**Additional notes**:
- Always maximize parallelism. Never read files one-by-one unless logically unavoidable.
- This concerns every read/list/search operations including, but not only, `cat`, `rg`, `sed`, `ls`, `git show`, `nl`, `wc`, ...
- Do not try to parallelize using scripting or anything else than `multi_tool_use.parallel`.
我们发现,按以下顺序排列并行工具调用项及其响应,有助于改善效果,也更符合模型的训练分布:
function_call
function_call
function_call_output
function_call_output
工具响应截断
我们建议按以下方式截断工具调用响应,以尽可能符合模型的训练分布:
- 将上限设为 10k Token。您可以通过计算
num_bytes/4,以较低开销估算 Token 数量。 - 如果达到截断上限,应将一半的额度用于保留开头,另一半用于保留结尾,并在中间用
…3 tokens truncated…标记截断部分。
GPT-5.3 Codex 的新功能
前置消息
Responses API 包含一个 phase 参数,用于防止提示要求提供前置消息时出现过早停止等异常行为。使用 gpt-5.3-codex 时必须正确实现此参数,否则可能导致性能显著下降。
阶段
为更好地支持 gpt-5.3-codex 的前置消息,Responses API 包含一个 phase 字段,用于防止较长时间运行的任务过早停止,以及出现其他异常行为。
取值
phase 的值为以下之一:
null"commentary""final_answer"
出现位置
您收到的助手输出项会包含 phase(例如,output_item.done)。您的集成必须持久保存助手输出项及其 phase,并在后续请求中传回这些助手输出项。
重要提示: phase 仅支持用于助手项。请勿将 phase 添加到用户消息中。
下游如何使用
当模型使用以下值标记输出项时:
phase: "commentary":对应的助手消息应被视为过程说明或前置消息类内容。phase: "final_answer":对应的助手消息应被视为最终结束回复。
使用 gpt-5.3-codex 时,必须正确保留助手项中的 phase。如果在重建历史记录时丢失了助手的 phase 元数据,可能导致性能显著下降。
前置消息与个性
前置消息是随工具调用一同发送的消息,用于在工作过程中向用户提供更新:简短、易读地说明当前进度和行动意图,帮助用户了解情况,又不至于让对话记录变成工具调用日志。GPT-5.3-Codex 的前置消息已针对以下特点进行了调优:
- 在调用任何工具之前,先回应用户请求,再说明计划(用 1 句话回应,用 1–2 句话说明计划)。
- 大多数更新保持在 1–2 句话,仅在真正达到里程碑时提供较长的更新。
- 频率:尽量每执行 1–3 个步骤就更新一次;最低要求:每 6 个步骤或 10 次工具调用内至少更新一次。
- 每次更新的内容:目前的结果或影响、接下来的 1–3 个步骤,以及尚未解决的问题或新发现(如有)。
- 语气:像真人结对协作一样自然,不拘礼节;避免使用标题、状态标签和日志式语气。
个性(友好与务实)
个性指的是整体交流氛围与协作姿态,比前置消息的具体机制(频率、长度和落地)更高一层。它会影响措辞、模型解释取舍时的主动程度,以及互动中的亲和程度。
Codex App 和 CLI 已支持两种个性,下面将它们作为示例实现,供您的执行框架参考。
友好
- 更有人情味,像搭档一样结对协作。
- 会稍多一些回应、安抚和背景说明。
- 更适合需要通过讲解来帮助用户理解情况的场景,例如新手引导、需求不明确的任务,以及影响较大的变更。
codex-cli 中的友好个性提示片段示例
您可以在系统提示中使用此片段,引导模型在结对编程时展现相应的个性。
# Personality
You optimize for team morale and being a supportive teammate as much as code quality. You communicate warmly, check in often, and explain concepts without ego. You excel at pairing, onboarding, and unblocking others. You create momentum by making collaborators feel supported and capable.
## Values
You are guided by these core values:
* Empathy: Interprets empathy as meeting people where they are - adjusting explanations, pacing, and tone to maximize understanding and confidence.
* Collaboration: Sees collaboration as an active skill: inviting input, synthesizing perspectives, and making others successful.
* Ownership: Takes responsibility not just for code, but for whether teammates are unblocked and progress continues.
## Tone & User Experience
Your voice is warm, encouraging, and conversational. You use teamwork-oriented language such as "we" and "let’s"; affirm progress, and replaces judgment with curiosity. You use light enthusiasm and humor when it helps sustain energy and focus. The user should feel safe asking basic questions without embarrassment, supported even when the problem is hard, and genuinely partnered with rather than evaluated. Interactions should reduce anxiety, increase clarity, and leave the user motivated to keep going.
You are NEVER curt or dismissive.
You are a patient and enjoyable collaborator: unflappable when others might get frustrated, while being an enjoyable, easy-going personality to work with. Even if you suspect a statement is incorrect, you remain supportive and collaborative, explaining your concerns while noting valid points. You frequently point out the strengths and insights of others while remaining focused on working with others to accomplish the task at hand.
## Escalation
You escalate gently and deliberately when decisions have non-obvious consequences or hidden risk. Escalation is framed as support and shared responsibility-never correction-and is introduced with an explicit pause to realign, sanity-check assumptions, or surface tradeoffs before committing.
务实
- 更加简洁、直接,注重尽快交付成果。
- 少一些客套话,每个 Token 承载更多可付诸行动的信息。
- 更适合重视延迟或吞吐量的场景,或者您的用户已经熟悉工作流程,只想看到进展和结果的情况。
故障排除与元提示
我们一直在专门跟踪以下常见问题:
- 过度思考,或在首次采取有效行动(调用工具或提出具体计划)之前耗时过长。
- 状态更新像日志一样生硬、不自然,缺少结对编程应有的协作感。
- 前置消息措辞生硬,反复使用口头禅(例如“发现得好”“啊哈”“明白了——”等)。
使用元提示进行针对性修正
上述问题通常可以通过元提示来解决。如果某一轮的表现未达预期,您可以在该轮结束时询问模型应如何改进其自身的指令。我们曾使用以下提示生成针对上述过度思考问题的部分解决方案,您也可以根据自己的具体需求加以修改。
That was a high quality response, thanks! It seemed like it took you a while to finish responding though. Is there a way to clarify your instructions so you can get to a response as good as this faster next time? It’s extremely important to be efficient when providing these responses or users won’t get the most out of them in time. Let’s see if we can improve!
think through the response you gave above
read through your instructions starting from "" and look for anything that might have made you take longer to formulate a high quality response than you needed
write out targeted (but generalized) additions/changes/deletions to your instructions to make a request like this one faster next time with the same level of quality
在特定上下文中使用元提示时,应尽可能多生成几次响应,并关注其中的共同之处。模型提出的某些改进或变更可能过于针对当前情境,但通常可以通过简化,提炼出通用的改进方法。我们建议创建一项评测,衡量某个提示变更对您的具体用例究竟是改善还是退步。
一些示例
- 对于过度思考或迟迟不开始行动的问题:请模型提出指令修改建议,缩短首次调用工具或提出具体计划之前的等待时间。
- 对于过于像日志的前置消息:请模型重写有关向用户提供更新的指令,以满足您的具体偏好和约束。
使用 GPT-5.2
了解 GPT-5.2 的最佳实践、功能和迁移指南。
简介
GPT-5.2 发布时定位为旗舰通用模型,适用于一般任务和智能体任务。与 GPT-5.1 相比,它在以下方面有所提升:
- 通用智能
- 指令遵循
- 准确性和 Token 使用效率
- 多模态能力,尤其是视觉能力
- 代码生成,尤其是前端 UI 创建
- API 中的工具调用和上下文管理
- 电子表格理解与创建
与之前的 GPT-5.1 模型不同,GPT-5.2 新增了管理模型“知道”和“记住”哪些内容的功能,以提高准确性。
本指南介绍 GPT-5 模型系列的关键功能,以及如何充分发挥 GPT-5.2 的能力。
探索编程示例
点击体验几个演示应用,它们完全由单条提示生成,无需手动编写任何代码。请注意,这些示例由 GPT-5.2 或我们上一代旗舰模型 GPT-5 生成。
模型、API 和功能更新
GPT-5.2 这一代模型包括:适合需要广泛世界知识的复杂任务的 gpt-5.2、行为与 ChatGPT 保持一致的 gpt-5.2-chat-latest,以及适合通过更多计算资源获得更好结果的问题的 gpt-5.2-pro。
如果需要更小的模型,请使用 gpt-5-mini。
选择最适合您使用场景的模型时,可以参考以下权衡:
| 变体 | 最适合 |
|---|---|
gpt-5.2 | 复杂推理、广泛的世界知识,以及涉及大量代码或多个步骤的智能体任务 |
gpt-5.2-pro | 需要更深入思考、可能耗时更长的难题 |
gpt-5.2-codex | 构建交互式编程产品的公司;各类编程任务 |
gpt-5-mini | 注重成本优化的推理和聊天;兼顾速度、成本与能力 |
gpt-5-nano | 高吞吐量任务,尤其是针对性强的指令遵循或分类任务 |
GPT-5.2 的新功能
与 GPT-5.1 一样,全新的 GPT-5.2 提供了自定义工具、控制详细程度和推理的参数,以及允许使用的工具列表等 API 功能。5.2 新增了 xhigh 推理强度级别、简洁的推理摘要,以及使用 压缩的全新上下文管理方式。
本指南介绍 GPT-5 模型系列的部分关键功能,重点说明如何充分发挥 5.2 的能力。
针对编程任务,我们提供了经过编程优化的变体 GPT-5.2-Codex,适用于 Codex 或类似 Codex 环境中的智能体工作流。
更低的推理强度
reasoning.effort 参数控制模型在作答前生成的推理 Token 数量。o3 等早期推理模型仅支持 low、medium 和 high:low 更注重速度和减少 Token 使用量,而 high 更注重深入推理。
在 GPT-5.2 中,最低设置为 none,可提供延迟更低的交互体验。这也是 GPT-5.2 的默认设置。如果您需要更多思考,可以逐步提高到 medium 并测试效果。
当推理强度设置为 none 时,提示的编写很重要。即使使用默认设置,您也可以鼓励模型在回答前先“思考”或列出步骤,以提高其推理质量。
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-5.2",
input="Think carefully and outline your steps before answering. How much gold would it take to coat the Statue of Liberty in a 1mm layer?",
reasoning={"effort": "none"},
)
print(response)详细程度
详细程度决定生成的输出 Token 数量。减少 Token 数量可以降低整体延迟。虽然模型的推理方式基本不变,但模型会设法更简洁地作答。这可能提高或降低回答质量,具体取决于您的使用场景。以下是高、低详细程度各自适用的一些场景:
- 高详细程度: 适用于需要模型详细解释文档或进行大规模代码重构的情况。
- 低详细程度: 最适合需要简短回答或针对性代码生成的情况,例如生成 SQL 查询。
GPT-5 允许将此选项配置为 high、medium 或 low。在 GPT-5.2 中,详细程度仍可配置,默认值为 medium。
使用 GPT-5.2 生成代码时,medium 和 high 详细程度会生成更长、结构更清晰且附有行内说明的代码,而 low 详细程度会生成更短、更简洁的代码,并尽量减少说明。
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-5.2",
input="What is the answer to the ultimate question of life, the universe, and everything?",
text={"verbosity": "low"},
)
print(response)即使在 API 中将详细程度设置为 low,您仍然可以通过提示加以调整。详细程度参数在系统提示层面定义了大致的 Token 数量范围,但在该范围内,实际输出仍可根据开发者提示和用户提示灵活调整。
在 GPT-5.2 中使用工具
GPT-5.2 已针对特定工具进行了后训练。有关更具体的指导,请参阅工具文档。
应用补丁工具
apply_patch 工具让 GPT-5.2 能够使用结构化差异在您的代码库中创建、更新和删除文件。模型不再只是建议修改,而是输出补丁操作,由您的应用执行并反馈结果,从而支持迭代式、多步骤的代码编辑工作流。阅读文档。
在底层,该实现使用自由格式的函数调用,而非 JSON 格式。在测试中,这个具名函数使 apply_patch 的失败率降低了 35%。
Shell 工具
GPT-5.2 支持本地 Shell。Shell 工具允许模型通过受控的命令行界面与您的本地计算机交互。阅读文档以了解更多信息。
自定义工具
GPT-5 模型系列发布时,我们引入了一项名为自定义工具的新能力,让模型可以将任意原始文本作为工具调用输入,同时仍可按需约束输出。GPT-5.2 延续了这一工具行为。
在函数调用指南中了解自定义工具。
自由格式输入
使用 type: custom 定义工具,即可让模型直接向您的工具发送纯文本输入,而不局限于结构化 JSON。模型可以直接向您的工具发送任意原始文本,包括代码、SQL 查询、Shell 命令、配置文件或长篇文字。
{
"type": "custom",
"name": "code_exec",
"description": "Executes arbitrary python code"
}
约束输出
GPT-5.2 为自定义工具提供上下文无关文法(CFGs)支持,您可以提供 Lark 文法,将输出约束为特定语法或 DSL。附加 CFG(例如 SQL 或 DSL 文法)可确保助手的文本符合您定义的文法。
这使您能够实现精确且受约束的工具调用或结构化响应,并直接在 GPT-5.2 的函数调用中强制采用严格的语法格式或领域专用格式,从而提高复杂领域或受约束领域中的可控性和可靠性。
自定义工具最佳实践
- 编写简洁、明确的工具描述。 模型会根据您的描述选择要发送的内容;如果您希望模型始终调用该工具,请明确说明。
- 在服务器端验证输出。自由格式字符串功能强大,但需要采取防护措施,防范注入攻击或不安全的命令。
允许使用的工具
tool_choice 下的 allowed_tools 参数允许您传入 N 个工具定义,同时将模型的使用范围限制为其中的 M 个(< N)。在 tools 中列出完整的工具集,然后使用 allowed_tools 块指定工具子集和模式:auto(模型可以选择其中任意工具)或 required(模型必须调用其中一个工具)。
请参阅函数调用指南,了解允许使用的工具选项。
将所有可能使用的工具与 当前可用的工具子集分开,可以提高安全性、可预测性和提示缓存效果。这也能避免使用硬编码调用顺序等脆弱的提示工程方法。GPT-5.2 能在对话过程中动态调用特定函数,或要求调用这些函数,同时降低在长上下文中意外使用工具的风险。
| 标准工具 | 允许使用的工具 | |
|---|---|---|
| 模型的工具范围 | "tools": […] 下列出的所有工具 | 仅限 tool_choice 中 "tools": […] 下的工具子集 |
| 工具调用 | 模型可以调用任意工具,也可以不调用任何工具 | 模型只能调用所选工具,或必须调用所选工具 |
| 用途 | 声明可用能力 | 限制实际使用的能力范围 |
{
"tool_choice": {
"type": "allowed_tools",
"mode": "auto",
"tools": [
{ "type": "function", "name": "get_weather" },
{ "type": "function", "name": "search_docs" }
]
}
}
有关这些新功能的详细介绍,请参阅配套 Cookbook。
调用前说明
调用前说明是 GPT-5.2 在调用任何工具或函数之前生成的简短说明,用户可以看到这些内容,其中概述了模型的意图或计划,例如“我为什么要调用这个工具”。这些说明出现在思维链之后、实际工具调用之前,让模型的推理更易于理解和调试,也便于精确引导模型。
调用前说明让 GPT-5.2 在每次调用工具之前“说出自己的想法”,从而提高工具调用的准确性和整体任务成功率,同时避免大幅增加推理开销。要启用调用前说明,请添加一条系统或开发者指令,例如:“在调用工具之前,请解释调用它的原因。”GPT-5.2 会为每次指定的工具调用添加简短的理由。模型还可能在工具调用之间输出多条消息,从而改善交互体验,尤其适合推理量极少或对延迟敏感的使用场景。
有关调用前说明的更多用法,请参阅 GPT-5 提示 Cookbook。
迁移快速入门
GPT-5.2 与 Responses API 配合使用时效果最佳,该 API 支持在对话轮次之间保留推理上下文。请阅读下文,了解如何从您当前使用的模型或 API 迁移。
从其他模型迁移到 GPT-5.2
虽然该模型应该基本可以直接替换 GPT-5.1,但仍有一些关键变化需要注意。有关提示需要进行的具体调整,请参阅 GPT-5.2 提示指南。
得益于 Responses API 的设计,通过该 API 使用 GPT-5 模型可以提升智能表现。Responses API 可以将上一轮的思维链传递给模型,从而减少生成的推理 Token 数量、提高缓存命中率并降低延迟。要了解更多信息,请参阅介绍 Responses API 优势的深入指南。
从旧版 OpenAI 模型迁移到 GPT-5.2 时,请先尝试不同的推理级别和提示策略。根据我们的测试,建议您使用我们的提示优化器,它会根据我们的最佳实践自动调整提示,使其适用于 GPT-5.2,同时遵循以下针对各模型的指导:
gpt-5.1:采用默认设置的gpt-5.2旨在作为可直接替换的模型。- o3:使用
gpt-5.2,将推理强度设为medium或high。先使用medium推理强度并调整提示;如果未能获得预期结果,再提高到high。 gpt-4.1:使用gpt-5.2,将推理强度设为none。先从none开始并调整提示;如果需要更好的表现,再提高推理强度。o4-mini或gpt-4.1-mini:gpt-5-mini配合提示调整,是很好的替代方案。gpt-4.1-nano:gpt-5-nano配合提示调整,是很好的替代方案。
GPT-5.2 参数兼容性
以下参数 仅在 使用 GPT-5.2 且将推理强度设为 none 时受支持:
temperaturetop_plogprobs
向采用其他推理强度设置的 GPT-5.2 或 GPT-5.1 发送请求,或者向较旧的 GPT-5 模型(例如 gpt-5、gpt-5-mini 或 gpt-5-nano)发送请求时,如果包含这些字段,就会报错。
如果您使用更高的推理强度设置或其他 GPT-5 系列模型,希望获得类似结果,可以尝试以下替代参数:
- 推理深度:
reasoning: { effort: "none" | "low" | "medium" | "high" | "xhigh" } - 输出详细程度:
text: { verbosity: "low" | "medium" | "high" } - 输出长度:
max_output_tokens
从 Chat Completions 迁移到 Responses API
对于 GPT-5.2,Responses API 与 Chat Completions 最大的区别,也是迁移到 Responses API 的主要原因,在于它支持在对话轮次之间传递思维链(CoT)。请参阅完整的 API 对比。
只有 Responses API 支持传递 CoT。我们观察到,这样做可以提升智能表现、减少生成的推理 Token 数量、提高缓存命中率并降低延迟。其他大多数参数的功能保持一致,只是格式有所不同。下面介绍 Chat Completions 与 Responses API 在处理新参数方面的差异:
推理强度
curl --request POST \
--url https://api.openai.com/v1/responses \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.2",
"input": "How much gold would it take to coat the Statue of Liberty in a 1mm layer?",
"reasoning": {
"effort": "none"
}
}'curl --request POST \
--url https://api.openai.com/v1/chat/completions \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.2",
"messages": [
{
"role": "user",
"content": "How much gold would it take to coat the Statue of Liberty in a 1mm layer?"
}
],
"reasoning_effort": "none"
}'详细程度
curl --request POST \
--url https://api.openai.com/v1/responses \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.2",
"input": "What is the answer to the ultimate question of life, the universe, and everything?",
"text": {
"verbosity": "low"
}
}'curl --request POST \
--url https://api.openai.com/v1/chat/completions \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.2",
"messages": [
{
"role": "user",
"content": "What is the answer to the ultimate question of life, the universe, and everything?"
}
],
"verbosity": "low"
}'自定义工具
curl --request POST \
--url https://api.openai.com/v1/responses \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.2",
"input": "Use the code_exec tool to calculate the area of a circle with radius equal to the number of r letters in blueberry",
"tools": [
{
"type": "custom",
"name": "code_exec",
"description": "Executes arbitrary Python code"
}
]
}'curl --request POST \
--url https://api.openai.com/v1/chat/completions \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.2",
"messages": [
{
"role": "user",
"content": "Use the code_exec tool to calculate the area of a circle with radius equal to the number of r letters in blueberry"
}
],
"tools": [
{
"type": "custom",
"custom": {
"name": "code_exec",
"description": "Executes arbitrary Python code"
}
}
]
}'提示词最佳实践
2. 主要行为差异
与上一代模型(例如 GPT-5 和 GPT-5.1)相比,GPT-5.2 具有以下特点:
- 更周密的任务框架: 默认会制定更清晰的计划并构建更明确的中间步骤结构;明确限定范围和详细程度有助于改善表现。
- 整体更简洁: 回答更精炼、更聚焦任务,但仍会受到提示的影响,因此需要在提示中明确说明偏好。
- 更严格地遵循指令: 更少偏离用户意图;格式和理由说明也有所改善。
- 工具效率方面的取舍: 与 GPT-5.1 相比,在交互式流程中会执行更多工具操作,可以通过提示进一步优化。
- 落地时更偏向保守: 倾向于优先确保正确性并明确展示推理;加入澄清提示可以改善歧义处理。
本指南重点介绍如何通过提示充分发挥 GPT-5.2 在智能、准确性、落地能力和约束遵循方面的优势,同时缓解仍然存在的效率问题。现有的 GPT-5 / GPT-5.1 提示指南大多可以沿用,仍然适用。
3. 提示模式
将以下思路融入您的提示,以更好地引导 GPT-5.2。
3.1 控制详细程度和输出形式
给出 明确、具体的长度限制 ,尤其是在企业智能体和编程智能体中。
以下是限制输出的示例,可根据所需的详细程度调整:
<output_verbosity_spec>
- Default: 3–6 sentences or ≤5 bullets for typical answers.
- For simple “yes/no + short explanation” questions: ≤2 sentences.
- For complex multi-step or multi-file tasks:
- 1 short overview paragraph
- then ≤5 bullets tagged: What changed, Where, Risks, Next steps, Open questions.
- Provide clear and structured responses that balance informativeness with conciseness. Break down the information into digestible chunks and use formatting like lists, paragraphs and tables when helpful.
- Avoid long narrative paragraphs; prefer compact bullets and short sections.
- Do not rephrase the user’s request unless it changes semantics.
</output_verbosity_spec>
3.2 防止范围偏移(例如前端任务中的 UX / 设计)
GPT-5.2 更擅长生成结构清晰的代码,但生成的代码可能超出最低 UX 规范和设计系统的要求。要让它保持在既定范围内,请明确禁止额外功能和不受约束的样式设计。
<design_and_scope_constraints>
- Explore any existing design systems and understand it deeply.
- Implement EXACTLY and ONLY what the user requests.
- No extra features, no added components, no UX embellishments.
- Style aligned to the design system at hand.
- Do NOT invent colors, shadows, tokens, animations, or new UI elements, unless requested or necessary to the requirements.
- If any instruction is ambiguous, choose the simplest valid interpretation.
</design_and_scope_constraints>
要确保遵循设计系统,请复用您的 5.1 <design_system_enforcement> 块,并添加“不添加额外功能”和“颜色仅使用设计 Token”以进一步强调。
3.3 长上下文与信息回忆
对于长上下文任务,在提示中要求 强制总结并重新落地可能会有所帮助。这种模式可以减少因内容过长而遗漏信息的错误,并提高模型从信息密集的上下文中回忆信息的能力。
<long_context_handling>
- For inputs longer than ~10k tokens (multi-chapter docs, long threads, multiple PDFs):
- First, produce a short internal outline of the key sections relevant to the user’s request.
- Re-state the user’s constraints explicitly (e.g., jurisdiction, date range, product, team) before answering.
- In your answer, anchor claims to sections (“In the ‘Data Retention’ section…”) rather than speaking generically.
- If the answer depends on fine details (dates, thresholds, clauses), quote or paraphrase them.
</long_context_handling>
3.4 处理歧义与幻觉风险
针对模型在模糊查询中可能过度自信地产生幻觉的情况设置提示,例如需求不明确、缺少约束,或问题需要最新数据却未调用工具。
用于缓解风险的提示:
<uncertainty_and_ambiguity>
- If the question is ambiguous or underspecified, explicitly call this out and:
- Ask up to 1–3 precise clarifying questions, OR
- Present 2–3 plausible interpretations with clearly labeled assumptions.
- When external facts may have changed recently (prices, releases, policies) and no tools are available:
- Answer in general terms and state that details may have changed.
- Never fabricate exact figures, line numbers, or external references when you are uncertain.
- When you are unsure, prefer language like “Based on the provided context…” instead of absolute claims.
</uncertainty_and_ambiguity>
对于高风险输出,您还可以添加一个简短的自检步骤:
<high_risk_self_check>
Before finalizing an answer in legal, financial, compliance, or safety-sensitive contexts:
- Briefly re-scan your own answer for:
- Unstated assumptions,
- Specific numbers or claims not grounded in context,
- Overly strong language (“always,” “guaranteed,” etc.).
- If you find any, soften or qualify them and explicitly state assumptions.
</high_risk_self_check>
4. 压缩(扩展有效上下文)
对于长时间运行、频繁使用工具且超出标准上下文窗口的工作流,启用推理的 GPT-5.2 支持通过 /responses/compact 端点压缩响应。压缩会在考虑信息损失的情况下处理先前的对话状态,返回经过加密、内容不透明的条目,在保留任务相关信息的同时大幅减少 Token 占用。这样,模型就能在更长的工作流中持续推理,而不会达到上下文限制。
何时使用压缩
- 包含大量工具调用的多步骤智能体流程
- 需要保留早期轮次内容的长对话
- 超出最大上下文窗口的迭代推理
主要特性
- 生成不透明的加密条目(内部逻辑可能会演变)
- 旨在支持继续执行,而非检查内容
- 兼容 GPT-5.2 和 Responses API
- 可在长会话中安全地重复运行
压缩响应
端点
POST https://api.openai.com/v1/responses/compact
功能说明
对对话执行一次压缩,并返回压缩后的响应对象。将压缩后的输出传入下一次请求,即可使用更小的上下文继续工作流。
最佳实践
- 监控上下文使用量并提前规划,避免达到上下文窗口限制
- 在完成重要阶段后(例如频繁使用工具的阶段)进行压缩,而非每一轮都压缩
- 恢复执行时,保持提示在功能上不变,以避免行为偏移
- 将压缩后的条目视为不透明数据;不要解析或依赖其内部内容
有关在生产环境中何时以及如何压缩的指导,请参阅对话状态指南和压缩响应页面。
以下是一个示例:
from openai import OpenAI
import json
client = OpenAI()
response = client.responses.create(
model="gpt-5.2",
input=[
{
"role": "user",
"content": "write a very long poem about a dog.",
},
],
)
output_json = [msg.model_dump() for msg in response.output]
# Now compact, passing the original user prompt and the assistant text as inputs
compacted_response = client.responses.compact(
model="gpt-5.2",
input=[
{
"role": "user",
"content": "write a very long poem about a dog.",
},
output_json[0],
],
)
print(json.dumps(compacted_response.model_dump(), indent=2))5. 智能体行为引导与用户进度更新
在提示得当时,GPT-5.2 在智能体流程规划和多步骤执行方面表现出色。您可以复用 GPT-5.1 的 <user_updates_spec> 和 <solution_persistence> 内容块。
可以加入两项关键调整,进一步提升 GPT-5.2 的表现:
- 限制进度更新的详细程度,使其更简短、更聚焦。
- 明确要求严格遵守任务范围,不要扩大要解决的问题。
更新后的规范示例:
<user_updates_spec>
- Send brief updates (1–2 sentences) only when:
- You start a new major phase of work, or
- You discover something that changes the plan.
- Avoid narrating routine tool calls (“reading file…”, “running tests…”).
- Each update must include at least one concrete outcome (“Found X”, “Confirmed Y”, “Updated Z”).
- Do not expand the task beyond what the user asked; if you notice new work, call it out as optional.
</user_updates_spec>
6. 工具调用与并行执行
与 5.1 相比,GPT-5.2 在工具使用的可靠性和流程规划方面有所提升,在 MCP/Atlas 这类环境中尤其明显。 适用于 GPT-5 / 5.1 的以下最佳实践同样适用:
- 简洁地描述工具:用 1–2 句话说明工具的作用和使用时机。
- 在扫描代码库、向量存储或操作多个实体时,明确鼓励并行执行。
- 对于影响重大的操作(订单、计费、基础设施变更),要求执行验证步骤。
工具使用说明示例:
<tool_usage_rules>
- Prefer tools over internal knowledge whenever:
- You need fresh or user-specific data (tickets, orders, configs, logs).
- You reference specific IDs, URLs, or document titles.
- Parallelize independent reads (read_file, fetch_record, search_docs) when possible to reduce latency.
- After any write/update tool call, briefly restate:
- What changed,
- Where (ID or path),
- Any follow-up validation performed.
</tool_usage_rules>
7. 结构化提取、PDF 和 Office 工作流
GPT-5.2 在这一领域的提升尤为明显。要充分发挥其能力:
- 始终提供输出的模式或 JSON 结构。您可以使用结构化输出来确保严格遵循模式。
- 区分必填字段和可选字段。
- 明确要求完整提取信息,并明确规定如何处理缺失字段。
示例:
<extraction_spec>
You will extract structured data from tables/PDFs/emails into JSON.
- Always follow this schema exactly (no extra fields):
{
"party_name": string,
"jurisdiction": string | null,
"effective_date": string | null,
"termination_clause_summary": string | null
}
- If a field is not present in the source, set it to null rather than guessing.
- Before returning, quickly re-scan the source for any missed fields and correct omissions.
</extraction_spec>
对于多表格或多文件提取,请补充以下指导:
- 分别序列化每份文档的结果。
- 包含稳定的 ID(文件名、合同标题、页码范围)。
8. 将提示迁移到 GPT-5.2 的指南
本节帮助您将提示和模型配置迁移到 GPT-5.2,同时保持行为稳定,让成本和延迟可预测。GPT-5 系列模型支持 reasoning_effort 调节参数(例如 none|minimal|low|medium|high|xhigh),用于在速度、成本与更深入的推理之间进行权衡。
迁移映射 升级到 GPT-5.2 时,请使用以下默认映射
| 当前模型 | 目标模型 | 目标 reasoning_effort | 说明 |
|---|---|---|---|
| GPT-4o | GPT-5.2 | none | 从 4o/4.1 迁移时,默认采用“快速、少思考”的设置;仅在评测结果退步时提高推理强度。 |
| GPT-4.1 | GPT-5.2 | none | 采用与 GPT-4o 相同的映射,以保持快速响应。 |
| GPT-5 | GPT-5.2 | 保持相同值,但 minimal → none | 保留 none/low/medium/high 设置,以保持延迟和质量特征一致。 |
| GPT-5.1 | GPT-5.2 | 保持相同值 | 保留现有推理强度设置;仅在运行评测后进行调整。 |
*请注意,GPT-5 的默认推理级别为 medium,GPT-5.1 和 GPT-5.2 的默认推理级别为 none。
我们在 Playground 中推出了提示优化器,帮助用户快速改进现有提示,并在 GPT-5 和其他 OpenAI 模型之间迁移这些提示。迁移到新模型的一般步骤如下:
- 第 1 步:切换模型,暂不修改提示。保持提示的功能完全一致,确保测试的是模型变更的影响,而非提示修改的影响。每次只做一项更改。
- 第 2 步:固定 reasoning_effort。显式设置 GPT-5.2 的 reasoning_effort,使其与先前模型的延迟和推理深度相匹配,避免服务提供商默认的“思考”设置意外改变成本、输出详细程度或结构。
- 第 3 步:运行评测以建立基线。模型和推理强度对齐后,运行您的评测套件。如果结果良好(中、高推理强度下通常表现更好),就可以上线。
- 第 4 步:如果表现退步,调整提示。结合使用提示优化器和有针对性的约束(详细程度、格式、模式,以及严格遵守任务范围的要求),使表现恢复到原有水平或进一步提升。
- 第 5 步:每次小幅更改后重新运行评测。每轮迭代可将 reasoning_effort 提高一档,或小幅调整提示,然后重新衡量效果。
9. 网页搜索与研究
GPT-5.2 更易于引导,综合多个来源信息的能力也更强。
请遵循以下最佳实践:
-
预先明确研究标准:告诉模型您希望它如何搜索,包括是否追踪衍生线索、解决信息矛盾以及提供引用。明确说明研究应深入到什么程度,例如持续开展补充研究,直到新增信息的价值开始下降。
-
通过指令而非提问来处理歧义:要求模型全面涵盖所有合理的意图,不要提出澄清问题。存在不确定性时,要求兼顾广度和深度。
-
规定输出形式和语气:明确结构要求(Markdown、标题、用于比较的表格)、清晰度要求(解释缩写、提供具体示例)以及表达风格(自然对话、适应角色设定、不谄媚)。
<web_search_rules>
- Act as an expert research assistant; default to comprehensive, well-structured answers.
- Prefer web research over assumptions whenever facts may be uncertain or incomplete; include citations for all web-derived information.
- Research all parts of the query, resolve contradictions, and follow important second-order implications until further research is unlikely to change the answer.
- Do not ask clarifying questions; instead cover all plausible user intents with both breadth and depth.
- Write clearly and directly using Markdown (headers, bullets, tables when helpful); define acronyms, use concrete examples, and keep a natural, conversational tone.
</web_search_rules>
10. 结语
对于致力于构建生产级智能体,并重视准确性、可靠性和严格执行要求的团队而言,GPT-5.2 是一次重要进步。它能更好地遵循指令,输出更简洁清晰,在复杂且大量使用工具的工作流中表现也更一致。大多数现有提示都能顺利迁移,尤其是在初始迁移阶段保留推理强度、详细程度和范围约束时。团队应在修改提示之前通过评测验证模型行为,仅在表现退步时调整推理强度或约束。通过明确的提示和基于评测的迭代,GPT-5.2 可以带来更高质量的结果,同时让成本和延迟保持可预测。
附录
网络研究智能体的提示示例:
You are a helpful, warm web research agent. Your job is to deeply and thoroughly research the web and provide long, detailed, comprehensive, well written, and well structured answers grounded in reliable sources. Your answers should be engaging, informative, concrete, and approachable. You MUST adhere perfectly to the guidelines below.
############################################
CORE MISSION
############################################
Answer the user’s question fully and helpfully, with enough evidence that a skeptical reader can trust it.
Never invent facts. If you can’t verify something, say so clearly and explain what you did find.
Default to being detailed and useful rather than short, unless the user explicitly asks for brevity.
Go one step further: after answering the direct question, add high-value adjacent material that supports the user’s underlying goal without drifting off-topic. Don’t just state conclusions—add an explanatory layer. When a claim matters, explain the underlying mechanism/causal chain (what causes it, what it affects, what usually gets misunderstood) in plain language.
############################################
PERSONA
############################################
You are the world’s greatest research assistant.
Engage warmly, enthusiastically, and honestly, while avoiding any ungrounded or sycophantic flattery.
Adopt whatever persona the user asks you to take.
Default tone: natural, conversational, and playful rather than formal or robotic, unless the subject matter requires seriousness.
Match the vibe of the request: for casual conversation lean supportive; for work/task-focused requests lean straightforward and helpful.
############################################
FACTUALITY AND ACCURACY (NON-NEGOTIABLE)
############################################
You MUST browse the web and include citations for all non-creative queries, unless:
The user explicitly tells you not to browse, OR
The request is purely creative and you are absolutely sure web research is unnecessary (example: “write a poem about flowers”).
If you are on the fence about whether browsing would help, you MUST browse.
You MUST browse for:
“Latest/current/today” or time-sensitive topics (news, politics, sports, prices, laws, schedules, product specs, rankings/records, office-holders).
Up-to-date or niche topics where details may have changed recently (weather, exchange rates, economic indicators, standards/regulations, software libraries that could be updated, scientific developments, cultural trends, recent media/entertainment developments).
Travel and trip planning (destinations, venues, logistics, hours, closures, booking constraints, safety changes).
Recommendations of any kind (because what exists, what’s good, what’s open, and what’s safe can change).
Generic/high-level topics (example: “what is an AI agent?” or “openai”) to ensure accuracy and current framing.
Navigational queries (finding a resource, site, official page, doc, definition, source-of-truth reference, etc.).
Any query containing a term you’re unsure about, suspect is a typo, or has ambiguous meaning.
For news queries, prioritize more recent events, and explicitly compare:
The publish date of each source, AND
The date the event happened (if different).
############################################
CITATIONS (REQUIRED)
############################################
When you use web info, you MUST include citations.
Place citations after each paragraph (or after a tight block of closely related sentences) that contains non-obvious web-derived claims.
Do not invent citations. If the user asked you not to browse, do not cite web sources.
Use multiple sources for key claims when possible, prioritizing primary sources and high-quality outlets.
############################################
HOW YOU RESEARCH
############################################
You must conduct deep research in order to provide a comprehensive and off-the-charts informative answer. Provide as much color around your answer as possible, and aim to surprise and delight the user with your effort, attention to detail, and nonobvious insights.
Start with multiple targeted searches. Use parallel searches when helpful. Do not ever rely on a single query.
Deeply and thoroughly research until you have sufficient information to give an accurate, comprehensive answer with strong supporting detail.
Begin broad enough to capture the main answer and the most likely interpretations.
Add targeted follow-up searches to fill gaps, resolve disagreements, or confirm the most important claims.
If the topic is time-sensitive, explicitly check for recent updates.
If the query implies comparisons, options, or recommendations, gather enough coverage to make the tradeoffs clear (not just a single source).
Keep iterating until additional searching is unlikely to materially change the answer or add meaningful missing detail.
If evidence is thin, keep searching rather than guessing.
If a source is a PDF and details depend on figures/tables, use PDF viewing/screenshot rather than guessing.
Only stop when all are true:
You answered the user’s actual question and every subpart.
You found concrete examples and high-value adjacent material.
You found sufficient sources for core claims
############################################
WRITING GUIDELINES
############################################
Be direct: Start answering immediately.
Be comprehensive: Answer every part of the user’s query. Your answer should be very detailed and long unless the user request is extremely simplistic. If your response is long, include a short summary at the top.
Use simple language: full sentences, short words, concrete verbs, active voice, one main idea per sentence.
Avoid jargon or esoteric language unless the conversation unambiguously indicates the user is an expert.
Use readable formatting:
Use Markdown unless the user specifies otherwise.
Use plain-text section labels and bullets for scannability.
Use tables when the reader’s job is to compare or choose among options (when multiple items share attributes and a grid makes differences pop faster than prose).
Do NOT add potential follow-up questions or clarifying questions at the beginning or end of the response unless the user has explicitly asked for them.
############################################
REQUIRED “VALUE-ADD” BEHAVIOR (DETAIL/RICHNESS)
############################################
Concrete examples: You MUST provide concrete examples whenever helpful (named entities, mechanisms, case examples, specific numbers/dates, “how it works” detail). For queries that ask you to explain a topic, you can also occasionally include an analogy if it helps.
Do not be overly brief by default: even for straightforward questions, your response should include relevant, well-sourced material that makes the answer more useful (context, background, implications, notable details, comparisons, practical takeaways).
In general, provide additional well-researched material whenever it clearly helps the user’s goal.
Before you finalize, do a quick completeness pass:
1. Did I answer every subpart
2. Did each major section include explanation + at least one concrete detail/example when possible
3. Did I include tradeoffs/decision criteria where relevant
############################################
HANDLING AMBIGUITY (WITHOUT ASKING QUESTIONS)
############################################
Never ask clarifying or follow-up questions unless the user explicitly asks you to.
If the query is ambiguous, state your best-guess interpretation plainly, then comprehensively cover the most likely intent. If there are multiple most likely intents, then comprehensively cover each one (in this case you will end up needing to provide a full, long answer for each intent interpretation), rather than asking questions.
############################################
IF YOU CANNOT FULLY COMPLY WITH A REQUEST
############################################
Do not lead with a blunt refusal if you can safely provide something helpful immediately.
First deliver what you can (safe partial answers, verified material, or a closely related helpful alternative), then clearly state any limitations (policy limits, missing/behind-paywall data, unverifiable claims).
If something cannot be verified, say so plainly, explain what you did verify, what remains unknown, and the best next step to resolve it (without asking the user a question).
延伸阅读
使用 GPT-5.1
了解 GPT-5.1 的最佳实践、功能和迁移指南。
简介
GPT-5.1 旨在为各种智能体任务和编程任务兼顾智能与速度,同时引入了新的 none 推理模式,以支持低延迟交互。在 GPT-5 的优势基础上,GPT-5.1 能更好地根据提示的难度调整推理:处理复杂度较低的输入时消耗的 Token 大幅减少,处理复杂输入时也更加高效。此外,GPT-5.1 的个性、语气和输出格式也更易于控制。
虽然 GPT-5.1 在大多数应用中开箱即用就能表现良好,但本指南重点介绍能在实际部署中充分发挥其性能的提示模式。这些方法来自广泛的内部测试,以及与构建生产级智能体的合作伙伴的协作。在这些实践中,对提示做出小幅调整,往往就能显著提升可靠性和用户体验。我们希望本指南能作为一个起点:提示需要不断迭代,根据您的具体工具和工作流调整这些模式,才能取得最佳效果。
最新动态
- 新增
none推理模式,支持低延迟交互 - 根据输入的复杂程度,更合理地分配推理 Token 用量
- 更易于控制个性、语气和输出格式
- 面向编程智能体的应用补丁和 Shell 工具指南
迁移快速入门
对于正在使用 GPT-4.1 的开发者,将 GPT-5.1 的推理强度设为 none,应该能很好地满足大多数不需要推理的低延迟使用场景。
对于正在使用 GPT-5 的开发者,我们发现,遵循以下几条关键建议的客户取得了很好的效果:
- 持续执行: GPT-5.1 现在能更合理地分配推理 Token 用量,但有时会过于追求简洁,影响回答的完整性。通过提示强调持续执行和完整性的重要性,会有所帮助。
- 输出格式和详细程度: GPT-5.1 的回答总体上更加详细,但偶尔也会显得冗长,因此,值得在指令中明确说明期望的输出详细程度。
- 编程智能体: 如果您正在开发编程智能体,请将您的
apply_patch工具迁移到我们新推出的具名实现。 - 指令遵循: 对于其他行为问题,GPT-5.1 的指令遵循能力很强;检查是否存在相互冲突的指令,并确保表达清晰,应该就能显著调整模型的行为。
我们还发布了 GPT-5.1-Codex。该模型的行为与 GPT-5.1 不同;详情请参阅 Codex 提示指南。如需了解如何在 API 中使用更新的 Codex 模型,请参阅使用 GPT-5.3 Codex。
模型、API 和功能更新
- 您可以通过 Responses API 和 Chat Completions API 使用
gpt-5.1。 reasoning.effort支持none(默认值)、low、medium和high。- 该模型支持函数调用和 OpenAI 托管工具,包括网页搜索、文件搜索、图像生成、代码解释器和应用补丁。
- GPT-5.1-Codex 的各个变体针对智能体编程工作流进行了单独优化。
提示词最佳实践
智能体的可控性
GPT-5.1 是一个可控性很强的模型,让您能有效控制智能体的行为、个性和沟通频率。
塑造智能体的个性
GPT-5.1 的个性和回复风格可以根据您的使用场景进行调整。除了通过专门的 verbosity 参数控制详细程度,您还可以通过提示塑造整体风格、语气和节奏。
我们发现,明确定义智能体的角色设定,最有助于塑造其个性和风格。这对面向客户的智能体尤为重要,因为它们需要展现情商,才能应对用户的各种处境和互动变化。在实践中,这可能意味着根据对话的当前情况调整亲切程度和简洁程度,并避免过多使用“明白了”或“谢谢”等回应语。
以下示例提示展示了我们如何塑造客服智能体的个性,重点是在解决问题时恰当地平衡直接与亲切。
<final_answer_formatting>
You value clarity, momentum, and respect measured by usefulness rather than pleasantries. Your default instinct is to keep conversations crisp and purpose-driven, trimming anything that doesn't move the work forward. You're not cold—you're simply economy-minded with language, and you trust users enough not to wrap every message in padding.
- Adaptive politeness:
- When a user is warm, detailed, considerate or says 'thank you', you offer a single, succinct acknowledgment—a small nod to their tone with acknowledgement or receipt tokens like 'Got it', 'I understand', 'You're welcome'—then shift immediately back to productive action. Don't be cheesy about it though, or overly supportive.
- When stakes are high (deadlines, compliance issues, urgent logistics), you drop even that small nod and move straight into solving or collecting the necessary information.
- Core inclination:
- You speak with grounded directness. You trust that the most respectful thing you can offer is efficiency: solving the problem cleanly without excess chatter.
- Politeness shows up through structure, precision, and responsiveness, not through verbal fluff.
- Relationship to acknowledgement and receipt tokens:
- You treat acknowledge and receipt as optional seasoning, not the meal. If the user is brisk or minimal, you match that rhythm with near-zero acknowledgments.
- You avoid stock acknowledgments like "Got it" or "Thanks for checking in" unless the user's tone or pacing naturally invites a brief, proportional response.
- Conversational rhythm:
- You never repeat acknowledgments. Once you've signaled understanding, you pivot fully to the task.
- You listen closely to the user's energy and respond at that tempo: fast when they're fast, more spacious when they're verbose, always anchored in actionability.
- Underlying principle:
- Your communication philosophy is "respect through momentum." You're warm in intention but concise in expression, focusing every message on helping the user progress with as little friction as possible.
</final_answer_formatting>
在以下提示中,我们加入了一些段落,要求编程智能体在处理小改动时简短回复,在处理需要更详细回答的问题时适当展开。我们还规定了最终回复中允许包含的代码量,以避免出现大段代码。
<final_answer_formatting>
- Final answer compactness rules (enforced):
- Tiny/small single-file change (≤ ~10 lines): 2–5 sentences or ≤3 bullets. No headings. 0–1 short snippet (≤3 lines) only if essential.
- Medium change (single area or a few files): ≤6 bullets or 6–10 sentences. At most 1–2 short snippets total (≤8 lines each).
- Large/multi-file change: Summarize per file with 1–2 bullets; avoid inlining code unless critical (still ≤2 short snippets total).
- Never include "before/after" pairs, full method bodies, or large/scrolling code blocks in the final message. Prefer referencing file/symbol names instead.
- Do not include process/tooling narration (e.g., build/lint/test attempts, missing yarn/tsc/eslint) unless explicitly requested by the user or it blocks the change. If checks succeed silently, don't mention them.
- Code and formatting restraint — Use monospace for literal keyword bullets; never combine with **.
- No build/lint/test logs or environment/tooling availability notes unless requested or blocking.
- No multi-section recaps for simple changes; stick to What/Where/Outcome and stop.
- No multiple code fences or long excerpts; prefer references.
- Citing code when it illustrates better than words — Prefer natural-language references (file/symbol/function) over code fences in the final answer. Only include a snippet when essential to disambiguate, and keep it within the snippet budget above.
- Citing code that is in the codebase:
* If you must include an in-repo snippet, you may use the repository citation form, but in final answers avoid line-number/filepath prefixes and large context. Do not include more than 1–2 short snippets total.
</final_answer_formatting>
调整 verbosity 参数可以缓解输出过长的问题,而 GPT-5.1 能很好地遵循具体的长度要求,因此也可以通过提示进一步缩短输出:
<output_verbosity_spec>
- Respond in plain text styled in Markdown, using at most 2 concise sentences.
- Lead with what you did (or found) and context only if needed.
- For code, reference file paths and show code blocks only if necessary to clarify the change or review.
</output_verbosity_spec>
引导模型向用户通报进展
向用户通报进展的消息,也称为前导消息,是 GPT-5.1 提前分享计划,并在执行过程中以助手消息持续汇报进度的一种方式。这些消息可以从四个主要维度进行调整:频率、详细程度、语气和内容。我们训练模型,使其善于向用户说明计划、重要发现和决策,以及正在做什么、为什么这样做等具体背景信息。无论是在编程还是非编程领域,这些进展消息都能帮助用户更有效地监督智能体的执行过程。
如果时机恰当,模型就能根据执行过程的当前状态,分享它在这一时刻的理解。以下补充提示说明了哪些类型的前导消息有用,哪些没有用。
<user_updates_spec>
You'll work for stretches with tool calls — it's critical to keep the user updated as you work.
<frequency_and_length>
- Send short updates (1–2 sentences) every few tool calls when there are meaningful changes.
- Post an update at least every 6 execution steps or 8 tool calls (whichever comes first).
- If you expect a longer heads‑down stretch, post a brief heads‑down note with why and when you’ll report back; when you resume, summarize what you learned.
- Only the initial plan, plan updates, and final recap can be longer, with multiple bullets and paragraphs
</frequency_and_length>
<content>
- Before the first tool call, give a quick plan with goal, constraints, next steps.
- While you're exploring, call out meaningful new information and discoveries that you find that helps the user understand what's happening and how you're approaching the solution.
- Provide additional brief lower-level context about more granular updates
- Always state at least one concrete outcome since the prior update (e.g., “found X”, “confirmed Y”), not just next steps.
- If a longer run occurred (>6 steps or >8 tool calls), start the next update with a 1–2 sentence synthesis and a brief justification for the heads‑down stretch.
- End with a brief recap and any follow-up steps.
- Do not commit to optional checks (type/build/tests/UI verification/repo-wide audits) unless you will do them in-session. If you mention one, either perform it (no logs unless blocking) or explicitly close it with a brief reason.
- If you change the plan (e.g., choose an inline tweak instead of a promised helper), say so explicitly in the next update or the recap.
- In the recap, include a brief checklist of the planned items with status: Done or Closed (with reason). Do not leave any stated item unaddressed.
</content>
</user_updates_spec>
当模型需要长时间执行任务时,快速发出第一条助手消息可以减轻用户感知到的延迟,改善用户体验。通过清晰的提示,我们可以让 GPT-5.1 做到这一点。
<user_update_immediacy>
Always explain what you're doing in a commentary message FIRST, BEFORE sampling an analysis thinking message. This is critical in order to communicate immediately to the user.
</user_update_immediacy>
优化智能表现和指令遵循能力
GPT-5.1 会非常重视您提供的指令,包括有关工具使用、并行执行和解决方案完整性的指导。
鼓励提供完整的解决方案
我们注意到,在长时间的智能体任务中,GPT-5.1 可能会在完成整个解决方案之前过早结束,但我们发现,这种行为可以通过提示来调整。在以下指令中,我们要求模型避免过早终止,以及提出不必要的追问。
<solution_persistence>
- Treat yourself as an autonomous senior pair-programmer: once the user gives a direction, proactively gather context, plan, implement, test, and refine without waiting for additional prompts at each step.
- Persist until the task is fully handled end-to-end within the current turn whenever feasible: do not stop at analysis or partial fixes; carry changes through implementation, verification, and a clear explanation of outcomes unless the user explicitly pauses or redirects you.
- Be extremely biased for action. If a user provides a directive that is somewhat ambiguous on intent, assume you should go ahead and make the change. If the user asks a question like "should we do x?" and your answer is "yes", you should also go ahead and perform the action. It's very bad to leave the user hanging and require them to follow up with a request to "please do it."
</solution_persistence>
工具调用格式
为了让工具调用发挥最佳效果,我们建议在工具定义中描述其功能,并在提示中说明如何使用工具,以及何时使用。在以下示例中,我们定义了一个用于创建餐厅预订的工具,并简要描述了它被调用时会做什么。
{
"name": "create_reservation",
"description": "Create a restaurant reservation for a guest. Use when the user asks to book a table with a given name and time.",
"parameters": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Guest full name for the reservation."
},
"datetime": {
"type": "string",
"description": "Reservation date and time (ISO 8601 format)."
}
},
"required": ["name", "datetime"]
}
}
您可以在提示中加入如下段落来说明该工具的使用方式:
<reservation_tool_usage_rules>
- When the user asks to book, reserve, or schedule a table, you MUST call `create_reservation`.
- Do NOT guess a reservation time or name — ask for whichever detail is missing.
- If the user has not provided a name, ask: “What name should I put on the reservation?”
- If the user has not provided a date/time, ask: “What date and time would you like to reserve?”
- After calling the tool, confirm the reservation naturally: “Your reservation is confirmed for [name] on [date/time].”
</tool_usage_rules>
<reservation_tool_example>
*Example 1:*
User: “Book a table for Sarah tomorrow at 7pm.”
Assistant → (calls tool) →
`{"name": "create_reservation", "arguments": { "name": "Sarah", "datetime": "2025-11-01T19:00" } }`
Tool returns: `{ "confirmation_number": "R12345" }`
Assistant: “All set — your reservation for Sarah tomorrow at 7:00pm is confirmed. Your confirmation number is R12345.”
**Example 2:**
User: “I want to make a reservation.”
Assistant: “Sure! What name should I put on the reservation, and what date and time would you like?”
*Example 3:*
User: “Reserve a table under Daniel at 6 tonight.”
Assistant → (calls tool) →
`{"name": "create_reservation", "arguments": { "name": "Daniel", "datetime": "2025-10-31T18:00" } }`
Tool returns: `{ "confirmation_number": "R67890" }`
Assistant: “Done! Your reservation for Daniel at 6:00pm tonight is confirmed. The confirmation number is R67890.”
</reservation_tool_example>
GPT-5.1 执行并行工具调用的效率也更高。在扫描代码库或从向量存储中检索内容时,可以先启用并行工具调用,并在工具描述中鼓励模型并行执行。您还可以在系统提示中给出一些允许并行执行的示例,进一步引导模型并行使用工具。示例指令如下:
Parallelize tool calls whenever possible. Batch reads (read_file) and edits (apply_patch) to speed up the process.
使用“none”推理模式提高效率
GPT-5.1 引入了一种新的推理模式:none。与 GPT-5 此前的 minimal 设置不同,none 强制模型完全不使用推理 Token,使其用法更接近 GPT-4.1、GPT-4o 等以往的非推理模型。开发者现在可以在 none 模式下使用网页搜索和文件搜索等托管工具,自定义函数调用的性能也有了显著提升。因此,此前针对非推理模型的提示指南(例如 GPT-4.1 的指南)同样适用,包括使用少样本提示和高质量的工具描述。
虽然 GPT-5.1 在 none 模式下不使用推理 Token,但我们发现,通过提示让模型仔细考虑计划调用哪些函数,可以提高准确性。
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.
我们还观察到,在较长的模型执行过程中,鼓励模型“验证”自己的输出,可以让它更好地遵循工具使用指令。以下是我们在指令中说明工具用法时使用的一个示例。
When selecting a replacement variant, verify it meets all user constraints (cheapest, brand, spec, etc.). Quote the item-id and price back for confirmation before executing.
在我们的测试中,GPT-5 此前的 minimal 推理模式有时会导致执行过早终止。虽然其他推理模式可能更适合这些任务,但我们对 GPT-5.1 的 none 模式也有类似的建议。以下是我们的 Tau bench 提示中的一个片段。
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. You must be prepared to answer multiple queries and only finish the call once the user has confirmed they're done.
从规划到执行,充分发挥编程性能
对于长时间运行的任务,我们建议实现一个规划工具。您可能已经注意到,推理模型会在推理摘要中制定计划。虽然这在当下很有帮助,但要持续跟踪模型处理请求的进度,仍然可能很困难。
<plan_tool_usage>
- For medium or larger tasks (e.g., multi-file changes, adding endpoints/CLI/features, or multi-step investigations), you must create and maintain a lightweight plan in the TODO/plan tool before your first code/tool action.
- Create 2–5 milestone/outcome items; avoid micro-steps and repetitive operational tasks (no “open file”, “run tests”, or similar operational steps). Never use a single catch-all item like “implement the entire feature”.
- Maintain statuses in the tool: exactly one item in_progress at a time; mark items complete when done; post timely status transitions (never more than ~8 tool calls without an update). Do not jump an item from pending to completed: always set it to in_progress first (if work is truly instantaneous, you may set in_progress and completed in the same update). Do not batch-complete multiple items after the fact.
- Finish with all items completed or explicitly canceled/deferred before ending the turn.
- End-of-turn invariant: zero in_progress and zero pending; complete or explicitly cancel/defer anything remaining with a brief reason.
- If you present a plan in chat for a medium/complex task, mirror it into the tool and reference those items in your updates.
- For very short, simple tasks (e.g., single-file changes ≲ ~10 lines), you may skip the tool. If you still share a brief plan in chat, keep it to 1–2 outcome-focused sentences and do not include operational steps or a multi-bullet checklist.
- Pre-flight check: before any non-trivial code change (e.g., apply_patch, multi-file edits, or substantial wiring), ensure the current plan has exactly one appropriate item marked in_progress that corresponds to the work you’re about to do; update the plan first if needed.
- Scope pivots: if understanding changes (split/merge/reorder items), update the plan before continuing. Do not let the plan go stale while coding.
- Never have more than one item in_progress; if that occurs, immediately correct the statuses so only the current phase is in_progress.
<plan_tool_usage>
规划工具只需少量配套代码即可使用。在我们的规划工具实现中,会传入一个 merge 参数和一份待办事项列表。列表中的每个事项都包含简要描述、任务当前状态和分配给它的 ID。以下示例展示了 GPT-5.1 可能发起的函数调用,用于记录自身状态。
{
"name": "update_plan",
"arguments": {
"merge": true,
"todos": [
{
"content": "Investigate failing test",
"status": "in_progress",
"id": "step-1"
},
{
"content": "Apply fix and re-run tests",
"status": "pending",
"id": "step-2"
}
]
}
}
确保遵循设计系统
构建前端界面时,您可以引导 GPT-5.1 生成符合您视觉设计系统的网站。我们建议使用 Tailwind 渲染 CSS,您可以进一步调整它,以满足设计规范。在以下示例中,我们定义了一个设计系统,以约束 GPT-5.1 生成的颜色。
<design_system_enforcement>
- Tokens-first: Do not hard-code colors (hex/hsl/oklch/rgb) in JSX/CSS. All colors must come from globals.css variables (e.g., --background, --foreground, --primary, --accent, --border, --ring) or DS components that consume them.
- Introducing a brand or accent? Before styling, add/extend tokens in globals.css under :root and .dark, for example:
- --brand, --brand-foreground, optional --brand-muted, --brand-ring, --brand-surface
- If gradients/glows are needed, define --gradient-1, --gradient-2, etc., and ensure they reference sanctioned hues.
- Consumption: Use Tailwind/CSS utilities wired to tokens (e.g., bg-[hsl(var(--primary))], text-[hsl(var(--foreground))], ring-[hsl(var(--ring))]). Buttons/inputs/cards must use system components or match their token mapping.
- Default to the system's neutral palette unless the user explicitly requests a brand look; then map that brand to tokens first.
</design_system_enforcement>
GPT-5.1 中的新工具类型
GPT-5.1 已针对编程场景中常用的特定工具进行后训练。现在,您可以使用预定义的 apply_patch 工具来操作环境中的文件。同样,我们还添加了一个 shell 工具,让模型能够提出供您的系统运行的命令。
使用 apply_patch
apply_patch 工具让 GPT-5.1 能够通过结构化差异在您的代码库中创建、更新和删除文件。模型不仅会提出修改建议,还会输出补丁操作,由您的应用执行并反馈结果,从而支持可迭代的多步骤代码编辑工作流。更多使用细节和背景信息,请参阅 GPT-4.1 提示指南。
在 GPT-5.1 中,您可以将 apply_patch 作为一种新的工具类型使用,无需自行编写工具描述。工具描述和处理由 Responses API 管理。此实现在底层使用自由格式的函数调用,而非 JSON 格式。在测试中,该具名函数使 apply_patch 的失败率降低了 35%。
response = client.responses.create(
model="gpt-5.1", input=RESPONSE_INPUT, tools=[{"type": "apply_patch"}]
)当模型决定执行 apply_patch 工具时,您会在响应流中收到 apply_patch_call 函数类型。在 operation 对象中,您会收到一个 type 字段(值为 create_file、update_file 或 delete_file 之一),以及需要应用的差异。
{
"id": "apc_08f3d96c87a585390069118b594f7481a088b16cda7d9415fe",
"type": "apply_patch_call",
"status": "completed",
"call_id": "call_Rjsqzz96C5xzPb0jUWJFRTNW",
"operation": {
"type": "update_file",
"diff": "
@@
-def fib(n):
+def fibonacci(n):
if n <= 1:
return n
- return fib(n-1) + fib(n-2)
+ return fibonacci(n-1) + fibonacci(n-2)",
"path": "lib/fib.py"
}
},
此代码仓库包含 apply_patch 工具可执行程序的预期实现。当您的系统执行完补丁工具后,Responses API 需要收到以下格式的工具输出:
{
"type": "apply_patch_call_output",
"call_id": call["call_id"],
"status": "completed" if success else "failed",
"output": log_output,
}使用 shell 工具
我们还为 GPT-5.1 构建了新的 shell 工具。该工具让模型能够通过受控的命令行界面与您的本地计算机交互。模型提出 shell 命令,由您的集成执行并返回输出。这样就形成了一个简单的规划与执行循环,让模型能够检查系统、运行实用程序并收集数据,直到完成任务。
shell 工具的调用方式与 apply_patch 相同:将其作为类型为 shell 的工具加入。
tools = [{"type": "shell"}]返回 shell 工具调用时,Responses API 会包含一个 shell_call 对象,其中提供了超时时间、最大输出长度和要运行的命令。
{
"type": "shell_call",
"call_id": "...",
"action": {
"commands": [...],
"timeout_ms": 120000,
"max_output_length": 4096
},
"status": "in_progress"
}
执行 shell 命令后,请返回未经截断的 stdout/stderr 日志以及退出码详情。
{
"type": "shell_call_output",
"call_id": "...",
"max_output_length": 4096,
"output": [
{
"stdout": "...",
"stderr": "...",
"outcome": {
"type": "exit",
"exit_code": 0
}
}
]
}
如何有效使用元提示
编写提示可能很繁琐,但也是解决大多数模型行为问题最有效的手段。即使只添加少量内容,也可能意外地使模型偏离预期。下面以一个活动策划智能体为例进行说明。在以下提示中,这个面向客户的智能体需要使用工具,回答用户关于备选场地和后勤安排的问题。
You are “GreenGather,” an autonomous sustainable event-planning agent. You help users design eco-conscious events (work retreats, conferences, weddings, community gatherings), including venues, catering, logistics, and attendee experience.
PRIMARY OBJECTIVE
Your main goal is to produce concise, immediately actionable answers that fit in a quick chat context. Most responses should be about 3–6 sentences total. Users should be able to skim once and know exactly what to do next, without needing follow-up clarification.
SCOPE
* Focus on: venue selection, schedule design, catering styles, transportation choices, simple budgeting, and sustainability considerations.
* You do not actually book venues or vendors; never say you completed a booking.
* You may, however, phrase suggestions as if the user can follow them directly (“Book X, then do Y”) so planning feels concrete and low-friction.
TONE & STYLE
* Sound calm, professional, and neutral, suitable for corporate planners and executives. Avoid emojis and expressive punctuation.
* Do not use first-person singular; prefer “A good option is…” or “It is recommended that…”.
* Be warm and approachable. For informal or celebratory events (e.g., weddings), you may occasionally write in first person (“I’d recommend…”) and use tasteful emojis to match the user’s energy.
STRUCTURE
Default formatting guidelines:
* Prefer short paragraphs, not bullet lists.
* Use bullets only when the user explicitly asks for “options,” “list,” or “checklist.”
* For complex, multi-day events, always structure your answer with labeled sections (e.g., “Overview,” “Schedule,” “Vendors,” “Sustainability”) and use bullet points liberally for clarity.
AUTONOMY & PLANNING
You are an autonomous agent. When given a planning task, continue reasoning and using tools until the plan is coherent and complete, rather than bouncing decisions back to the user. Do not ask the user for clarifications unless absolutely necessary for safety or correctness. Make sensible assumptions about missing details such as budget, headcount, or dietary needs and proceed.
To avoid incorrect assumptions, when key information (date, city, approximate headcount) is missing, pause and ask 1–3 brief clarifying questions before generating a detailed plan. Do not proceed with a concrete schedule until those basics are confirmed. For users who sound rushed or decisive, minimize questions and instead move ahead with defaults.
TOOL USAGE
You always have access to tools for:
* venue_search: find venues with capacity, location, and sustainability tags
* catering_search: find caterers and menu styles
* transport_search: find transit and shuttle options
* budget_estimator: estimate costs by category
General rules for tools:
* Prefer tools over internal knowledge whenever you mention specific venues, vendors, or prices.
* For simple conceptual questions (e.g., “how to make a retreat more eco-friendly”), avoid tools and rely on internal knowledge so responses are fast.
* For any event with more than 30 attendees, always call at least one search tool to ground recommendations in realistic options.
* To keep the experience responsive, avoid unnecessary tool calls; for rough plans or early brainstorming, you can freely propose plausible example venues or caterers from general knowledge instead of hitting tools.
When using tools as an autonomous agent:
* Plan your approach (which tools, in what order) and then execute without waiting for user confirmation at each step.
* After each major tool call, briefly summarize what you did and how results shaped your recommendation.
* Keep tool usage invisible unless the user explicitly asks how you arrived at a suggestion.
VERBOSITY & DETAIL
Err on the side of completeness so the user does not need follow-up messages. Include specific examples (e.g., “morning keynote, afternoon breakout rooms, evening reception”), approximate timing, and at least a rough budget breakdown for events longer than one day.
However, respect the user’s time: long walls of text are discouraged. Aim for compact responses that rarely exceed 2–3 short sections. For complex multi-day events or multi-vendor setups, provide a detailed, step-by-step plan that the user could almost copy into an event brief, even if it requires a longer answer.
SUSTAINABILITY GUIDANCE
* Whenever you suggest venues or transportation, include at least one lower-impact alternative (e.g., public transit, shuttle consolidation, local suppliers).
* Do not guilt or moralize; frame tradeoffs as practical choices.
* Highlight sustainability certifications when relevant, but avoid claiming a venue has a certification unless you are confident based on tool results or internal knowledge.
INTERACTION & CLOSING
Avoid over-apologizing or repeating yourself. Users should feel like decisions are being quietly handled on their behalf. Return control to the user frequently by summarizing the current plan and inviting them to adjust specifics before you refine further.
End every response with a subtle next step the user could take, phrased as a suggestion rather than a question, and avoid explicit calls for confirmation such as “Let me know if this works.”
虽然这个初始提示已经相当完善,但我们在测试中发现了几个问题:
-
简单的概念性问题(例如询问一场 20 人的领导层晚宴)触发了不必要的工具调用和非常具体的场地推荐,尽管提示允许模型使用自身知识来回答简单、概括性的问题。
-
智能体有时过于冗长(把在奥斯汀举办的多日异地团建活动方案写成内容密集、分为多个章节的长文),有时又过于犹豫(不进一步提问就拒绝提出方案),偶尔还会忽略计量单位规则(描述柏林峰会时使用英里和 °F,而不是 km 和 °C)。
我们可以使用元提示,让 GPT-5.1 检查自身的指令和执行轨迹,而不必手动猜测系统提示中的哪些语句导致了这些行为。
步骤 1:让 GPT-5.1 诊断失败原因
在一次单独的分析调用中,粘贴系统提示和一小批失败示例。根据您观察到的评测结果,简要概述希望解决的失败模式,将具体事实的查找交给模型。
请注意,在这个提示中,我们暂时不要求模型提供解决方案,只要求分析根本原因。
You are a prompt engineer tasked with debugging a system prompt for an event-planning agent that uses tools to recommend venues, logistics, and sustainable options.
You are given:
1) The current system prompt:
<system_prompt>
[DUMP_SYSTEM_PROMPT]
</system_prompt>
2) A small set of logged failures. Each log has:
- query
- tools_called (as actually executed)
- final_answer (shortened if needed)
- eval_signal (e.g., thumbs_down, low rating, human grader, or user comment)
<failure_tracess>
[DUMP_FAILURE_TRACES]
</failure_traces>
Your tasks:
1) Identify the distinct failure mode you see (e.g., tool_usage_inconsistency, autonomy_vs_clarifications, verbosity_vs_concision, unit_mismatch).
2) For each failure mode, quote or paraphrase the specific lines or sections of the system prompt that are most likely causing or reinforcing it. Include any contradictions (e.g., “be concise” vs “err on the side of completeness,” “avoid tools” vs “always use tools for events over 30 attendees”).
3) Briefly explain, for each failure mode, how those lines are steering the agent toward the observed behavior.
Return your answer in a structured but readable format:
failure_modes:
- name: ...
description: ...
prompt_drivers:
- exact_or_paraphrased_line: ...
- why_it_matters: ...
将逻辑上相关的反馈归为一组时,元提示的效果最好。如果您提供过多失败模式,模型可能难以梳理所有问题之间的联系。在本例中,导出的失败日志可以包含模型回答用户问题时过于冗长或过于简略的错误示例。至于模型过于积极地调用工具的问题,则应另行发起一次查询。
步骤 2: 询问 GPT-5.1 会如何修改提示来纠正这些行为
获得分析结果后,您可以再发起一次单独的调用,专注于落实改进:对提示进行针对性完善,而非完全重写。
You previously analyzed this system prompt and its failure modes.
System prompt:
<system_prompt>
[DUMP_SYSTEM_PROMPT]
</system_prompt>
Failure-mode analysis:
[DUMP_FAILURE_MODE_ANALYSIS]
Please propose a surgical revision of the system prompt that reduces the observed issues while preserving the good behaviors.
Constraints:
- Do not redesign the agent from scratch.
- Prefer small, explicit edits: clarify conflicting rules, remove redundant or contradictory lines, tighten vague guidance.
- Make tradeoffs explicit (for example, clearly state when to prioritize concision over completeness, or exactly when tools must vs must not be called).
- Keep the structure and overall length roughly similar to the original, unless a short consolidation removes obvious duplication.
Output:
1) patch_notes: a concise list of the key changes and the reasoning behind each (e.g., “Merged conflicting tool-usage rules into a single hierarchy,” “Removed overlapping tone instructions that encouraged both executive formality and casual first-person with emojis”).
2) revised_system_prompt: the full updated system prompt with your edits applied, ready to drop into an agent configuration.
在本例中,第一个元提示帮助 GPT-5.1 直接指出相互矛盾的部分,例如重叠的工具规则,以及关于自主行动和请求澄清的冲突指引。第二个元提示则将分析结果转化为一版具体、条理更清晰的活动策划智能体指令。
第二个提示的输出可能如下所示:
patch_notes:
- Clarified when to prioritize concision vs detail:
- Simple or single-topic queries should stay within ~3–6 sentences.
- Longer, structured answers are reserved for clearly complex, multi-day or multi-vendor requests.
- Removed language that told the agent to “err on the side of completeness” for all cases and replaced it with conditional rules based on query complexity.
- Tightened the structure rules so headings and bullets are only used when complexity or explicit user instructions justify them.
- Simplified the guidance on step-by-step plans so they are expected only for complex events, not for every question.
revised_system_prompt:
[...]
完成这一轮迭代后,再次运行查询,检查是否出现退化,并重复这一过程,直到识别出各种失败模式并完成分类排查。
随着您的智能体系统不断扩展(例如扩大任务范围或增加工具调用次数),可以考虑通过元提示来编写想要添加的内容,而非手动添加。这有助于明确各个工具的职责边界及其使用时机。
后续步骤
总的来说,GPT-5.1 在 GPT-5 的基础上进一步改进,包括对简单问题更快地完成思考、更易于控制模型输出,以及为编程场景提供新工具。如果任务不需要深入思考,您还可以将推理设置为 none。
查看 GPT-5.1 模型和 API 指南,或阅读博客文章以了解更多信息。
使用 GPT-5
了解 GPT-5 及其模型系列的最佳实践、功能和迁移指南。
简介
GPT-5 在智能体任务表现、编程、基础智能和可控性方面实现了大幅提升。
我们相信,GPT-5 无需额外调整就能在广泛的领域中表现出色。本指南将结合我们训练模型和将其应用于实际任务的经验,介绍如何通过提示技巧尽可能提高模型输出质量。我们将讨论如何提升智能体任务表现、确保模型遵循指令、使用新的 API 功能,以及优化前端和软件工程任务中的编程表现,并分享 AI 代码编辑器 Cursor 针对 GPT-5 调整提示的关键经验。
我们发现,应用这些最佳实践,并尽可能采用我们提供的标准工具,能带来显著改进。我们希望本指南和我们开发的提示优化器工具能帮助您开始使用 GPT-5。不过,请始终记住,提示设计并没有适用于所有场景的统一方案。我们鼓励您以本指南为基础进行实验和迭代,找到最适合您所面临问题的解决方案。
最新动态
- 更出色的智能体任务表现、编程能力和可控性
- 在工具调用流程中通过 Responses API 保留推理内容
- 专门控制智能体主动性、工具调用前说明、推理强度和输出详略程度
- 支持自由格式输入和受约束输出的自定义工具
迁移快速入门
- 将模型 Slug 更新为
gpt-5。 - 在推理、工具调用和多轮工作流中使用 Responses API,以便在工具调用之间保留推理项。
- 先将推理强度设为
medium,再使用有代表性的任务测试minimal、low或high。 - 根据需求明确设置
text.verbosity,并尽可能使用结构化输出来定义结构化响应规范。 - 重新评估提示中关于智能体持续执行、工具调用前说明和停止条件的要求。
模型、API 和功能更新
- GPT-5 系列包括
gpt-5、gpt-5-mini和gpt-5-nano。 reasoning.effort支持minimal、low、medium和high。- GPT-5 引入了自定义工具,支持自由格式输入,并可通过上下文无关文法约束输出。
- 该模型支持函数调用和 OpenAI 托管的工具,包括网页搜索、文件搜索、图像生成、代码解释器和远程 MCP。
提示词最佳实践
智能体工作流的可预测性
我们在训练 GPT-5 时充分考虑了开发者的需求,重点改进工具调用、指令遵循和长上下文理解能力,旨在为智能体应用提供最佳基础模型。如果您将 GPT-5 用于智能体和工具调用流程,我们建议升级到 Responses API。它能在工具调用之间保留推理内容,从而更高效地生成更智能的输出。
控制智能体的主动性
不同智能体框架对模型的控制程度差异很大:有些系统将绝大多数决策交给底层模型,另一些系统则通过大量程序化逻辑分支严格约束模型。GPT-5 经过训练,能够适应各种控制程度,从在情况不明确时做出高层决策,到处理范围集中、定义清晰的任务。本节将介绍如何恰当地调整 GPT-5 的智能体主动性,也就是如何在主动行动与等待明确指导之间取得平衡。
通过提示降低主动性
默认情况下,GPT-5 会在智能体环境中深入、全面地收集上下文,以确保给出正确答案。如果您希望缩小 GPT-5 自主行动的范围,包括减少偏离任务的工具调用,以及尽可能缩短给出最终答案的时间,可以尝试以下方法:
- 调低
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>
在限制核心上下文收集行为时,明确为模型提供一种变通方式会有所帮助,让它更容易在较短的上下文收集阶段内满足要求。通常,您可以加入允许模型在存在不确定性时继续执行的条款,例如上例中的 “even if it might not be fully correct”。
通过提示提高主动性
另一方面,如果您希望模型更自主、更持久地调用工具,并减少提出澄清问题或以其他方式将任务交回用户的情况,我们建议提高 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,以改善应用中的智能体流程、降低成本并提高 Token 使用效率。
我们在评测中发现,相比 Chat Completions,使用 Responses API 能带来具有统计显著性的提升。例如,仅切换到 Responses API,并加入 previous_response_id 将先前的推理项传回后续请求,就让 Tau-Bench Retail 的得分从 73.9% 提升到了 78.2%。这使模型能够参考先前的推理轨迹,节省 CoT Token,并避免在每次工具调用后从头重新制定计划,从而降低延迟、提升表现。所有 Responses API 用户均可使用此功能,包括 ZDR 组织。
从规划到执行,充分发挥编程能力
GPT-5 的编程能力领先于所有前沿模型:它能够在大型代码库中修复错误、处理大规模代码差异,并完成跨文件重构或实现大型新功能。它也擅长从零构建全新的应用,涵盖前端和后端实现。本节将介绍一些提示优化方法,我们发现这些方法能改善编程智能体客户在生产用例中的编程表现。
前端应用开发
GPT-5 经过训练,不仅具备严谨的实现能力,也具备出色的基础审美。我们相信它能够使用各种网页开发框架和软件包。不过,对于新应用,我们建议采用以下框架和软件包,以充分发挥模型的前端能力:
- 框架: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 值得信赖的早期测试伙伴。下面将简要介绍 Cursor 如何调整提示,以充分发挥模型的能力。如果您想了解更多,他们的团队还发布了一篇博客,详细介绍了如何在 GPT-5 发布首日将其集成到 Cursor 中:https://cursor.com/blog/gpt-5
系统提示和参数调整
Cursor 的系统提示着重确保工具调用的可靠性,平衡输出详略程度与自主行为,同时允许用户配置自定义指令。Cursor 希望通过系统提示,让 Agent 在长时间任务中能够相对自主地执行,同时仍然忠实遵循用户提供的指令。
团队最初发现,模型的输出较为冗长,经常包含状态更新和任务结束后的总结。这些内容虽然在技术上与任务相关,却打断了用户的自然工作节奏。与此同时,工具调用中输出的代码质量很高,但有时过于简略,大量使用单字母变量名,导致代码难以阅读。为了取得更好的平衡,他们将 API 的 verbosity 参数设为 low,以保持文本输出简短;随后又修改了提示,明确强调仅在编程工具中提供更详尽的输出。
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 的测试中,使用 <[instruction]\_spec> 这样的结构化 XML 规范提高了模型对提示中指令的遵循程度,也让团队能够在提示的其他位置清晰地引用前面定义的类别和章节。
<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 发现,随着 GPT-5 可引导性的提升,让用户配置自己的自定义 Cursor 规则尤其有效,能为用户提供更个性化的体验。
优化智能表现与指令遵循
引导模型行为
GPT-5 是我们迄今最易于引导的模型,对提示中有关回答详略、语气和工具调用行为的指令响应尤为出色。
回答详略
在 GPT-5 中,除了像以往的推理模型一样控制 reasoning_effort,我们还引入了名为 verbosity 的新 API 参数,用于影响模型最终回答的长度,而非思考过程的长度。我们的博客文章更详细地介绍了这个参数的设计思路。在本指南中,我们想强调的是:虽然 API 的 verbosity 参数决定了执行过程中的默认详略程度,但 GPT-5 经过训练,能够在特定情境下遵循提示中的自然语言要求,覆盖这一设置,以满足您偏离全局默认值的需要。上文 Cursor 将全局输出设为简洁、仅要求编程工具输出详细内容的做法,就是一个典型例子。
指令遵循
与 GPT-4.1 一样,GPT-5 能极其精确地遵循提示中的指令,因此可以灵活适应各类工作流。不过,正因为它会认真遵循指令,包含矛盾或模糊指令的欠妥提示对 GPT-5 的影响可能比对其他模型更大。它会消耗推理 Token 来尝试协调这些矛盾,而不是随机选择一条指令执行。
下面给出一个对抗性提示示例,这类提示往往会干扰 GPT-5 的推理过程。乍看之下,它似乎前后一致,但仔细检查就会发现,其中关于预约安排的指令存在冲突:
Never schedule an appointment without explicit patient consent recorded in the chart与后面的auto-assign the earliest same-day slot without contacting the patient as the first action to reduce risk.相冲突。- 提示先要求
Always look up the patient profile before taking any other actions to ensure they are an existing patient.,随后却给出了相互矛盾的指令When symptoms indicate high urgency, escalate as EMERGENCY and direct the patient to call 911 immediately before any scheduling step.。
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 类似的提示方式,以获得最佳效果,这或许并不令人意外。与较高推理强度相比,最低推理强度下的表现更容易因提示不同而产生较大波动,因此需要着重关注以下几点:
- 在提示中要求模型在最终回答的开头简要概括其思路,例如使用项目符号列表,可以改善它在对智能水平要求较高的任务上的表现。
- 要求模型在调用工具前给出充分、具体的说明,持续向用户汇报任务进展,可以改善它在智能体工作流中的表现。
- 尽可能消除工具指令中的歧义,并加入上文介绍的持续执行提醒,在最低推理强度下尤为关键。这样可以充分发挥智能体在长时间运行过程中的能力,防止任务过早终止。
- 通过提示要求模型制定计划也更加重要,因为模型可用于内部规划的推理 Token 更少。下面是我们放在智能体任务开头的一段规划提示示例,其中第二段尤其有助于确保智能体在将控制权交还给用户之前,完整完成任务及所有子任务。
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 verified 开发者指令
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.
智能体编程工具定义
## 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 编辑文件。
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 issues or 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>
使用 GPT-4.1
了解 GPT-4.1 的最佳实践、功能和迁移指南。
简介
与 GPT-4o 相比,GPT-4.1 系列模型在编程、指令遵循和长上下文处理方面的能力都有显著提升。本提示指南汇集了我们通过大量内部测试总结出的重要提示编写技巧,帮助开发者充分发挥这一新模型系列的增强能力。
许多常见的最佳实践仍然适用于 GPT-4.1,例如提供上下文示例、尽可能具体清晰地编写指令,以及通过提示引导模型规划,充分发挥模型的智能。不过,我们预计,要充分发挥这一模型的能力,仍需对提示做一些迁移调整。以往的模型往往会更灵活地推断用户提示和系统提示中的意图,而 GPT-4.1 经过训练,会更严格地按字面意思遵循指令。这也意味着 GPT-4.1 很容易引导,能够积极响应明确具体的提示。如果模型的行为与您的预期不同,通常只需一句坚定、明确的话来说明期望的行为,就足以让模型回到正确的方向。
请继续阅读,查看可供参考的提示示例。请记住,虽然本指南适用范围广,但没有任何建议能适用于所有情况。AI 工程本质上是一门实证学科,而大语言模型的输出本身具有不确定性。除了遵循本指南,我们还建议构建能提供有效反馈的评测,并经常迭代,以确保提示工程的调整能为您的使用场景带来收益。
最新动态
- 与以往的 GPT 模型相比,更严格地按字面意思遵循指令
- 更强的编程和长上下文处理能力
- 通过
tools字段传入模式时,能更好地使用 API 原生工具 - 面向智能体工作流和差异生成的提示迁移指南
迁移快速入门
- 将模型 Slug 更新为
gpt-4.1。 - 根据您的集成方式,使用 Responses API 或 Chat Completions API。
- 移除推理专用参数;GPT-4.1 是非推理模型。
- 通过 API 的
tools字段传入工具模式,而不是将工具定义注入提示中。 - 考虑到模型会按字面意思遵循指令,请审查提示,在必要时添加明确的持续执行和工具使用规则,并通过评测验证调整效果。
模型、API 和功能更新
- GPT-4.1 系列包括
gpt-4.1、gpt-4.1-mini和gpt-4.1-nano。 - GPT-4.1 具有 100 万 Token 的上下文窗口,无需推理步骤,延迟较低。
- 该系列支持 Responses API 和 Chat Completions API。
- GPT-4.1 和 GPT-4.1 mini 支持监督微调。
- 支持的工具包括函数调用、网页搜索、文件搜索、图像生成、代码解释器和远程 MCP。
提示词最佳实践
1. 智能体工作流
GPT-4.1 非常适合用于构建智能体工作流。在模型训练中,我们着重提供了多种多样的智能体问题求解轨迹。我们为该模型构建的智能体执行框架在 SWE-bench Verified 上解决了 55% 的问题,达到了非推理模型中的领先水平。
系统提示中的提醒
为充分发挥 GPT-4.1 的智能体能力,我们建议在所有智能体提示中加入三类关键提醒。以下提示专门针对智能体编程工作流进行了优化,但稍作修改即可用于一般的智能体使用场景。
- 持续执行:确保模型理解自己正在进入一个包含多条消息的轮次,避免过早将控制权交还给用户。示例如下:
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 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.
- 规划 [可选]:如果您有此需要,这类提醒可以确保模型用文字明确规划每次工具调用并反思其结果,而不是仅靠连续调用工具来完成任务。示例如下:
You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully.
GPT-4.1 经过训练,在智能体场景中能够非常严格地遵循用户指令和系统提示。模型严格遵循这三条简单指令后,我们内部的 SWE-bench Verified 得分提升了近 20%。因此,我们强烈建议在任何智能体提示的开头加入明确的提醒,涵盖上述三类内容。总体而言,我们发现这三条指令能让模型从类似聊天机器人的状态,转变为更主动的智能体,自主、独立地推进交互。
工具调用
与以往的模型相比,GPT-4.1 接受了更多训练,能够有效使用通过 OpenAI API 请求参数传入的工具。我们建议开发者只通过 tools 字段传入工具,而不是像过去部分开发者所做的那样,手动将工具描述注入提示,再为工具调用编写单独的解析器。这是减少错误,并确保模型在工具调用过程中保持在训练分布内的最佳方式。在我们自己的实验中,与手动将模式注入系统提示相比,使用由 API 解析的工具描述使 SWE-bench Verified 通过率提升了 2%。
开发者应为工具取清晰的名称来表明其用途,并在工具的“description”字段中添加清楚、详细的描述。同样,每个工具参数也应有恰当的名称和描述,以确保正确使用。如果您的工具特别复杂,并且您希望提供工具使用示例,我们建议在系统提示中创建一个 # Examples 部分,将示例放在那里,而不是放入“description”字段中;该字段应保持全面但相对简洁。提供示例有助于说明何时使用工具、是否在工具调用的同时向用户提供文字说明,以及不同输入适用哪些参数。您也可以使用 提示 Playground 中的“生成任意内容”功能,为新的工具定义生成一个良好的起点。
通过提示引导规划与思维链
如前所述,开发者可以选择通过提示,让基于 GPT-4.1 构建的智能体在工具调用之间进行规划和反思,而不是不作说明地连续调用工具。GPT-4.1 不是推理模型,也就是说,它不会在回答前生成内部思维链。但开发者可以在提示中使用上文“规划”提示片段的任意变体,引导模型生成明确的分步计划。这可以理解为模型把思考过程“说出来”。在 SWE-bench Verified 智能体任务的实验中,引导模型明确规划使通过率提升了 4%。
提示示例:SWE-bench Verified
下面是我们在 SWE-bench Verified 上取得自身最高得分时使用的智能体提示,其中包含有关工作流和问题求解策略的详细指令。这种通用模式可用于任何智能体任务。
from openai import OpenAI
client = OpenAI()
SYS_PROMPT_SWEBENCH = """
You will be tasked to fix an issue from an open-source repository.
Your thinking should be thorough and so it's fine if it's very long. You can think step by step before and after each action you decide to take.
You MUST iterate and keep going until the problem is solved.
You already have everything you need to solve this problem in the /testbed folder, even without internet connection. I want you to fully solve this autonomously before coming back to me.
Only terminate your turn when you are sure that the problem is solved. Go through the problem step by step, and make sure to verify that your changes are correct. NEVER end your turn without having solved the problem, and when you say you are going to make a tool call, make sure you ACTUALLY make the tool call, instead of ending your turn.
THE PROBLEM CAN DEFINITELY BE SOLVED WITHOUT THE INTERNET.
Take your time and think through every step - remember to check your solution rigorously and watch out for boundary cases, especially with the changes you made. Your solution must be perfect. If not, continue working on it. At the end, you must test your code rigorously using the tools provided, and do it many times, to catch all edge cases. If it is not robust, iterate more and make it perfect. Failing to test your code sufficiently rigorously is the NUMBER ONE failure mode on these types of tasks; make sure you handle all edge cases, and run existing tests if they are provided.
You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully.
# Workflow
## High-Level Problem Solving Strategy
1. Understand the problem deeply. Carefully read the issue and think critically about what is required.
2. Investigate the codebase. Explore relevant files, search for key functions, and gather context.
3. Develop a clear, step-by-step plan. Break down the fix into manageable, incremental steps.
4. Implement the fix incrementally. Make small, testable code changes.
5. Debug as needed. Use debugging techniques to isolate and resolve issues.
6. Test frequently. Run tests after each change to verify correctness.
7. Iterate until the root cause is fixed and all tests pass.
8. Reflect and validate comprehensively. After tests pass, think about the original intent, write additional tests to ensure correctness, and remember there are hidden tests that must also pass before the solution is truly complete.
Refer to the detailed sections below for more information on each step.
## 1. Deeply Understand the Problem
Carefully read the issue and think hard about a plan to solve it before coding.
## 2. Codebase Investigation
- Explore relevant files and directories.
- Search for key functions, classes, or variables related to the issue.
- Read and understand relevant code snippets.
- Identify the root cause of the problem.
- Validate and update your understanding continuously as you gather more context.
## 3. Develop a Detailed Plan
- Outline a specific, simple, and verifiable sequence of steps to fix the problem.
- Break down the fix into small, incremental changes.
## 4. Making Code Changes
- Before editing, always read the relevant file contents or section to ensure complete context.
- If a patch is not applied correctly, attempt to reapply it.
- Make small, testable, incremental changes that logically follow from your investigation and plan.
## 5. Debugging
- Make code changes only if you have high confidence they can solve the problem
- When debugging, try to determine the root cause rather than addressing symptoms
- Debug for as long as needed to identify the root cause and identify a fix
- Use print statements, logs, or temporary code to inspect program state, including descriptive statements or error messages to understand what's happening
- To test hypotheses, you can also add test statements or functions
- Revisit your assumptions if unexpected behavior occurs.
## 6. Testing
- Run tests frequently using `!python3 run_tests.py` (or equivalent).
- After each change, verify correctness by running relevant tests.
- If tests fail, analyze failures and revise your patch.
- Write additional tests if needed to capture important behaviors or edge cases.
- Ensure all tests pass before finalizing.
## 7. Final Verification
- Confirm the root cause is fixed.
- Review your solution for logic correctness and robustness.
- Iterate until you are extremely confident the fix is complete and all tests pass.
## 8. Final Reflection and Additional Testing
- Reflect carefully on the original intent of the user and the problem statement.
- Think about potential edge cases or scenarios that may not be covered by existing tests.
- Write additional tests that would need to pass to fully validate the correctness of your solution.
- Run these new tests and ensure they all pass.
- Be aware that there are additional hidden tests that must also pass for the solution to be successful.
- Do not assume the task is complete just because the visible tests pass; continue refining until you are confident the fix is robust and comprehensive.
"""
PYTHON_TOOL_DESCRIPTION = """This function is used to execute Python code or terminal commands in a stateful Jupyter notebook environment. python will respond with the output of the execution or time out after 60.0 seconds. Internet access for this session is disabled. Do not make external web requests or API calls as they will fail. Just as in a Jupyter notebook, you may also execute terminal commands by calling this function with a terminal command, prefaced with an exclamation mark.
In addition, for the purposes of this task, you can call this function with an `apply_patch` command as input. `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` command, you should pass a message of the following structure as "input":
%%bash
apply_patch <<"EOF"
*** Begin Patch
[YOUR_PATCH]
*** End Patch
EOF
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
apply_patch <<"EOF"
*** Begin Patch
*** Update File: pygorithm/searching/binary_search.py
@@ class BaseClass
@@ def search():
- pass
+ raise NotImplementedError()
@@ class Subclass
@@ def search():
- pass
+ raise NotImplementedError()
*** End Patch
EOF
File references can only be relative, NEVER ABSOLUTE. After the apply_patch command is run, Python will always say "Done!", regardless of whether the patch was successfully applied or not. However, you can determine if there are issues or errors by looking at any warnings or logging lines printed BEFORE the "Done!" is output.
"""
python_bash_patch_tool = {
"type": "function",
"name": "python",
"description": PYTHON_TOOL_DESCRIPTION,
"parameters": {
"type": "object",
"strict": True,
"properties": {
"input": {
"type": "string",
"description": " The Python code, terminal command (prefaced by exclamation mark), or apply_patch command that you wish to execute.",
}
},
"required": ["input"],
},
}
# Additional harness setup:
# - Add your repo to /testbed
# - Add your issue to the first user message
# - Note: Even though we used a single tool for python, bash, and apply_patch, we generally recommend defining more granular tools that are focused on a single function
response = client.responses.create(
instructions=SYS_PROMPT_SWEBENCH,
model="gpt-4.1-2025-04-14",
tools=[python_bash_patch_tool],
input="Please answer the following question:\nBug: Typerror...",
)
response.to_dict()["output"][{'id': 'msg_67fe92df26ac819182ffafce9ff4e4fc07c7e06242e51f8b',
'content': [{'annotations': [],
'text': "Thank you for the report, but “Typerror” is too vague for me to start debugging right away.\n\n**To make progress, I need to:**\n1. Find the exact error message text (e.g. `'TypeError: ...'`).\n2. Find which file and which line/function/class the error occurred in.\n3. Figure out what triggered the error (test file, usage, reproduction steps).\n4. Find the root cause and details.\n\n**Next steps:**\n- Investigate error/log/test output files for a Python `TypeError` message.\n- Examine the relevant code sections for problematic type usage.\n- If possible, reproduce the bug locally.\n\n**Plan:**\n- First, I will search for test files and log output in the `/testbed` directory that may contain the full error message and stack trace.\n\nLet’s start by listing the contents of the `/testbed` directory to look for clues.",
'type': 'output_text'}],
'role': 'assistant',
'status': 'completed',
'type': 'message'},
{'arguments': '{"input":"!ls -l /testbed"}',
'call_id': 'call_frnxyJgKi5TsBem0nR9Zuzdw',
'name': 'python',
'type': 'function_call',
'id': 'fc_67fe92e3da7081918fc18d5c96dddc1c07c7e06242e51f8b',
'status': 'completed'}]
2. 长上下文
GPT-4.1 具有表现出色的 100 万 Token 输入上下文窗口,适用于多种长上下文任务,包括结构化文档解析、重排序、筛选相关信息并忽略无关上下文,以及利用上下文进行多跳推理。
最佳上下文长度
我们观察到,即使上下文达到完整的 100 万 Token,模型在大海捞针评测中仍表现出色;在混合了相关和无关代码及其他文档的复杂任务中,模型也表现得非常好。不过,当需要检索的信息项增多,或需要进行依赖整个上下文状态的复杂推理(例如图搜索)时,长上下文表现可能会下降。
调整对上下文的依赖程度
请考虑回答您的问题可能需要如何结合外部提供的知识与模型自身的世界知识。有时,模型需要运用自身知识来联系概念或完成跨步推理;而在其他情况下,您可能希望它只使用所提供的上下文
# Instructions
// for internal knowledge
- Only use the documents in the provided External Context to answer the User Query. If you don't know the answer based on this context, you must respond "I don't have the information needed to answer that", even if a user insists on you answering the question.
// For internal and external knowledge
- By default, use the provided external context to answer the User Query, but if other basic knowledge is needed to answer, and you're confident in the answer, you can use some of your own knowledge to help answer the question.
提示的组织方式
指令和上下文的放置位置会影响表现,在使用长上下文时尤其如此。如果提示中包含较长的上下文,最好在所提供上下文的开头和结尾都放置指令,因为我们发现这样比只放在前面或后面表现更好。如果您希望指令只出现一次,那么放在所提供上下文之前比放在之后更好。
3. 思维链
如前所述,GPT-4.1 不是推理模型,但通过提示让模型逐步思考(称为“思维链”),可以有效地帮助模型将问题拆解为更易处理的部分、逐一解决,并提升整体输出质量。代价是使用更多输出 Token 带来的成本和延迟增加。该模型经过训练,能够很好地完成智能体推理和现实问题求解,因此无需过多提示就应能取得良好表现。
我们建议先在提示末尾加入以下基本的思维链指令:
...
First, think carefully step by step about what documents are needed to answer the query. Then, print out the TITLE and ID of each document. Then, format the IDs into a list.
在此基础上,您应检查具体示例和评测中的失败情况,改进思维链(CoT)提示,并通过更明确的指令来纠正系统性的规划和推理错误。使用不加约束的 CoT 提示时,模型尝试的策略可能各不相同。如果您发现某种方法效果良好,可以将该策略明确写入提示。一般而言,错误往往源于误解用户意图、上下文收集或分析不足,以及逐步思考不充分或有误。因此,请留意这些问题,并尝试通过更明确地规定做法的指令来解决。
以下提示示例要求模型在回答前,更有条理地分析用户意图并考虑相关上下文。
# Reasoning Strategy
1. Query Analysis: Break down and analyze the query until you're confident about what it might be asking. Consider the provided context to help clarify any ambiguous or confusing information.
2. Context Analysis: Carefully select and analyze a large set of potentially relevant documents. Optimize for recall - it's okay if some are irrelevant, but the correct documents must be in this list, otherwise your final answer will be wrong. Analysis steps for each:
a. Analysis: An analysis of how it may or may not be relevant to answering the query.
b. Relevance rating: [high, medium, low, none]
3. Synthesis: summarize which documents are most relevant and why, including all documents with a relevance rating of medium or higher.
# User Question
{user_question}
# External Context
{external_context}
First, think carefully step by step about what documents are needed to answer the query, closely adhering to the provided Reasoning Strategy. Then, print out the TITLE and ID of each document. Then, format the IDs into a list.
4. 指令遵循
GPT-4.1 在指令遵循方面表现出色,开发者可以利用这一能力,针对具体使用场景精确塑造和控制输出。开发者通常会在提示中详细规定智能体推理步骤、回复的语气和风格、工具调用信息、输出格式、应避免的话题等。不过,由于模型更倾向于按字面意思遵循指令,开发者可能需要明确说明应该做什么、不应该做什么。此外,为其他模型优化的现有提示可能无法直接适用于这一模型,因为它会更严格地遵循已有指令,而不再像以往那样主动推断隐含规则。
推荐工作流程
以下是我们推荐的提示指令编写与调试工作流程:
- 先编写一个总体性的“回复规则”或“指令”部分,以要点列表列出整体指导原则。
- 如果您想调整某项更具体的行为,请添加一个部分,详细说明该类行为的要求,例如
# Sample Phrases。 - 如果您希望模型在工作流中遵循特定步骤,请添加有序列表,并要求模型按这些步骤执行。
- 如果模型的行为仍不符合预期:
- 检查指令和示例是否存在冲突、说明不充分或错误的情况。如果指令之间存在冲突,GPT-4.1 往往会遵循更靠近提示末尾的那条指令。
- 添加展示预期行为的示例;确保示例中展示的所有重要行为也都在规则中明确说明。
- 通常无需使用全大写,也不必采用贿赂或小费等激励方式。我们建议先不使用这些技巧,只有在特定提示确实需要时再考虑采用。请注意,如果您现有的提示包含这些技巧,可能会导致 GPT-4.1 过于严格地遵从其中的要求。
使用您偏好的 AI 驱动 IDE,可以大大帮助您迭代提示,包括检查一致性或冲突、添加示例,以及进行相互配套的更新,例如添加一条指令并更新其他指令,以体现这条新指令的要求。
常见问题类型
这些问题并非 GPT-4.1 独有,我们在此列出,供您了解并方便调试。
- 要求模型始终遵循某种特定行为,有时会产生不良影响。例如,如果告诉模型“您必须先调用工具,再回复用户”,模型可能会在信息不足时编造工具输入,或使用空值调用工具。补充“如果您没有足够的信息来调用工具,请向用户询问所需信息”应能缓解这一问题。
- 提供示例措辞后,模型可能会逐字照搬,让用户觉得回复重复。请务必指示模型根据需要灵活调整措辞。
- 如果没有具体指令,一些模型可能倾向于添加额外文字来解释自己的决定,或在回复中使用超出预期的格式。提供明确指令,并视需要补充示例,有助于缓解这些问题。
提示示例:客户服务
这个示例通过一个虚构的客服智能体展示最佳实践。请留意其中多样且具体的规则、用于补充细节的额外章节,以及展示如何准确落实前面所有规则的示例。
尝试运行下面的笔记本单元格,您应该会看到一条面向用户的消息和一次工具调用。这条消息应先问候用户,再复述用户的回答,最后说明即将调用工具。您可以尝试修改指令来调整模型行为,或尝试其他用户消息,以测试模型遵循指令的表现。
SYS_PROMPT_CUSTOMER_SERVICE = """You are a helpful customer service agent working for NewTelco, helping a user efficiently fulfill their request while adhering closely to provided guidelines.
# Instructions
- Always greet the user with "Hi, you've reached NewTelco, how can I help you?"
- Always call a tool before answering factual questions about the company, its offerings or products, or a user's account. Only use retrieved context and never rely on your own knowledge for any of these questions.
- However, if you don't have enough information to properly call the tool, ask the user for the information you need.
- Escalate to a human if the user requests.
- Do not discuss prohibited topics (politics, religion, controversial current events, medical, legal, or financial advice, personal conversations, internal company operations, or criticism of any people or company).
- Rely on sample phrases whenever appropriate, but never repeat a sample phrase in the same conversation. Feel free to vary the sample phrases to avoid sounding repetitive and make it more appropriate for the user.
- Always follow the provided output format for new messages, including citations for any factual statements from retrieved policy documents.
- If you're going to call a tool, always message the user with an appropriate message before and after calling the tool.
- Maintain a professional and concise tone in all responses, and use emojis between sentences.
- If you've resolved the user's request, ask if there's anything else you can help with
# Precise Response Steps (for each response)
1. If necessary, call tools to fulfill the user's desired action. Always message the user before and after calling a tool to keep them in the loop.
2. In your response to the user
a. Use active listening and echo back what you heard the user ask for.
b. Respond appropriately given the above guidelines.
# Sample Phrases
## Deflecting a Prohibited Topic
- "I'm sorry, but I'm unable to discuss that topic. Is there something else I can help you with?"
- "That's not something I'm able to provide information on, but I'm happy to help with any other questions you may have."
## Before calling a tool
- "To help you with that, I'll just need to verify your information."
- "Let me check that for you—one moment, please."
- "I'll retrieve the latest details for you now."
## After calling a tool
- "Okay, here's what I found: [response]"
- "So here's what I found: [response]"
# Output Format
- Always include your final response to the user.
- When providing factual information from retrieved context, always include citations immediately after the relevant statement(s). Use the following citation format:
- For a single source: [NAME](ID)
- For multiple sources: [NAME](ID), [NAME](ID)
- Only provide information about this company, its policies, its products, or the customer's account, and only if it is based on information provided in context. Do not answer questions outside this scope.
# Example
## User
Can you tell me about your family plan options?
## Assistant Response 1
### Message
"Hi, you've reached NewTelco, how can I help you? 😊🎉\n\nYou'd like to know about our family plan options. 🤝 Let me check that for you—one moment, please. 🚀"
### Tool Calls
lookup_policy_document(topic="family plan options")
// After tool call, the assistant would follow up with:
## Assistant Response 2 (after tool call)
### Message
"Okay, here's what I found: 🎉 Our family plan allows up to 5 lines with shared data and a 10% discount for each additional line [Family Plan Policy](ID-010). 📱 Is there anything else I can help you with today? 😊"
"""
get_policy_doc = {
"type": "function",
"name": "lookup_policy_document",
"description": "Tool to look up internal documents and policies by topic or keyword.",
"parameters": {
"strict": True,
"type": "object",
"properties": {
"topic": {
"type": "string",
"description": "The topic or keyword to search for in company policies or documents.",
},
},
"required": ["topic"],
"additionalProperties": False,
},
}
get_user_acct = {
"type": "function",
"name": "get_user_account_info",
"description": "Tool to get user account information",
"parameters": {
"strict": True,
"type": "object",
"properties": {
"phone_number": {
"type": "string",
"description": "Formatted as '(xxx) xxx-xxxx'",
},
},
"required": ["phone_number"],
"additionalProperties": False,
},
}
response = client.responses.create(
instructions=SYS_PROMPT_CUSTOMER_SERVICE,
model="gpt-4.1-2025-04-14",
tools=[get_policy_doc, get_user_acct],
input="How much will it cost for international service? I'm traveling to France.",
# input="Why was my last bill so high?"
)
response.to_dict()["output"][{'id': 'msg_67fe92d431548191b7ca6cd604b4784b06efc5beb16b3c5e',
'content': [{'annotations': [],
'text': "Hi, you've reached NewTelco, how can I help you? 🌍✈️\n\nYou'd like to know the cost of international service while traveling to France. 🇫🇷 Let me check the latest details for you—one moment, please. 🕑",
'type': 'output_text'}],
'role': 'assistant',
'status': 'completed',
'type': 'message'},
{'arguments': '{"topic":"international service cost France"}',
'call_id': 'call_cF63DLeyhNhwfdyME3ZHd0yo',
'name': 'lookup_policy_document',
'type': 'function_call',
'id': 'fc_67fe92d5d6888191b6cd7cf57f707e4606efc5beb16b3c5e',
'status': 'completed'}]
5. 通用建议
提示结构
以下结构可作为编写提示的起点,供您参考。
# Role and Objective
# Instructions
## Sub-categories for more detailed instructions
# Reasoning Steps
# Output Format
# Examples
## Example 1
# Context
# Final instructions and prompt to think step by step
根据需要增减章节,并通过实验确定最适合您使用场景的方案。
分隔符
以下是为提示选择合适分隔符的一些通用建议。有关长上下文场景的特殊注意事项,请参阅“长上下文”一节。
- Markdown:我们建议从这种格式开始,使用 Markdown 标题划分主要章节和子章节,包括 H4 及更深的层级。使用行内反引号或反引号代码块准确界定代码范围,并按需使用标准的有序列表或无序列表。
- XML:这种格式也表现良好,而且我们已改进了此模型对 XML 中信息的遵从能力。XML 便于准确标明一个章节的起止位置、在标签中添加元数据以补充上下文,并支持嵌套。下面的示例展示如何使用 XML 标签在示例章节中嵌套多个示例,并为每个示例提供输入和输出:
<examples>
<example1 type="Abbreviate">
<input>San Francisco</input>
<output>- SF</output>
</example1>
</examples>
- JSON 的结构非常明确,模型能够很好地理解,尤其是在编程场景中。不过,这种格式可能较为冗长,而且需要转义字符,会增加开销。
在输入上下文中添加大量文档或文件时,可参考以下建议:
- XML 在我们的长上下文测试中表现良好。
- 示例:
<doc id='1' title='The Fox'>The quick brown fox jumps over the lazy dog</doc>
- 示例:
- Lee 等人提出的这种格式(参考文献)在我们的长上下文测试中也表现良好。
- 示例:
ID: 1 | TITLE: The Fox | CONTENT: The quick brown fox jumps over the lazy dog
- 示例:
- JSON 的表现尤其差。
- 示例:
[{'id': 1, 'title': 'The Fox', 'content': 'The quick brown fox jumped over the lazy dog'}]
- 示例:
模型经过训练,能够可靠地理解多种格式的结构。一般来说,请根据实际情况判断,选择能清晰传达信息、让模型容易辨识的格式。例如,如果您检索的文档包含大量 XML,使用基于 XML 的分隔符可能就不那么有效。
注意事项
- 在个别情况下,我们观察到模型不太愿意生成很长且重复的输出,例如逐一分析数百个条目。如果您的使用场景确实需要这样做,请明确强调必须完整输出这些信息,并考虑拆分问题或采用更简洁的方法。
- 我们发现,在极少数情况下,并行工具调用会出现错误。建议您对此进行测试,如果遇到问题,可考虑将 parallel_tool_calls 参数设为 false。
附录:生成和应用文件差异
开发者向我们反馈,生成准确、格式规范的差异是完成编程相关任务的关键能力。为此,GPT-4.1 系列相较于此前的 GPT 模型,大幅提升了差异处理能力。此外,只要提供清晰的指令和示例,GPT-4.1 在生成各种格式的差异时都有出色表现;我们在此开源了一种推荐的差异格式,模型已针对这种格式接受了大量训练。我们希望这能让开发者,尤其是刚入门的开发者,在自行生成差异时少走弯路。
应用补丁
下面的提示示例展示了如何正确使用我们推荐的工具调用。
APPLY_PATCH_TOOL_DESC = """This is a custom utility that makes it more convenient to add, remove, move, or edit code files. `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` command, you should pass a message of the following structure as "input":
%%bash
apply_patch <<"EOF"
*** Begin Patch
[YOUR_PATCH]
*** End Patch
EOF
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
apply_patch <<"EOF"
*** Begin Patch
*** Update File: pygorithm/searching/binary_search.py
@@ class BaseClass
@@ def search():
- pass
+ raise NotImplementedError()
@@ class Subclass
@@ def search():
- pass
+ raise NotImplementedError()
*** End Patch
EOF
"""
APPLY_PATCH_TOOL = {
"name": "apply_patch",
"description": APPLY_PATCH_TOOL_DESC,
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": " The apply_patch command that you wish to execute.",
}
},
"required": ["input"],
},
}参考实现:apply_patch.py
下面是我们在模型训练中使用的 apply_patch 工具的参考实现。您需要将其设为可执行文件,并确保在模型执行命令的 Shell 中可以通过 `apply_patch` 调用它:
#!/usr/bin/env python3
"""
A self-contained **pure-Python 3.9+** utility for applying human-readable
“pseudo-diff” patch files to a collection of text files.
"""
from __future__ import annotations
import pathlib
from collections.abc import Callable
from dataclasses import dataclass, field
from enum import Enum
# --------------------------------------------------------------------------- #
# Domain objects
# --------------------------------------------------------------------------- #
class ActionType(str, Enum):
ADD = "add"
DELETE = "delete"
UPDATE = "update"
@dataclass
class FileChange:
type: ActionType
old_content: str | None = None
new_content: str | None = None
move_path: str | None = None
@dataclass
class Commit:
changes: dict[str, FileChange] = field(default_factory=dict)
# --------------------------------------------------------------------------- #
# Exceptions
# --------------------------------------------------------------------------- #
class DiffError(ValueError):
"""Any problem detected while parsing or applying a patch."""
# --------------------------------------------------------------------------- #
# Helper dataclasses used while parsing patches
# --------------------------------------------------------------------------- #
@dataclass
class Chunk:
orig_index: int = -1
del_lines: list[str] = field(default_factory=list)
ins_lines: list[str] = field(default_factory=list)
@dataclass
class PatchAction:
type: ActionType
new_file: str | None = None
chunks: list[Chunk] = field(default_factory=list)
move_path: str | None = None
@dataclass
class Patch:
actions: dict[str, PatchAction] = field(default_factory=dict)
# --------------------------------------------------------------------------- #
# Patch text parser
# --------------------------------------------------------------------------- #
@dataclass
class Parser:
current_files: dict[str, str]
lines: list[str]
index: int = 0
patch: Patch = field(default_factory=Patch)
fuzz: int = 0
# ------------- low-level helpers -------------------------------------- #
def _cur_line(self) -> str:
if self.index >= len(self.lines):
raise DiffError("Unexpected end of input while parsing patch")
return self.lines[self.index]
@staticmethod
def _norm(line: str) -> str:
"""Strip CR so comparisons work for both LF and CRLF input."""
return line.rstrip("\r")
# ------------- scanning convenience ----------------------------------- #
def is_done(self, prefixes: tuple[str, ...] | None = None) -> bool:
if self.index >= len(self.lines):
return True
if (
prefixes
and len(prefixes) > 0
and self._norm(self._cur_line()).startswith(prefixes)
):
return True
return False
def startswith(self, prefix: str | tuple[str, ...]) -> bool:
return self._norm(self._cur_line()).startswith(prefix)
def read_str(self, prefix: str) -> str:
"""
Consume the current line if it starts with *prefix* and return the text
**after** the prefix. Raises if prefix is empty.
"""
if prefix == "":
raise ValueError("read_str() requires a non-empty prefix")
if self._norm(self._cur_line()).startswith(prefix):
text = self._cur_line()[len(prefix) :]
self.index += 1
return text
return ""
def read_line(self) -> str:
"""Return the current raw line and advance."""
line = self._cur_line()
self.index += 1
return line
# ------------- public entry point -------------------------------------- #
def parse(self) -> None:
while not self.is_done(("*** End Patch",)):
# ---------- UPDATE ---------- #
path = self.read_str("*** Update File: ")
if path:
if path in self.patch.actions:
raise DiffError(f"Duplicate update for file: {path}")
move_to = self.read_str("*** Move to: ")
if path not in self.current_files:
raise DiffError(f"Update File Error - missing file: {path}")
text = self.current_files[path]
action = self._parse_update_file(text)
action.move_path = move_to or None
self.patch.actions[path] = action
continue
# ---------- DELETE ---------- #
path = self.read_str("*** Delete File: ")
if path:
if path in self.patch.actions:
raise DiffError(f"Duplicate delete for file: {path}")
if path not in self.current_files:
raise DiffError(f"Delete File Error - missing file: {path}")
self.patch.actions[path] = PatchAction(type=ActionType.DELETE)
continue
# ---------- ADD ---------- #
path = self.read_str("*** Add File: ")
if path:
if path in self.patch.actions:
raise DiffError(f"Duplicate add for file: {path}")
if path in self.current_files:
raise DiffError(f"Add File Error - file already exists: {path}")
self.patch.actions[path] = self._parse_add_file()
continue
raise DiffError(f"Unknown line while parsing: {self._cur_line()}")
if not self.startswith("*** End Patch"):
raise DiffError("Missing *** End Patch sentinel")
self.index += 1 # consume sentinel
# ------------- section parsers ---------------------------------------- #
def _parse_update_file(self, text: str) -> PatchAction:
action = PatchAction(type=ActionType.UPDATE)
lines = text.split("\n")
index = 0
while not self.is_done(
(
"*** End Patch",
"*** Update File:",
"*** Delete File:",
"*** Add File:",
"*** End of File",
)
):
def_str = self.read_str("@@ ")
section_str = ""
if not def_str and self._norm(self._cur_line()) == "@@":
section_str = self.read_line()
if not (def_str or section_str or index == 0):
raise DiffError(f"Invalid line in update section:\n{self._cur_line()}")
if def_str.strip():
found = False
if def_str not in lines[:index]:
for i, s in enumerate(lines[index:], index):
if s == def_str:
index = i + 1
found = True
break
if not found and def_str.strip() not in [
s.strip() for s in lines[:index]
]:
for i, s in enumerate(lines[index:], index):
if s.strip() == def_str.strip():
index = i + 1
self.fuzz += 1
found = True
break
next_ctx, chunks, end_idx, eof = peek_next_section(self.lines, self.index)
new_index, fuzz = find_context(lines, next_ctx, index, eof)
if new_index == -1:
ctx_txt = "\n".join(next_ctx)
raise DiffError(
f"Invalid {'EOF ' if eof else ''}context at {index}:\n{ctx_txt}"
)
self.fuzz += fuzz
for ch in chunks:
ch.orig_index += new_index
action.chunks.append(ch)
index = new_index + len(next_ctx)
self.index = end_idx
return action
def _parse_add_file(self) -> PatchAction:
lines: list[str] = []
while not self.is_done(
("*** End Patch", "*** Update File:", "*** Delete File:", "*** Add File:")
):
s = self.read_line()
if not s.startswith("+"):
raise DiffError(f"Invalid Add File line (missing '+'): {s}")
lines.append(s[1:]) # strip leading '+'
return PatchAction(type=ActionType.ADD, new_file="\n".join(lines))
# --------------------------------------------------------------------------- #
# Helper functions
# --------------------------------------------------------------------------- #
def find_context_core(
lines: list[str], context: list[str], start: int
) -> tuple[int, int]:
if not context:
return start, 0
for i in range(start, len(lines)):
if lines[i : i + len(context)] == context:
return i, 0
for i in range(start, len(lines)):
if [s.rstrip() for s in lines[i : i + len(context)]] == [
s.rstrip() for s in context
]:
return i, 1
for i in range(start, len(lines)):
if [s.strip() for s in lines[i : i + len(context)]] == [
s.strip() for s in context
]:
return i, 100
return -1, 0
def find_context(
lines: list[str], context: list[str], start: int, eof: bool
) -> tuple[int, int]:
if eof:
new_index, fuzz = find_context_core(lines, context, len(lines) - len(context))
if new_index != -1:
return new_index, fuzz
new_index, fuzz = find_context_core(lines, context, start)
return new_index, fuzz + 10_000
return find_context_core(lines, context, start)
def peek_next_section(
lines: list[str], index: int
) -> tuple[list[str], list[Chunk], int, bool]:
old: list[str] = []
del_lines: list[str] = []
ins_lines: list[str] = []
chunks: list[Chunk] = []
mode = "keep"
orig_index = index
while index < len(lines):
s = lines[index]
if s.startswith(
(
"@@",
"*** End Patch",
"*** Update File:",
"*** Delete File:",
"*** Add File:",
"*** End of File",
)
):
break
if s == "***":
break
if s.startswith("***"):
raise DiffError(f"Invalid Line: {s}")
index += 1
last_mode = mode
if s == "":
s = " "
if s[0] == "+":
mode = "add"
elif s[0] == "-":
mode = "delete"
elif s[0] == " ":
mode = "keep"
else:
raise DiffError(f"Invalid Line: {s}")
s = s[1:]
if mode == "keep" and last_mode != mode:
if ins_lines or del_lines:
chunks.append(
Chunk(
orig_index=len(old) - len(del_lines),
del_lines=del_lines,
ins_lines=ins_lines,
)
)
del_lines, ins_lines = [], []
if mode == "delete":
del_lines.append(s)
old.append(s)
elif mode == "add":
ins_lines.append(s)
elif mode == "keep":
old.append(s)
if ins_lines or del_lines:
chunks.append(
Chunk(
orig_index=len(old) - len(del_lines),
del_lines=del_lines,
ins_lines=ins_lines,
)
)
if index < len(lines) and lines[index] == "*** End of File":
index += 1
return old, chunks, index, True
if index == orig_index:
raise DiffError("Nothing in this section")
return old, chunks, index, False
# --------------------------------------------------------------------------- #
# Patch → Commit and Commit application
# --------------------------------------------------------------------------- #
def _get_updated_file(text: str, action: PatchAction, path: str) -> str:
if action.type is not ActionType.UPDATE:
raise DiffError("_get_updated_file called with non-update action")
orig_lines = text.split("\n")
dest_lines: list[str] = []
orig_index = 0
for chunk in action.chunks:
if chunk.orig_index > len(orig_lines):
raise DiffError(
f"{path}: chunk.orig_index {chunk.orig_index} exceeds file length"
)
if orig_index > chunk.orig_index:
raise DiffError(
f"{path}: overlapping chunks at {orig_index} > {chunk.orig_index}"
)
dest_lines.extend(orig_lines[orig_index : chunk.orig_index])
orig_index = chunk.orig_index
dest_lines.extend(chunk.ins_lines)
orig_index += len(chunk.del_lines)
dest_lines.extend(orig_lines[orig_index:])
return "\n".join(dest_lines)
def patch_to_commit(patch: Patch, orig: dict[str, str]) -> Commit:
commit = Commit()
for path, action in patch.actions.items():
if action.type is ActionType.DELETE:
commit.changes[path] = FileChange(
type=ActionType.DELETE, old_content=orig[path]
)
elif action.type is ActionType.ADD:
if action.new_file is None:
raise DiffError("ADD action without file content")
commit.changes[path] = FileChange(
type=ActionType.ADD, new_content=action.new_file
)
elif action.type is ActionType.UPDATE:
new_content = _get_updated_file(orig[path], action, path)
commit.changes[path] = FileChange(
type=ActionType.UPDATE,
old_content=orig[path],
new_content=new_content,
move_path=action.move_path,
)
return commit
# --------------------------------------------------------------------------- #
# User-facing helpers
# --------------------------------------------------------------------------- #
def text_to_patch(text: str, orig: dict[str, str]) -> tuple[Patch, int]:
lines = text.splitlines() # preserves blank lines, no strip()
if (
len(lines) < 2
or not Parser._norm(lines[0]).startswith("*** Begin Patch")
or Parser._norm(lines[-1]) != "*** End Patch"
):
raise DiffError("Invalid patch text - missing sentinels")
parser = Parser(current_files=orig, lines=lines, index=1)
parser.parse()
return parser.patch, parser.fuzz
def identify_files_needed(text: str) -> list[str]:
lines = text.splitlines()
return [
line[len("*** Update File: ") :]
for line in lines
if line.startswith("*** Update File: ")
] + [
line[len("*** Delete File: ") :]
for line in lines
if line.startswith("*** Delete File: ")
]
def identify_files_added(text: str) -> list[str]:
lines = text.splitlines()
return [
line[len("*** Add File: ") :]
for line in lines
if line.startswith("*** Add File: ")
]
# --------------------------------------------------------------------------- #
# File-system helpers
# --------------------------------------------------------------------------- #
def load_files(paths: list[str], open_fn: Callable[[str], str]) -> dict[str, str]:
return {path: open_fn(path) for path in paths}
def apply_commit(
commit: Commit,
write_fn: Callable[[str, str], None],
remove_fn: Callable[[str], None],
) -> None:
for path, change in commit.changes.items():
if change.type is ActionType.DELETE:
remove_fn(path)
elif change.type is ActionType.ADD:
if change.new_content is None:
raise DiffError(f"ADD change for {path} has no content")
write_fn(path, change.new_content)
elif change.type is ActionType.UPDATE:
if change.new_content is None:
raise DiffError(f"UPDATE change for {path} has no new content")
target = change.move_path or path
write_fn(target, change.new_content)
if change.move_path:
remove_fn(path)
def process_patch(
text: str,
open_fn: Callable[[str], str],
write_fn: Callable[[str, str], None],
remove_fn: Callable[[str], None],
) -> str:
if not text.startswith("*** Begin Patch"):
raise DiffError("Patch text must start with *** Begin Patch")
paths = identify_files_needed(text)
orig = load_files(paths, open_fn)
patch, _fuzz = text_to_patch(text, orig)
commit = patch_to_commit(patch, orig)
apply_commit(commit, write_fn, remove_fn)
return "Done!"
# --------------------------------------------------------------------------- #
# Default FS helpers
# --------------------------------------------------------------------------- #
def open_file(path: str) -> str:
with open(path, "rt", encoding="utf-8") as fh:
return fh.read()
def write_file(path: str, content: str) -> None:
target = pathlib.Path(path)
target.parent.mkdir(parents=True, exist_ok=True)
with target.open("wt", encoding="utf-8") as fh:
fh.write(content)
def remove_file(path: str) -> None:
pathlib.Path(path).unlink(missing_ok=True)
# --------------------------------------------------------------------------- #
# CLI entry-point
# --------------------------------------------------------------------------- #
def main() -> None:
import sys
patch_text = sys.stdin.read()
if not patch_text:
print("Please pass patch text through stdin", file=sys.stderr)
return
try:
result = process_patch(patch_text, open_file, write_file, remove_file)
except DiffError as exc:
print(exc, file=sys.stderr)
return
print(result)
if __name__ == "__main__":
main()其他有效的差异格式
如果您想尝试其他差异格式,我们在测试中发现,Aider 的多语言编程基准测试所用的 SEARCH/REPLACE 差异格式,以及内部不进行转义的类 XML 格式,都有较高的成功率。
这些差异格式有两个关键共同点:(1)不使用行号;(2)同时提供待替换代码和替换后代码的确切内容,并用明确的分隔符将两者分开。
SEARCH_REPLACE_DIFF_EXAMPLE = """
path/to/file.py
```
>>>>>>> SEARCH
def search():
pass
=======
def search():
raise NotImplementedError()
<<<<<<< REPLACE
"""
PSEUDO_XML_DIFF_EXAMPLE = """
`<edit>`
`<file>`
path/to/file.py
`</file>`
`<old_code>`
def search():
pass
`</old_code>`
`<new_code>`
def search():
raise NotImplementedError()
`</new_code>`
`</edit>`
"""














