NOTE / 2026.04.21
Prompt engineering | OpenAI API(对照翻译)
OpenAI 提示词工程指南对照翻译,涵盖模型选择、消息角色、提示词复用、上下文窗口与 GPT-5/推理模型写法。
说明:本文件按“原文 + 中文译文”逐段对照,便于精读学习。
1) Text generation basics(文本生成基础)
With the OpenAI API, you can use a large language model to generate text from a prompt, as you might using ChatGPT. Models can generate almost any kind of text response—like code, mathematical equations, structured JSON data, or human-like prose.
通过 OpenAI API,你可以像使用 ChatGPT 一样,用提示词让大语言模型生成文本。模型几乎可以生成任意类型的文本结果,例如代码、数学公式、结构化 JSON 数据,或者接近人类写作风格的自然语言。
Here’s a simple example using the Responses API.
下面是一个使用 Responses API 的简单示例。
import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-5.4",
input: "Write a one-sentence bedtime story about a unicorn."
});
console.log(response.output_text);
An array of content generated by the model is in the output property of the response. In this simple example, we have just one output which looks like this:
模型生成的内容位于响应对象的 output 属性中,它是一个数组。在这个简单示例里,只有一个输出项,类似如下:
[
{
"id": "msg_67b73f697ba4819183a15cc17d011509",
"type": "message",
"role": "assistant",
"content": [
{
"type": "output_text",
"text": "Under the soft glow of the moon, Luna the unicorn danced through fields of twinkling stardust, leaving trails of dreams for every child asleep.",
"annotations": []
}
]
}
]
The output array often has more than one item in it! It can contain tool calls, data about reasoning tokens generated by reasoning models, and other items. It is not safe to assume that the model’s text output is present at output[0].content[0].text.
output 数组通常不止一个元素。它可能包含工具调用、推理模型生成的 reasoning token 相关数据,以及其他条目。因此,不能安全地假设模型文本一定在 output[0].content[0].text。
Some of our official SDKs include an output_text property on model responses for convenience, which aggregates all text outputs from the model into a single string. This may be useful as a shortcut to access text output from the model.
部分官方 SDK 为了方便提供了 output_text 属性,会把模型的所有文本输出聚合成一个字符串。它可以作为访问文本输出的快捷方式。
In addition to plain text, you can also have the model return structured data in JSON format - this feature is called Structured Outputs.
除了纯文本,你还可以让模型返回 JSON 格式的结构化数据,这项功能称为 Structured Outputs(结构化输出)。
2) Choosing a model(模型选择)
Choosing a model
A key choice to make when generating content through the API is which model you want to use - the model parameter of the code samples above. You can find a full listing of available models here. Here are a few factors to consider when choosing a model for text generation.
模型选择
通过 API 生成内容时,一个关键决策是使用哪个模型,也就是上面代码里的 model 参数。你可以在官方列表中查看全部可用模型。下面是文本生成场景下选型时应考虑的几个因素。
Reasoning models generate an internal chain of thought to analyze the input prompt, and excel at understanding complex tasks and multi-step planning. They are also generally slower and more expensive to use than GPT models.
Reasoning 模型会生成内部思维链来分析输入提示词,擅长复杂任务理解和多步规划。但相较 GPT 模型,它们通常更慢、成本更高。
GPT models are fast, cost-efficient, and highly intelligent, but benefit from more explicit instructions around how to accomplish tasks.
GPT 模型速度快、成本效益高、智能水平也高,但通常更依赖“明确且具体”的任务指令。
Large and small (mini or nano) models offer trade-offs for speed, cost, and intelligence. Large models are more effective at understanding prompts and solving problems across domains, while small models are generally faster and cheaper to use.
大模型与小模型(mini 或 nano)在速度、成本、智能上存在权衡。大模型在理解提示词和跨领域解题上更强,小模型通常更快、更便宜。
When in doubt, gpt-4.1 offers a solid combination of intelligence, speed, and cost effectiveness.
如果不确定怎么选,gpt-4.1 在智能、速度与成本之间提供了较均衡的组合。
3) Prompt engineering(提示词工程)
Prompt engineering
Prompt engineering is the process of writing effective instructions for a model, such that it consistently generates content that meets your requirements.
提示词工程
提示词工程就是为模型编写有效指令的过程,从而让模型持续稳定地生成满足你要求的内容。
Because the content generated from a model is non-deterministic, prompting to get your desired output is a mix of art and science. However, you can apply techniques and best practices to get good results consistently.
由于模型输出具有非确定性,要通过提示词得到理想输出,本质上是“艺术 + 科学”的结合。不过你可以通过一套技术与最佳实践,持续获得较好的结果。
Some prompt engineering techniques work with every model, like using message roles. But different model types (like reasoning versus GPT models) might need to be prompted differently to produce the best results. Even different snapshots of models within the same family could produce different results. So as you build more complex applications, we strongly recommend:
有些提示词技巧适用于所有模型,例如使用 message role(消息角色)。但不同模型类型(如 reasoning 与 GPT)常常需要不同的提示方式才能达到最佳效果。即便是同一模型家族的不同快照版本,也可能产生不同结果。因此,在构建更复杂应用时,官方强烈建议:
Pinning your production applications to specific model snapshots (like gpt-4.1-2025-04-14 for example) to ensure consistent behavior
将生产环境固定到具体的模型快照版本(例如 gpt-4.1-2025-04-14),以确保行为一致。
Building evals that measure the behavior of your prompts so you can monitor prompt performance as you iterate, or when you change and upgrade model versions
构建可评测(eval)体系来衡量提示词行为,这样在你迭代提示词或升级模型版本时,能持续监控效果变化。
Now, let’s examine some tools and techniques available to you to construct prompts.
接下来,看看构建提示词时可用的一些工具和技巧。
4) Message roles and instruction following(消息角色与指令遵循)
Message roles and instruction following
You can provide instructions to the model with differing levels of authority using the instructions API parameter or message roles.
消息角色与指令遵循
你可以通过 instructions API 参数或 message role,以不同“优先级/权重”向模型提供指令。
The instructions parameter gives the model high-level instructions on how it should behave while generating a response, including tone, goals, and examples of correct responses. Any instructions provided this way will take priority over a prompt in the input parameter.
instructions 参数用于给模型提供高层行为指令(如语气、目标、正确回答示例)。通过 instructions 提供的指令,其优先级高于 input 参数里的提示内容。
import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-5",
reasoning: { effort: "low" },
instructions: "Talk like a pirate.",
input: "Are semicolons optional in JavaScript?",
});
console.log(response.output_text);
The example above is roughly equivalent to using the following input messages in the input array:
上面的示例大体等价于在 input 数组中写成下面这种消息形式:
import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-5",
reasoning: { effort: "low" },
input: [
{
role: "developer",
content: "Talk like a pirate."
},
{
role: "user",
content: "Are semicolons optional in JavaScript?",
},
],
});
console.log(response.output_text);
Note that the instructions parameter only applies to the current response generation request. If you are managing conversation state with the previous_response_id parameter, the instructions used on previous turns will not be present in the context.
注意:instructions 参数只作用于当前这一次生成请求。如果你通过 previous_response_id 管理多轮对话状态,之前轮次里的 instructions 不会自动出现在当前上下文中。
The OpenAI model spec describes how our models give different levels of priority to messages with different roles.
OpenAI model spec 描述了模型如何对不同角色消息分配不同优先级。
- developer
- user
- assistant
- developer
- user
- assistant
- Developer messages are instructions provided by the application developer, prioritized ahead of user messages.
- User messages are instructions provided by an end user, prioritized behind developer messages.
- Messages generated by the model have the assistant role.
developer消息:由应用开发者提供,优先级高于user消息。user消息:由最终用户提供,优先级低于developer消息。- 模型生成的消息角色是
assistant。
A multi-turn conversation may consist of several messages of these types, along with other content types provided by both you and the model. Learn more about managing conversation state here.
多轮会话通常由上述多种消息类型组成,也可能包含你和模型提供的其他内容类型。更多细节可参考会话状态管理文档。
You could think about developer and user messages like a function and its arguments in a programming language.
你可以把 developer 和 user 消息类比为编程语言里的“函数定义”和“函数参数”。
developer messages provide the system’s rules and business logic, like a function definition.
developer 消息提供系统规则与业务逻辑,类似函数定义。
user messages provide inputs and configuration to which the developer message instructions are applied, like arguments to a function.
user 消息提供输入和配置,供 developer 指令应用,类似函数参数。
5) Reusable prompts(可复用提示词)
Reusable prompts
In the OpenAI dashboard, you can develop reusable prompts that you can use in API requests, rather than specifying the content of prompts in code. This way, you can more easily build and evaluate your prompts, and deploy improved versions of your prompts without changing your integration code.
可复用提示词
在 OpenAI 控制台中,你可以创建可复用提示词,并在 API 请求中直接引用,而不是把提示词内容硬编码在代码里。这样你可以更容易地构建、评估提示词,并在不改集成代码的前提下发布优化版提示词。
Here’s how it works:
工作方式如下:
Create a reusable prompt in the dashboard with placeholders like {{customer_name}}.
在控制台创建可复用提示词,并使用 {{customer_name}} 这类占位符。
Use the prompt in your API request with the prompt parameter. The prompt parameter object has three properties you can configure:
在 API 请求中通过 prompt 参数引用该提示词。prompt 对象有三个可配置字段:
id: Prompt identifier in the dashboard.version: Prompt version (defaults to the dashboard “current” version).variables: Placeholder values; supports strings and Response input types likeinput_imageandinput_file. See API reference.
id:提示词唯一标识(控制台可查)。version:提示词版本(默认控制台“current”)。variables:占位值映射,支持字符串和input_image、input_file等 Response 输入类型。详见 API 参考。
import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-5",
prompt: {
id: "pmpt_abc123",
version: "2",
variables: {
customer_name: "Jane Doe",
product: "40oz juice box"
}
}
});
console.log(response.output_text);
6) Message formatting with Markdown and XML(用 Markdown 与 XML 做提示词结构化)
Message formatting with Markdown and XML
When writing developer and user messages, you can help the model understand logical boundaries of your prompt and context data using a combination of Markdown formatting and XML tags.
用 Markdown 与 XML 做消息格式化
在编写 developer / user 消息时,你可以结合 Markdown 与 XML 标签,帮助模型更清晰地理解提示词与上下文数据的逻辑边界。
Markdown headers and lists can be helpful to mark distinct sections of a prompt, and to communicate hierarchy to the model. They can also potentially make your prompts more readable during development. XML tags can help delineate where one piece of content (like a supporting document used for reference) begins and ends. XML attributes can also be used to define metadata about content in the prompt that can be referenced by your instructions.
Markdown 标题和列表有助于标记提示词的不同区块,并向模型传达层级关系,也能提升开发阶段的可读性。XML 标签可用于清楚地标出某段内容(如参考文档)的起止边界。XML 属性还可以定义元数据,供你的指令引用。
In general, a developer message will contain the following sections, usually in this order (though the exact optimal content and order may vary by which model you are using):
通常,一个 developer 消息会包含以下区块,并常按如下顺序组织(但最佳内容与顺序会随模型而变化):
Identity: Describe the purpose, communication style, and high-level goals of the assistant.
Identity(身份):描述助手的目的、沟通风格和高层目标。
Instructions: Provide guidance to the model on how to generate the response you want. What rules should it follow? What should the model do, and what should the model never do? This section could contain many subsections as relevant for your use case, like how the model should call custom functions.
Instructions(指令):指导模型如何生成你想要的回答。应遵循什么规则?必须做什么?绝不能做什么?该部分可按场景拆多个子节,例如“如何调用自定义函数”。
Examples: Provide examples of possible inputs, along with the desired output from the model.
Examples(示例):提供可能输入及其期望输出样例。
Context: Give the model any additional information it might need to generate a response, like private/proprietary data outside its training data, or any other data you know will be particularly relevant. This content is usually best positioned near the end of your prompt, as you may include different context for different generation requests.
Context(上下文):提供模型生成回答可能需要的额外信息,例如训练数据之外的私有/专有数据,或你已知特别相关的数据。此类内容通常适合放在提示词后部,因为不同请求可能会携带不同上下文。
Below is an example of using Markdown and XML tags to construct a developer message with distinct sections and supporting examples.
下面是一个结合 Markdown 与 XML 标签构建 developer 消息的示例,包含分区与配套样例。
# Identity
You are coding assistant that helps enforce the use of snake case
variables in JavaScript code, and writing code that will run in
Internet Explorer version 6.
# Instructions
* When defining variables, use snake case names (e.g. my_variable)
instead of camel case names (e.g. myVariable).
* To support old browsers, declare variables using the older
"var" keyword.
* Do not give responses with Markdown formatting, just return
the code as requested.
# Examples
<user_query>
How do I declare a string variable for a first name?
</user_query>
<assistant_response>
var first_name = "Anna";
</assistant_response>
7) Save on cost and latency with prompt caching(用提示词缓存降低成本与延迟)
Save on cost and latency with prompt caching
When constructing a message, you should try and keep content that you expect to use over and over in your API requests at the beginning of your prompt, and among the first API parameters you pass in the JSON request body to Chat Completions or Responses. This enables you to maximize cost and latency savings from prompt caching.
使用提示词缓存节省成本与延迟
构建消息时,应尽量把会反复复用的内容放在提示词前部,并优先放在 Chat Completions 或 Responses 请求体 JSON 的前几个参数中。这样可以最大化利用 prompt caching 带来的成本与时延收益。
8) Few-shot learning(少样本学习)
Few-shot learning
Few-shot learning lets you steer a large language model toward a new task by including a handful of input/output examples in the prompt, rather than fine-tuning the model. The model implicitly “picks up” the pattern from those examples and applies it to a prompt. When providing examples, try to show a diverse range of possible inputs with the desired outputs.
少样本学习
Few-shot learning 通过在提示词中加入少量输入/输出样例来引导模型完成新任务,而不需要微调。模型会隐式“学习”样例模式并迁移到新输入。提供样例时,应尽量覆盖多样输入与对应的目标输出。
Typically, you will provide examples as part of a developer message in your API request. Here’s an example developer message containing examples that show a model how to classify positive or negative customer service reviews.
通常你会把样例放在 API 请求的 developer 消息里。下面是一个示例:通过样例教模型将客服评论分类为正向、负向或中性。
# Identity
You are a helpful assistant that labels short product reviews as
Positive, Negative, or Neutral.
# Instructions
* Only output a single word in your response with no additional formatting
or commentary.
* Your response should only be one of the words "Positive", "Negative", or
"Neutral" depending on the sentiment of the product review you are given.
# Examples
<product_review id="example-1">
I absolutely love this headphones — sound quality is amazing!
</product_review>
<assistant_response id="example-1">
Positive
</assistant_response>
<product_review id="example-2">
Battery life is okay, but the ear pads feel cheap.
</product_review>
<assistant_response id="example-2">
Neutral
</assistant_response>
<product_review id="example-3">
Terrible customer service, I'll never buy from them again.
</product_review>
<assistant_response id="example-3">
Negative
</assistant_response>
9) Include relevant context information(加入相关上下文信息)
Include relevant context information
It is often useful to include additional context information the model can use to generate a response within the prompt you give the model. There are a few common reasons why you might do this:
加入相关上下文信息
在提示词中补充模型可利用的上下文,通常很有帮助。常见原因包括:
To give the model access to proprietary data, or any other data outside the data set the model was trained on.
让模型访问专有数据,或训练语料之外的其他数据。
To constrain the model’s response to a specific set of resources that you have determined will be most beneficial.
将模型回答约束在你认为最有价值的一组资源范围内。
The technique of adding additional relevant context to the model generation request is sometimes called retrieval-augmented generation (RAG). You can add additional context to the prompt in many different ways, from querying a vector database and including the text you get back into a prompt, or by using OpenAI’s built-in file search tool to generate content based on uploaded documents.
在生成请求中补充相关上下文的技术,常被称为 RAG(检索增强生成)。你可以用很多方式加上下文,例如查询向量数据库并把检索文本拼入提示词,或使用 OpenAI 内置的文件搜索工具基于上传文档生成内容。
10) Planning for the context window(上下文窗口规划)
Planning for the context window
Models can only handle so much data within the context they consider during a generation request. This memory limit is called a context window, which is defined in terms of tokens (chunks of data you pass in, from text to images).
上下文窗口规划
模型在单次生成请求中只能处理有限上下文数据。这个“记忆上限”称为上下文窗口(context window),以 token(你传入的数据块,从文本到图像)计量。
Models have different context window sizes from the low 100k range up to one million tokens for newer GPT-4.1 models. Refer to the model docs for specific context window sizes per model.
不同模型的上下文窗口大小不同,从十几万 token 到新版 GPT-4.1 的百万 token 不等。具体大小请查对应模型文档。
11) Prompting GPT-5 models(GPT-5 提示词)
Prompting GPT-5 models
GPT models like gpt-5 benefit from precise instructions that explicitly provide the logic and data required to complete the task in the prompt. GPT-5 in particular is highly steerable and responsive to well-specified prompts. To get the most out of GPT-5, refer to the prompting guide in the cookbook.
GPT-5 模型提示词
像 gpt-5 这样的 GPT 模型更受益于精确指令:在提示词中明确写出完成任务所需的逻辑与数据。特别是 GPT-5,可控性高、对规范提示响应好。若想最大化发挥 GPT-5,建议参考 Cookbook 里的 prompting guide。
GPT-5 prompting guide
GPT-5 提示词指南
Get the most out of prompting GPT-5 with the tips and tricks in this prompting guide, extracted from real-world use cases and practical experience.
该指南总结了来自真实场景与实践经验的技巧,帮助你把 GPT-5 提示词效果发挥到更高水平。
GPT-5 prompting best practices
While the cookbook has the best and most comprehensive guidance for prompting this model, here are a few best practices to keep in mind.
GPT-5 提示词最佳实践
Cookbook 提供了最完整的 GPT-5 提示词指南;此外这里还给出一些需要牢记的实践原则。
- Coding
- Front-end engineering
- Agentic tasks
- 编码任务
- 前端工程任务
- Agent 化任务
12) Prompting reasoning models(推理模型提示词)
Prompting reasoning models
There are some differences to consider when prompting a reasoning model versus prompting a GPT model. Generally speaking, reasoning models will provide better results on tasks with only high-level guidance. This differs from GPT models, which benefit from very precise instructions.
推理模型提示词
给 reasoning 模型写提示词,与给 GPT 模型写提示词有一些差异。总体上,reasoning 模型在“仅提供高层指导”的任务上往往效果更好;而 GPT 模型通常更依赖非常具体、明确的指令。
You could think about the difference between reasoning and GPT models like this.
可以用下面这个类比来理解 reasoning 与 GPT 模型的差别:
A reasoning model is like a senior co-worker. You can give them a goal to achieve and trust them to work out the details.
Reasoning 模型像资深同事:你给目标,它能自行推敲细节并落地。
A GPT model is like a junior coworker. They’ll perform best with explicit instructions to create a specific output.
GPT 模型像初级同事:在你提供明确指令、指定输出形式时表现最佳。
For more information on best practices when using reasoning models, refer to this guide.
更多 reasoning 模型最佳实践,请参考对应官方指南。
DISCUSSION