使用 OpenAI API,您可以利用大型语言模型从提示词生成文本,就像使用 ChatGPT 一样。模型几乎可以生成任何类型的文本响应——例如代码、数学公式、结构化 JSON 数据或类人散文。
这是一个使用 Responses API 的简单示例。
1
2
3
4
5
6
7
8
9
import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-5.5",
input: "Write a one-sentence bedtime story about a unicorn."
});
console.log(response.output_text);模型生成的内容数组位于响应的 output 属性中。在这个简单的例子中,我们只有一个输出,如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
[
{
"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": []
}
]
}
]output 数组中通常不止一项! 它可能包含工具调用、由推理模型生成的推理令牌相关数据以及其他项。认为模型的文本输出一定出现在 output[0].content[0].text 是不安全的。
为了方便起见,我们的一些官方 SDK 在模型响应上包含了 output_text 属性,它将模型的所有文本输出汇总为一个字符串。这可以作为访问模型文本输出的快捷方式。
除了纯文本外,您还可以让模型以 JSON 格式返回结构化数据——此功能称为结构化输出 (Structured Outputs)。
这是一个使用 Chat Completions API 的简单示例。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import OpenAI from "openai";
const client = new OpenAI();
const completion = await client.chat.completions.create({
model: "gpt-5",
messages: [
{
role: "user",
content: "Write a one-sentence bedtime story about a unicorn.",
},
],
});
console.log(completion.choices[0].message.content);模型生成的内容数组位于响应的 choices 属性中。在这个简单的例子中,我们只有一个输出,如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
[
{
"index": 0,
"message": {
"role": "assistant",
"content": "Under the soft glow of the moon, Luna the unicorn danced through fields of twinkling stardust, leaving trails of dreams for every child asleep.",
"refusal": null
},
"logprobs": null,
"finish_reason": "stop"
}
]除了纯文本外,您还可以让模型以 JSON 格式返回结构化数据——此功能称为结构化输出 (Structured Outputs)。
选择模型
通过 API 生成内容时,一个关键的选择是决定使用哪个模型——即上述代码示例中的 model 参数。您可以在此处找到可用模型的完整列表。在选择文本生成模型时,需要考虑以下几个因素。
- 推理模型会生成内部思维链来分析输入提示,擅长理解复杂任务和多步规划。它们通常比 GPT 模型更慢且使用成本更高。
- GPT 模型快速、具有成本效益且高度智能,但通过更明确的任务完成指令可以获得更好的效果。
- 大型和小型(mini 或 nano)模型在速度、成本和智能方面各有取舍。大型模型在理解提示和跨领域解决问题方面更有效,而小型模型通常更快、使用成本更低。
如果拿不定主意,gpt-5.5 为通用文本生成和提示词迭代提供了强大的默认选择。
提示词工程
提示工程是为模型编写有效指令的过程,旨在使其持续生成符合您需求的内容。
由于模型生成的内容具有非确定性,因此获取所需输出的提示过程是艺术与科学的结合。然而,您可以应用一些技术和最佳实践来稳定地获得良好的结果。
某些提示工程技术适用于所有模型,例如使用消息角色。但不同类型的模型(如推理模型与 GPT 模型)可能需要不同的提示方式才能产生最佳效果。同一系列模型中甚至不同版本的快照也可能产生不同的结果。因此,随着您构建越来越复杂的应用程序,我们强烈建议:
- 将生产应用程序固定在特定的模型快照上(例如
gpt-4.1-2025-04-14),以确保行为一致。 - 构建评估体系 (evals) 来衡量提示词的表现,以便您在迭代时,或在更改和升级模型版本时监控提示词的性能。
现在,让我们检查一些可用于构建提示词的工具和技术。
消息角色与指令遵循
您可以使用 instructions API 参数或消息角色,通过不同级别的权限向模型提供指令。
instructions 参数为模型提供有关生成响应时应如何表现的高级指令,包括语调、目标和正确响应的示例。通过这种方式提供的任何指令都将优先于 input 参数中的提示词。
1
2
3
4
5
6
7
8
9
10
11
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);上面的示例大致相当于在 input 数组中使用以下输入消息:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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);请注意,instructions 参数仅适用于当前的响应生成请求。如果您正在使用 previous_response_id 参数管理对话状态,则之前轮次使用的 instructions 将不会出现在上下文中。
您可以使用消息角色,通过不同级别的权限向模型提供指令(提示词)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import OpenAI from "openai";
const client = new OpenAI();
const completion = await client.chat.completions.create({
model: "gpt-5",
messages: [
{
role: "developer",
content: "Talk like a pirate."
},
{
role: "user",
content: "Are semicolons optional in JavaScript?",
},
],
});
console.log(completion.choices[0].message);OpenAI 模型规范描述了我们的模型如何为不同角色的消息赋予不同级别的优先级。
developer(开发者) | 用户 (user) | 助手 (assistant) |
|---|---|---|
developer 消息是由应用程序开发人员提供的指令,优先级高于 user 消息。 | user 消息是由最终用户提供的指令,优先级低于 developer 消息。 | 模型生成的消息具有 assistant(助手)角色。 |
多轮对话可以由多个这些类型的消息组成,以及您和模型提供的其他内容类型。了解更多关于管理对话状态的信息请点击此处。
您可以将 developer 和 user 消息视为编程语言中的函数及其参数。
developer消息提供系统的规则和业务逻辑,就像函数定义一样。user消息提供输入和配置,developer消息的指令将应用于这些输入和配置,就像函数的参数一样。
可重用提示词
在 OpenAI 控制面板中,您可以开发可重用的提示词,以便在 API 请求中使用,而不是在代码中指定提示内容。通过这种方式,您可以更轻松地构建和评估提示词,并在不更改集成代码的情况下部署改进后的版本。
可重用提示词目前仅在 Responses API 中受支持。它们在 Chat Completions API 中不可用。
工作原理如下
- 创建一个可重用提示词:在控制面板中创建带有占位符(如
{{customer_name}})的提示词。 - 使用提示词:在您的 API 请求中使用
prompt参数。Prompt 参数对象有三个您可以配置的属性:id— 提示词的唯一标识符,可在控制面板中找到version— 提示词的特定版本(默认为控制面板中指定的“当前”版本)variables— 用于替换提示词中变量的值映射。替换值可以是字符串,或其他响应输入消息类型,如input_image或input_file。查看完整 API 参考。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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);1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import fs from "fs";
import OpenAI from "openai";
const client = new OpenAI();
// Upload a PDF we will reference in the prompt variables
const file = await client.files.create({
file: fs.createReadStream("draconomicon.pdf"),
purpose: "user_data",
});
const response = await client.responses.create({
model: "gpt-5",
prompt: {
id: "pmpt_abc123",
variables: {
topic: "Dragons",
reference_pdf: {
type: "input_file",
file_id: file.id,
},
},
},
});
console.log(response.output_text);使用 Markdown 和 XML 进行消息格式化
在编写 developer 和 user 消息时,您可以结合使用 Markdown 格式和 XML 标签,帮助模型理解提示词和上下文数据的逻辑边界。
Markdown 标题和列表有助于标记提示词的不同部分,并向模型传达层次结构。它们还可以使您的提示词在开发过程中更具可读性。XML 标签可以帮助界定一段内容(例如用于参考的辅助文档)的起始和结束位置。XML 属性还可用于定义提示词中内容的元数据,这些元数据可被您的指令引用。
通常,开发者消息应包含以下部分,且通常按此顺序排列(尽管确切的最佳内容和顺序可能因您使用的模型而异):
- 身份 (Identity): 描述助手的用途、沟通风格和高级目标。
- 指令 (Instructions): 为模型提供有关如何生成所需响应的指导。它应遵循哪些规则?模型应该做什么,绝不能做什么?此部分可以包含许多针对您的用例的子部分,例如模型应如何调用自定义函数。
- 示例 (Examples): 提供可能的输入示例,以及模型的预期输出。
- 上下文 (Context): 为模型提供生成响应可能需要的任何附加信息,例如训练数据之外的私有/专有数据,或您认为特别相关的任何其他数据。此内容通常最好放在提示词的末尾,因为您可能会针对不同的生成请求包含不同的上下文。
以下是使用 Markdown 和 XML 标签构建带有不同部分和支持示例的 developer 消息的示例。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 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>1
2
3
4
5
6
7
8
9
10
11
12
13
import fs from "fs/promises";
import OpenAI from "openai";
const client = new OpenAI();
const instructions = await fs.readFile("prompt.txt", "utf-8");
const response = await client.responses.create({
model: "gpt-5",
instructions,
input: "How would I declare a variable for a last name?",
});
console.log(response.output_text);通过提示词缓存节省成本和延迟
构建消息时,应尽量将期望在 API 请求中反复使用的内容放在提示词的开头,并且放在您传递给 Chat Completions 或 Responses 的 JSON 请求体的前几个 API 参数中。这使您能够最大限度地利用提示词缓存来节省成本和降低延迟。
少样本学习 (Few-shot learning)
少样本学习允许您通过在提示词中包含少量输入/输出示例来引导大型语言模型完成新任务,而无需对模型进行微调 (fine-tuning)。模型会隐式地从这些示例中“提取”模式并将其应用于提示词。在提供示例时,尽量展示多样化的可能输入及其预期的输出。
通常,您将在 API 请求的 developer 消息中提供示例。这是一个包含示例的 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>包含相关的上下文信息
在您给模型的提示词中包含模型可以用来生成响应的额外上下文信息通常很有用。您可以这样做有几个常见原因:
- 使模型能够访问专有数据,或模型训练数据集之外的任何其他数据。
- 将模型的响应限制在您认为最有益的一组特定资源内。
向模型生成请求添加额外相关上下文的技术有时称为检索增强生成 (RAG)。您可以通过多种方式向提示词添加额外上下文,从查询向量数据库并将获取的文本包含在提示词中,到使用 OpenAI 的内置文件搜索工具根据上传的文档生成内容。
规划上下文窗口
模型在生成请求期间只能处理其考虑范围内的有限数据。此内存限制称为上下文窗口,以令牌 (tokens)(您传递的数据块,从文本到图像)定义。
模型具有不同的上下文窗口大小,从较低的 100k 范围到较新的 GPT-4.1 模型的 100 万个令牌不等。请参考模型文档以了解每个模型的具体上下文窗口大小。
当前 GPT-5 系列模型的提示
像 gpt-5.5 这样的 GPT 模型受益于精确的指令,这些指令在提示词中明确提供了完成任务所需的逻辑和数据。要充分利用最新的 GPT-5 系列模型,请从当前的提示词指南开始。
通过当前的指导、实用示例和迁移说明,充分利用最新的 GPT-5 系列模型。
最新 GPT-5 系列模型的提示最佳实践
如需获取完整且最新的处理方案,请使用提示词指南 (prompt guidance)。下面的实用提醒仍然适用。
提示推理模型
在提示推理模型与提示 GPT 模型时,需要考虑一些差异。总的来说,推理模型在仅有高级指导的任务上会提供更好的结果。这与 GPT 模型不同,GPT 模型受益于非常精确的指令。
您可以这样思考推理模型和 GPT 模型之间的区别:
- 推理模型就像一位资深的同事。您可以给他们一个要实现的目标,并信任他们能处理好细节。
- GPT 模型就像一位初级同事。他们通过明确的指令来创建特定输出时表现最好。
有关使用推理模型时的最佳实践的更多信息,请参考此指南。
后续步骤
既然您已经了解了文本输入和输出的基础知识,您可能想接着查看以下资源之一:
使用 Playground 开发和迭代提示词。
确保模型发出的 JSON 数据符合 JSON 架构。
在 API 参考中查看文本生成的所有选项。
其他资源
如需更多灵感,请访问 OpenAI Cookbook,其中包含示例代码,并提供了指向第三方资源的链接,例如: