如需查看完整的文档索引,请参阅 llms.txt。在文档页面的 URL 末尾加上 .md 即可查看该页面的 Markdown 版本。

使用 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 的智能体能力,我们建议在所有智能体提示词中加入以下三类关键提醒。下面的提示词专门针对智能体编程工作流进行了优化,稍作调整即可用于其他智能体场景。

  1. 持续执行:让模型明白当前轮次会包含多条消息,避免过早将控制权交还给用户。示例如下:
您是一个智能体。请持续处理用户的请求,直到用户的问题得到彻底解决。只有在确认问题已经解决后,才能结束本轮并将控制权交还给用户。
  1. 工具调用:鼓励模型充分利用工具,降低它编造或猜测答案的可能性。示例如下:
如果不确定与用户请求有关的文件内容或代码库结构,请使用工具读取文件并收集相关信息。切勿猜测或编造答案。
  1. 规划 [可选]:如果您希望模型在每次工具调用前后用文字明确说明计划并回顾结果,可以加入这类提醒,避免模型仅靠连续调用工具来完成任务。示例如下:
每次调用函数前,都必须详细制定计划,并仔细回顾此前各次函数调用的结果。切勿仅靠调用函数完成整个过程,这样可能会妨碍您深入思考和解决问题。

GPT-4.1 经过训练,能够在智能体场景中严格遵循用户指令和系统提示词。模型严格执行上述三条简单指令后,我们的内部 SWE-bench Verified 得分提高了近 20%。因此,我们强烈建议在编写智能体提示词时,开头就针对这三方面给出明确提醒。我们发现,这三条指令配合使用,能让原本像聊天机器人一样应答的模型成为更主动的智能体,自主推动交互继续进行。

工具调用

与以往的模型相比,GPT-4.1 接受了更多专门训练,能更有效地使用通过 OpenAI API 请求参数传入的工具。有些开发者过去会把工具描述手动插入提示词,再单独编写解析器来处理工具调用。我们建议开发者只使用 tools 字段传入工具。这样最有助于减少错误,也能使整个工具调用过程符合模型训练时的数据分布。在我们的实验中,相比将工具模式手动插入系统提示词,使用由 API 解析的工具描述使 SWE-bench Verified 的通过率提高了 2%。

请为工具取一个能清楚体现其用途的名称,并在工具的“description”字段中清楚、详细地说明其用途。同样,每个工具参数也应有清晰的名称和说明,帮助模型正确使用。如果工具特别复杂,您希望提供用法示例,建议在系统提示词中创建 # Examples 部分来放置示例。“description”字段应写得全面而相对简洁。示例可以说明何时使用工具、调用工具时是否应同时向用户发送文字,以及针对不同输入应使用哪些参数。您还可以在提示词 Playground中使用“Generate Anything”,生成新工具定义的初稿。

通过提示词引导规划和思维链

您可以通过提示词,让基于 GPT-4.1 构建的智能体在工具调用之间说明计划、回顾结果,避免模型一言不发地连续调用工具。GPT-4.1 是非推理模型,回答前不会生成内部思维链。您可以在提示词中使用上文“规划”提醒的任一变体,引导模型明确写出分步计划。这可以理解为让模型“把思考过程说出来”。在 SWE-bench Verified 智能体任务实验中,引导模型明确写出计划使通过率提高了 4%。

SWE-bench Verified 提示词示例

下面是我们在 SWE-bench Verified 上取得最高分时使用的智能体提示词,其中详细说明了工作流程和解题策略。这种通用结构适用于任何智能体任务。

发送智能体编程提示词
const response = await client.responses.create({
  instructions:
    "\nYou will be tasked to fix an issue from an open-source repository.\n\nYour 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.\n\nYou MUST iterate and keep going until the problem is solved.\n\nYou 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.\n\nOnly 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.\n\nTHE PROBLEM CAN DEFINITELY BE SOLVED WITHOUT THE INTERNET.\n\nTake 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.\n\nYou 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.\n\n# Workflow\n\n## High-Level Problem Solving Strategy\n\n1. Understand the problem deeply. Carefully read the issue and think critically about what is required.\n2. Investigate the codebase. Explore relevant files, search for key functions, and gather context.\n3. Develop a clear, step-by-step plan. Break down the fix into manageable, incremental steps.\n4. Implement the fix incrementally. Make small, testable code changes.\n5. Debug as needed. Use debugging techniques to isolate and resolve issues.\n6. Test frequently. Run tests after each change to verify correctness.\n7. Iterate until the root cause is fixed and all tests pass.\n8. 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.\n\nRefer to the detailed sections below for more information on each step.\n\n## 1. Deeply Understand the Problem\nCarefully read the issue and think hard about a plan to solve it before coding.\n\n## 2. Codebase Investigation\n- Explore relevant files and directories.\n- Search for key functions, classes, or variables related to the issue.\n- Read and understand relevant code snippets.\n- Identify the root cause of the problem.\n- Validate and update your understanding continuously as you gather more context.\n\n## 3. Develop a Detailed Plan\n- Outline a specific, simple, and verifiable sequence of steps to fix the problem.\n- Break down the fix into small, incremental changes.\n\n## 4. Making Code Changes\n- Before editing, always read the relevant file contents or section to ensure complete context.\n- If a patch is not applied correctly, attempt to reapply it.\n- Make small, testable, incremental changes that logically follow from your investigation and plan.\n\n## 5. Debugging\n- Make code changes only if you have high confidence they can solve the problem\n- When debugging, try to determine the root cause rather than addressing symptoms\n- Debug for as long as needed to identify the root cause and identify a fix\n- Use print statements, logs, or temporary code to inspect program state, including descriptive statements or error messages to understand what's happening\n- To test hypotheses, you can also add test statements or functions\n- Revisit your assumptions if unexpected behavior occurs.\n\n## 6. Testing\n- Run tests frequently using `!python3 run_tests.py` (or equivalent).\n- After each change, verify correctness by running relevant tests.\n- If tests fail, analyze failures and revise your patch.\n- Write additional tests if needed to capture important behaviors or edge cases.\n- Ensure all tests pass before finalizing.\n\n## 7. Final Verification\n- Confirm the root cause is fixed.\n- Review your solution for logic correctness and robustness.\n- Iterate until you are extremely confident the fix is complete and all tests pass.\n\n## 8. Final Reflection and Additional Testing\n- Reflect carefully on the original intent of the user and the problem statement.\n- Think about potential edge cases or scenarios that may not be covered by existing tests.\n- Write additional tests that would need to pass to fully validate the correctness of your solution.\n- Run these new tests and ensure they all pass.\n- Be aware that there are additional hidden tests that must also pass for the solution to be successful.\n- 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.\n",
  model: "gpt-4.1-2025-04-14",
  tools: [
    {
      type: "function",
      name: "python",
      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.\n\nIn 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":\n\n%%bash\napply_patch <<"EOF"\n*** Begin Patch\n[YOUR_PATCH]\n*** End Patch\nEOF\n\nWhere [YOUR_PATCH] is the actual content of your patch, specified in the following V4A diff format.\n\n*** [ACTION] File: [path/to/file] -> ACTION can be one of Add, Update, or Delete.\nFor each snippet of code that needs to be changed, repeat the following:\n[context_before] -> See below for further instructions on context.\n- [old_code] -> Precede the old code with a minus sign.\n+ [new_code] -> Precede the new, replacement code with a plus sign.\n[context_after] -> See below for further instructions on context.\n\nFor instructions on [context_before] and [context_after]:\n- 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.\n- 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:\n@@ class BaseClass\n[3 lines of pre-context]\n- [old_code]\n+ [new_code]\n[3 lines of post-context]\n\n- 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:\n\n@@ class BaseClass\n@@ \tdef method():\n[3 lines of pre-context]\n- [old_code]\n+ [new_code]\n[3 lines of post-context]\n\nNote, 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.\n\n%%bash\napply_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\n@@ class Subclass\n@@     def search():\n-        pass\n+        raise NotImplementedError()\n\n*** End Patch\nEOF\n\nFile 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.\n',
      parameters: {
        type: "object",
        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"],
        additionalProperties: false,
      },
      strict: true,
    },
  ],
  input: "Please answer the following question:\nBug: Typerror...",
});
if (response.status !== "completed") {
  throw new Error(`Response ended with status ${response.status}`);
}
console.log(JSON.stringify(response.output, null, 2));
[{'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 的上限,模型依然表现出色。对于混合了相关和无关代码及其他文档的复杂任务,我们也观察到了很好的效果。不过,当需要检索的条目增多,或任务涉及必须掌握整个上下文状态才能完成的复杂推理(例如图搜索)时,模型处理长上下文的表现可能会下降。

调整模型对上下文的依赖程度

请考虑回答问题需要哪些外部知识,又需要哪些模型自身已有的知识。有时,模型需要运用自身知识来关联概念或推导出未明说的结论。有时,您则希望模型只使用提供的上下文。

# 指令
// 仅依据所提供的文档作答
- 回答用户问题时,只能使用所提供的“外部上下文”中的文档。如果根据这些文档无法确定答案,即使用户坚持要求作答,也必须回复“我没有回答这个问题所需的信息”。
// 结合模型已有知识与外部知识作答
- 默认使用所提供的外部上下文回答用户问题。如果回答还需要其他基础知识,并且对答案有把握,可以运用自身已有的知识辅助作答。

提示词的组织方式

指令和上下文的位置会影响效果,在使用长上下文时尤其如此。如果提示词中包含很长的上下文,最好在上下文的前后各写一次指令。我们发现,这样比只在前面或后面写一次效果更好。如果您希望指令只出现一次,放在上下文之前比放在之后效果更好。

3. 思维链

GPT-4.1 是非推理模型。通过提示词引导模型逐步思考(即使用“思维链”),可以帮助模型将问题拆解成更容易处理的部分,逐一解决,从而提高整体输出质量。代价是输出 Token 增多,成本和延迟也随之增加。模型在训练中已针对智能体推理和解决实际问题进行了优化,因此通常无需复杂的提示词就能取得良好效果。

建议先在提示词末尾加入以下基本的思维链指令:

...

首先,逐步分析,仔细判断回答这个问题需要哪些文档。然后,输出每份所需文档的 TITLE 和 ID。最后,将这些 ID 整理成列表。

接下来,您可以检查具体示例和评估中的失败案例,用更明确的指令纠正反复出现的规划和推理错误,从而改进思维链(CoT)提示词。如果思维链提示词没有限定策略,模型可能会尝试不同方法。发现某种方法效果好时,您可以将其写入提示词。常见的错误原因包括误解用户意图、收集或分析上下文不充分,以及逐步思考不够充分或存在错误。请留意这些情况,并尝试用更有针对性的指令加以解决。

以下提示词示例要求模型先系统地分析用户意图并考虑相关上下文,再作答。

# 推理策略
1. 分析问题:拆解并分析用户的问题,直到有把握判断用户想问什么。结合所提供的上下文,厘清含糊或难以理解的信息。
2. 分析上下文:仔细筛选并分析大量可能相关的文档。优先保证召回率:可以纳入一些无关文档,但必须将回答问题所需的文档全部列入,否则最终答案就会出错。对每份文档执行以下步骤:
	a. 分析:说明这份文档是否可能有助于回答问题,并给出理由。
	b. 评定相关性:[high, medium, low, none]
3. 综合归纳:总结哪些文档最相关,并说明原因。相关性评级为 medium 或更高的文档都必须纳入总结。

# 用户问题
{user_question}

# 外部上下文
{external_context}

首先,严格遵循上述推理策略,逐步分析,仔细判断回答这个问题需要哪些文档。然后,输出每份所需文档的 TITLE 和 ID。最后,将这些 ID 整理成列表。

4. 遵循指令

GPT-4.1 在遵循指令方面表现出色,开发者可以据此针对具体应用场景精确控制输出。开发者经常在提示词中详细规定智能体的推理步骤、回复的语气和风格、工具调用细节、输出格式以及应避开的话题等。由于模型更倾向于按字面含义执行指令,您可能需要明确说明它应该做什么、避免做什么。为其他模型优化的现有提示词也可能无法直接达到预期效果,因为 GPT-4.1 对明示的指令执行得更严格,也更少自行推断隐含规则。

推荐工作流程

我们建议按以下流程编写和调试提示词中的指令:

  1. 先写一个总的“回复规则”或“指令”部分,分条列出总体要求。
  2. 如果您希望改变某项具体行为,可以增加一个部分,详细说明这类行为的要求,例如 # Sample Phrases。
  3. 如果您希望模型按特定步骤执行工作流,请用有序列表列出步骤,并要求模型依次执行。
  4. 如果模型的行为仍不符合预期:
    1. 检查指令和示例是否相互冲突、表述不够具体或存在错误。如果指令冲突,GPT-4.1 通常会遵循更靠近提示词末尾的那条指令。
    2. 添加示例来展示期望的行为。凡是示例中体现的重要行为,也都应明确写入规则。
    3. 通常无需使用全大写字母来强调要求,也无需通过许诺好处或小费等方式激励模型。建议先尝试常规写法,仅在具体提示词确有需要时才使用这些技巧。如果现有提示词包含这些技巧,GPT-4.1 可能会过于重视相应要求。

使用您惯用的 AI 辅助 IDE 可以方便您反复调整提示词,例如检查指令是否一致、有无冲突,补充示例,或在添加一条新指令时同步更新相关指令,使它们体现新的要求。

常见问题

以下问题也会出现在其他模型中。在此列出是为了方便您识别和排查。

  • 要求模型始终执行某项行为偶尔会产生意外后果。例如,如果指令写的是“回复用户前必须调用工具”,当信息不足时,模型可能会编造工具输入或使用空值调用工具。补充“如果没有足够的信息来调用工具,请向用户询问所需信息”通常能缓解这一问题。
  • 提供示例用语后,模型可能会逐字照搬,导致用户觉得回复千篇一律。请明确要求模型根据需要变换措辞。
  • 如果没有具体指令,有些模型会主动添加文字来解释自己的决定,或在回复中使用过多的格式。您可以明确说明要求,必要时提供示例来缓解这些问题。

客户服务提示词示例

以下示例以虚构的客服智能体展示最佳实践。请留意规则覆盖了哪些行为、要求写得有多具体,以及提示词如何通过单独的部分补充细节,再通过一个示例展示遵循前面所有规则时的具体表现。

请尝试运行下面的笔记本单元格。您应该能看到一条面向用户的消息和一次工具调用。消息应先问候用户,再复述用户的回答,然后说明即将调用工具。您可以修改指令来调整模型行为,也可以尝试输入其他用户消息,以测试模型遵循指令的效果。

运行客服提示词
const response = await client.responses.create({
  instructions:
    'You are a helpful customer service agent working for NewTelco, helping a user efficiently fulfill their request while adhering closely to provided guidelines.\n\n# Instructions\n- Always greet the user with "Hi, you\'ve reached NewTelco, how can I help you?"\n- 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.\n    - However, if you don\'t have enough information to properly call the tool, ask the user for the information you need.\n- Escalate to a human if the user requests.\n- 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).\n- 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.\n- Always follow the provided output format for new messages, including citations for any factual statements from retrieved policy documents.\n- If you\'re going to call a tool, always message the user with an appropriate message before and after calling the tool.\n- Maintain a professional and concise tone in all responses, and use emojis between sentences.\n- If you\'ve resolved the user\'s request, ask if there\'s anything else you can help with\n\n# Precise Response Steps (for each response)\n1. 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.\n2. In your response to the user\n    a. Use active listening and echo back what you heard the user ask for.\n    b. Respond appropriately given the above guidelines.\n\n# Sample Phrases\n## Deflecting a Prohibited Topic\n- "I\'m sorry, but I\'m unable to discuss that topic. Is there something else I can help you with?"\n- "That\'s not something I\'m able to provide information on, but I\'m happy to help with any other questions you may have."\n\n## Before calling a tool\n- "To help you with that, I\'ll just need to verify your information."\n- "Let me check that for you—one moment, please."\n- "I\'ll retrieve the latest details for you now."\n\n## After calling a tool\n- "Okay, here\'s what I found: [response]"\n- "So here\'s what I found: [response]"\n\n# Output Format\n- Always include your final response to the user.\n- When providing factual information from retrieved context, always include citations immediately after the relevant statement(s). Use the following citation format:\n    - For a single source: [NAME](ID)\n    - For multiple sources: [NAME](ID), [NAME](ID)\n- 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.\n\n# Example\n## User\nCan you tell me about your family plan options?\n\n## Assistant Response 1\n### Message\n"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. 🚀"\n\n### Tool Calls\nlookup_policy_document(topic="family plan options")\n\n// After tool call, the assistant would follow up with:\n\n## Assistant Response 2 (after tool call)\n### Message\n"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? 😊"\n',
  model: "gpt-4.1-2025-04-14",
  tools: [
    {
      type: "function",
      name: "lookup_policy_document",
      description:
        "Tool to look up internal documents and policies by topic or keyword.",
      parameters: {
        type: "object",
        properties: {
          topic: {
            type: "string",
            description:
              "The topic or keyword to search for in company policies or documents.",
          },
        },
        required: ["topic"],
        additionalProperties: false,
      },
      strict: true,
    },
    {
      type: "function",
      name: "get_user_account_info",
      description: "Tool to get user account information",
      parameters: {
        type: "object",
        properties: {
          phone_number: {
            type: "string",
            description: "Formatted as '(xxx) xxx-xxxx'",
          },
        },
        required: ["phone_number"],
        additionalProperties: false,
      },
      strict: true,
    },
  ],
  input:
    "How much will it cost for international service? I'm traveling to France.",
});
if (response.status !== "completed") {
  throw new Error(`Response ended with status ${response.status}`);
}
console.log(JSON.stringify(response.output, null, 2));
[{'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. 通用建议

提示词结构

编写提示词时,您可以从以下结构入手。

# 角色与目标

# 指令

## 按类别列出详细指令

# 推理步骤

# 输出格式

# 示例
## 示例 1

# 上下文

# 最终指令及逐步思考的要求

请根据需要增删各部分,并通过实验找出最适合您应用场景的结构。

分隔符

以下是为提示词选择分隔符的一些通用建议。如果使用长上下文,请同时参阅“长上下文”部分了解该场景的注意事项。

  1. Markdown:建议从这种格式入手,用 Markdown 标题划分主要部分和子部分(需要时可使用四级或更深层级的标题)。使用行内反引号或反引号代码块准确标出代码的边界,并根据需要使用标准有序列表或无序列表。
  2. XML:这种格式同样有效,而且我们已改进该模型依据 XML 中的信息执行指令的能力。XML 便于精确标明一个部分的起止位置,还可以在标签中添加元数据以补充上下文,并支持嵌套。以下示例使用 XML 标签在示例部分内嵌套具体示例,并标出每个示例的输入和输出:
<examples>
<example1 type="Abbreviate">
<input>San Francisco</input>
<output>- SF</output>
</example1>
</examples>
  1. 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 模型相比,GPT-4.1 系列在处理文件差异方面有了显著提升。只要有清晰的指令和示例,GPT-4.1 就能很好地生成各种格式的差异。此外,我们在这里开源了一种推荐的差异格式,模型已针对这种格式接受了大量训练。我们希望这能减少开发者自行生成差异时的摸索,尤其是对于刚开始使用这项能力的开发者。

应用补丁

下面的提示词示例展示了如何正确使用我们推荐的工具调用方式。

定义补丁工具
const applyPatchToolDescription = `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
`;

const tool = {
  name: "apply_patch",
  description: applyPatchToolDescription,
  parameters: {
    type: "object",
    properties: {
      input: {
        type: "string",
        description: "The apply_patch command to execute.",
      },
    },
    required: ["input"],
  },
};

参考实现:apply_patch.py

Python 选项卡提供了模型训练时使用的 apply_patch.py 参考实现。TypeScript、Go 和 Ruby 选项卡提供的是独立编写的移植版本,模型训练时未使用这三个版本。请确保在模型执行命令的 shell 中可以通过 apply_patch 调用您选择的实现。

将完整的 TypeScript 移植版保存为 apply_patch.ts,运行 chmod +x apply_patch.ts 为该文件添加执行权限,然后在 PATH 所列的某个目录中创建名为 apply_patch 的符号链接,使其指向该文件。脚本首行的解释器指令会启动 Node 并启用 TypeScript 支持。在要修改的代码仓库中运行 apply_patch < changes.patch,通过标准输入传入补丁。该脚本要求系统的 env 命令支持 -S 选项,Linux 和 macOS 上的 env 均支持该选项。

补丁解析器的参考实现及移植版本
// TypeScript port of this guide's Python pseudo-diff reference implementation.
// Run in a trusted working directory with no concurrent filesystem changes.
import {
  lstatSync,
  mkdirSync,
  readFileSync,
  unlinkSync,
  writeFileSync,
} from "node:fs";
import path from "node:path";

type Chunk = { index: number; deleted: string[]; inserted: string[] };
type Change = { source: string; target: string; kind: string; content: string };

function contextIndex(
  lines: string[],
  context: string[],
  start: number
): number {
  if (!context.length) return start;
  for (const normalize of [
    (s: string) => s,
    (s: string) => s.trimEnd(),
    (s: string) => s.trim(),
  ]) {
    for (let i = Math.max(0, start); i + context.length <= lines.length; i++) {
      if (
        context.every((line, j) => normalize(lines[i + j]) === normalize(line))
      )
        return i;
    }
  }
  return -1;
}

class PatchParser {
  lines: string[];
  position = 1;
  constructor(lines: string[]) {
    this.lines = lines;
  }
  current(): string {
    return this.lines[this.position] ?? "";
  }
  boundary(): boolean {
    return (
      this.position >= this.lines.length ||
      [
        "*** End Patch",
        "*** Update File:",
        "*** Delete File:",
        "*** Add File:",
      ].some((prefix) => this.current().startsWith(prefix))
    );
  }
  prefix(prefix: string): string | undefined {
    if (!this.current().startsWith(prefix)) return undefined;
    return this.lines[this.position++].slice(prefix.length);
  }
  update(text: string): string {
    const lines = text.split("\n");
    let index = 0;
    const chunks: Chunk[] = [];
    while (!this.boundary()) {
      const anchor = this.prefix("@@ ");
      let bare = false;
      if (anchor === undefined && this.current() === "@@") {
        this.position++;
        bare = true;
      }
      if (anchor === undefined && !bare && index !== 0)
        throw new Error("Invalid update section");
      if (anchor?.trim() && !lines.slice(0, index).includes(anchor)) {
        let found = lines.indexOf(anchor, index);
        if (
          found < 0 &&
          !lines.slice(0, index).some((line) => line.trim() === anchor.trim())
        ) {
          found = lines.findIndex(
            (line, i) => i >= index && line.trim() === anchor.trim()
          );
        }
        if (found >= 0) index = found + 1;
      }
      const context: string[] = [];
      let deleted: string[] = [],
        inserted: string[] = [];
      const section: Chunk[] = [];
      const start = this.position;
      const flush = () => {
        if (deleted.length + inserted.length) {
          section.push({
            index: context.length - deleted.length,
            deleted,
            inserted,
          });
          deleted = [];
          inserted = [];
        }
      };
      while (
        !this.boundary() &&
        !this.current().startsWith("@@") &&
        this.current() !== "*** End of File"
      ) {
        const line = this.lines[this.position++] || " ";
        if (line[0] === " ") {
          flush();
          context.push(line.slice(1));
        } else if (line[0] === "-") {
          deleted.push(line.slice(1));
          context.push(line.slice(1));
        } else if (line[0] === "+") inserted.push(line.slice(1));
        else throw new Error("Invalid context line");
      }
      flush();
      if (start === this.position) throw new Error("Empty update section");
      let location = -1;
      if (this.current() === "*** End of File") {
        this.position++;
        location = contextIndex(lines, context, lines.length - context.length);
      }
      if (location < 0) location = contextIndex(lines, context, index);
      if (location < index || location + context.length > lines.length)
        throw new Error("Update context not found");
      for (const chunk of section)
        chunks.push({ ...chunk, index: chunk.index + location });
      index = location + context.length;
    }
    const result: string[] = [];
    let cursor = 0;
    for (const chunk of chunks) {
      if (
        chunk.index < cursor ||
        chunk.index + chunk.deleted.length > lines.length
      )
        throw new Error("Overlapping update");
      result.push(...lines.slice(cursor, chunk.index), ...chunk.inserted);
      cursor = chunk.index + chunk.deleted.length;
    }
    return [...result, ...lines.slice(cursor)].join("\n");
  }
}

function patchPath(filename: string): string {
  if (
    !filename ||
    path.isAbsolute(filename) ||
    /^[A-Za-z]:/.test(filename) ||
    filename.includes("\\") ||
    filename.includes("\0") ||
    filename.split(/[\\/]/).includes("..")
  ) {
    throw new Error("Patch path must stay inside the working directory");
  }
  let prefix = "";
  for (const part of filename.split("/")) {
    prefix = path.join(prefix, part);
    const stat = lstatSync(prefix, { throwIfNoEntry: false });
    if (stat?.isSymbolicLink())
      throw new Error("Symlink paths are not supported");
  }
  return path.normalize(filename);
}

function processPatch(text: string): void {
  const lines = text.replaceAll("\r\n", "\n").replace(/\n$/, "").split("\n");
  if (
    lines.length < 2 ||
    lines[0] !== "*** Begin Patch" ||
    lines.at(-1) !== "*** End Patch"
  )
    throw new Error("Invalid patch sentinels");
  const parser = new PatchParser(lines);
  const changes: Change[] = [];
  const reserved = new Set<string>();
  while (
    parser.current() !== "*** End Patch" &&
    parser.position < lines.length
  ) {
    const header = /^\*\*\* (Update|Delete|Add) File: (.+)$/.exec(
      parser.current()
    );
    if (!header) throw new Error(`Unknown patch line: ${parser.current()}`);
    parser.position++;
    const [, kind, filename] = header;
    const source = patchPath(filename);
    if (reserved.has(source))
      throw new Error(`Duplicate file action: ${source}`);
    reserved.add(source);
    const change: Change = { source, target: source, kind, content: "" };
    if (kind === "Add") {
      const added: string[] = [];
      while (!parser.boundary()) {
        const line = parser.prefix("+");
        if (line === undefined)
          throw new Error("Add-file lines must start with +");
        added.push(line);
      }
      change.content = added.join("\n");
    } else {
      const original = readFileSync(source, "utf8");
      if (kind === "Update") {
        const target = parser.prefix("*** Move to: ");
        if (target !== undefined) {
          change.target = patchPath(target);
          if (change.target !== source) {
            if (reserved.has(change.target))
              throw new Error("Conflicting destination");
            reserved.add(change.target);
          }
        }
        change.content = parser.update(original);
      }
    }
    if (
      (kind === "Add" || change.target !== source) &&
      lstatSync(change.target, { throwIfNoEntry: false })
    ) {
      throw new Error(`Destination already exists: ${change.target}`);
    }
    changes.push(change);
  }
  if (parser.position !== lines.length - 1)
    throw new Error("Content after end sentinel");
  // Validate the complete patch before writing. Filesystem errors can still
  // leave a partially applied patch; this utility is not a transaction system.
  for (const change of changes) {
    patchPath(change.source);
    patchPath(change.target);
    if (change.kind === "Delete") {
      unlinkSync(change.source);
      continue;
    }
    mkdirSync(path.dirname(change.target), { recursive: true });
    writeFileSync(change.target, change.content, {
      flag:
        change.kind === "Add" || change.target !== change.source ? "wx" : "w",
    });
    if (change.target !== change.source) unlinkSync(change.source);
  }
}

processPatch(readFileSync(0, "utf8"));
console.log("Done!");

其他有效的差异格式

如果您希望尝试其他差异格式,我们在测试中发现,Aider 多语言编程基准测试使用的 SEARCH/REPLACE 差异格式,以及一种内部无需转义的类 XML 格式,成功率都很高。

这两种差异格式有两个共同点:(1)省略行号。(2)完整、准确地给出待替换的代码和用于替换的新代码,并用清晰的分隔符区分二者。

比较其他差异格式
const SEARCH_REPLACE_DIFF_EXAMPLE =
  "\n    path/to/file.py\n    ```\n    >>>>>>> SEARCH\n    def search():\n        pass\n    =======\n    def search():\n       raise NotImplementedError()\n    <<<<<<< REPLACE\n    ";
const PSEUDO_XML_DIFF_EXAMPLE =
  "\n    `<edit>`\n    `<file>`\n    path/to/file.py\n    `</file>`\n    `<old_code>`\n    def search():\n        pass\n    `</old_code>`\n    `<new_code>`\n    def search():\n       raise NotImplementedError()\n    `</new_code>`\n    `</edit>`\n    ";
OpenAI API 文档镜像