通过 OpenAI API,您可以让大语言模型根据提示词生成文本,就像使用 ChatGPT 时一样。模型几乎可以生成任何形式的文本回复,例如代码、数学方程、结构化 JSON 数据,或读起来自然流畅、如同人写的文章。
要直接向模型发出请求,请使用 Responses API。下面的文本生成调用就是一个例子。
1
2
3
4
5
6
7
8
9import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-6.2-astra",
input: "Write a one-sentence bedtime story about a unicorn.",
});
console.log(response.output_text);
1
2
3
4
5
6
7
8
9
10from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6.2-astra",
input="Write a one-sentence bedtime story about a unicorn.",
)
print(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
23package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
resp, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{
Model: "gpt-6.2-astra",
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say this is a test")},
})
if err != nil {
panic(err.Error())
}
fmt.Println(resp.OutputText())
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
public class Main {
public static void main(String[] args) {
OpenAIClient client = OpenAIOkHttpClient.fromEnv();
ResponseCreateParams params =
ResponseCreateParams.builder().input("Say this is a test").model("gpt-6.2-astra").build();
Response response = client.responses().create(params);
response.output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(outputText -> System.out.println(outputText.text()));
}
}
1
2
3
4
5
6
7
8
9
10
11
12using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
ResponseResult response = await client.CreateResponseAsync(
"gpt-6.2-astra",
"Say 'this is a test.'"
);
Console.WriteLine($"[ASSISTANT]: {response.GetOutputText()}");
1
2
3
4
5
6
7
8
9
10require "openai"
openai = OpenAI::Client.new
response = openai.responses.create(
model: "gpt-6.2-astra",
input: "Write a one-sentence bedtime story about a unicorn."
)
puts(response.output_text)
1
2
3
4
5openai responses create \
--model "gpt-6.2-astra" \
--input "Write a one-sentence bedtime story about a unicorn." \
--raw-output \
--transform 'output.#(type=="message").content.0.text'
1
2
3
4
5
6
7curl "https://api.openai.com/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-6.2-astra",
"input": "Write a one-sentence bedtime story about a unicorn."
}'
响应的 output 属性是一个数组,包含模型生成的内容。在这个示例中,数组只有一个输出项:
1234567891011121314[
{
"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 数组通常包含多个输出项! 其中可能包括工具调用、与推理模型生成的推理 Token 相关的数据,以及其他内容。不能假定模型输出的文本一定位于 output[0].content[0].text。
为了方便使用,部分官方 SDK 在模型响应中提供了 output_text 属性。该属性将模型输出的所有文本合并为一个字符串,方便您快速获取文本输出。
除了纯文本,您还可以让模型以 JSON 格式返回结构化数据。这项功能称为结构化输出。
提示词工程是指为模型编写有效的指令,使其能够稳定地生成符合您要求的内容。
由于模型生成的内容具有不确定性,要通过提示词获得预期输出,既需要经验和判断,也需要系统的方法。运用合适的技巧和最佳实践,可以帮助您稳定地获得良好的结果。
有些提示词工程技巧适用于所有模型,例如使用消息角色。但要获得最佳结果,不同模型可能需要不同的提示方式。即使是同一系列模型的不同快照,也可能产生不同的结果。在构建更复杂的应用时,我们强烈建议您:
- 在生产应用中固定使用特定的模型快照(例如
gpt-5.5-2026-04-23),以确保模型行为一致。
- 编写测试并构建评估套件,衡量模型在给定提示词下的表现,以便在迭代提示词、更换或升级模型版本时持续监测效果。
下面介绍一些可用于编写提示词的工具和技巧。
OpenAI 提供多种模型和多个 API 供您选择。推理模型(例如 gpt-6.2-astra)的行为与聊天模型不同,适合它们的提示词也有所不同。值得注意的是,通过 Responses API 使用推理模型时,模型表现更好,展现出的智能水平也更高。
无论您构建哪种文本生成应用,我们都建议优先使用 Responses API,而非较早推出的 Chat Completions API。如果您使用的是推理模型,迁移到 Responses API 尤其有益。
您可以向模型提供不同优先级的指令,具体做法是结合使用 instructions API 参数和消息角色。
instructions 参数用于设定模型生成回复时应遵循的总体要求,包括语气、目标和正确回复的示例。这些指令的优先级高于 input 中的用户消息。
1
2
3
4
5
6
7
8
9
10
11import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-6.2-astra",
reasoning: { effort: "low" },
instructions: "Talk like a pirate.",
input: "Are semicolons optional in JavaScript?",
});
console.log(response.output_text);
1
2
3
4
5
6
7
8
9
10
11
12from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6.2-astra",
reasoning={"effort": "low"},
instructions="Talk like a pirate.",
input="Are semicolons optional in JavaScript?",
)
print(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
26
27
28
29package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6.2-astra",
Instructions: openai.String("Talk like a pirate."),
Reasoning: responses.ReasoningParam{
Effort: responses.ReasoningEffortLow,
},
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("Are semicolons optional in JavaScript?"),
},
})
if err != nil {
panic(err)
}
fmt.Println(response.OutputText())
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.Reasoning;
import com.openai.models.ReasoningEffort;
import com.openai.models.responses.ResponseCreateParams;
String semicolonsDevMsg = "Talk like a pirate.";
String semicolonsPrompt = "Are semicolons optional in JavaScript?";
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6.2-astra")
.input(semicolonsPrompt)
.instructions(semicolonsDevMsg)
.reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())
.build();
client.responses().create(params).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text()));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
CreateResponseOptions options = new()
{
Model = "gpt-6.2-astra",
Instructions = "Talk like a pirate.",
ReasoningOptions = new ResponseReasoningOptions
{
ReasoningEffortLevel = ResponseReasoningEffortLevel.Low,
},
};
options.InputItems.Add(
ResponseItem.CreateUserMessageItem("Are semicolons optional in JavaScript?")
);
ResponseResult response = await client.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
1
2
3
4
5
6
7
8
9
10
11require "openai"
client = OpenAI::Client.new
response = client.responses.create(
model: "gpt-6.2-astra",
instructions: "Talk like a pirate.",
reasoning: { effort: :low },
input: "Are semicolons optional in JavaScript?"
)
puts(response.output_text)
1
2
3
4
5
6
7
8
9curl "https://api.openai.com/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-6.2-astra",
"reasoning": {"effort": "low"},
"instructions": "Talk like a pirate.",
"input": "Are semicolons optional in JavaScript?"
}'
要在多轮对话中使用相同的指令,请将这些指令写入第一条 developer 消息,并将该消息放入 input 中。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-6.2-astra",
reasoning: { effort: "low" },
input: [
{
role: "developer",
content: "Talk like a pirate.",
},
{
role: "user",
content: "Are semicolons optional in JavaScript?",
},
],
});
console.log(response.output_text);
1
2
3
4
5
6
7
8
9
10
11
12
13
14from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6.2-astra",
reasoning={"effort": "low"},
input=[
{"role": "developer", "content": "Talk like a pirate."},
{"role": "user", "content": "Are semicolons optional in JavaScript?"},
],
)
print(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
26
27
28
29
30
31
32
33
34
35
36
37package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6.2-astra",
Reasoning: responses.ReasoningParam{
Effort: responses.ReasoningEffortLow,
},
Input: responses.ResponseNewParamsInputUnion{
OfInputItemList: responses.ResponseInputParam{
responses.ResponseInputItemParamOfMessage(
"Talk like a pirate.",
responses.EasyInputMessageRoleDeveloper,
),
responses.ResponseInputItemParamOfMessage(
"Are semicolons optional in JavaScript?",
responses.EasyInputMessageRoleUser,
),
},
},
})
if err != nil {
panic(err)
}
fmt.Println(response.OutputText())
}
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
26
27
28
29
30
31
32
33
34
35
36
37import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.Reasoning;
import com.openai.models.ReasoningEffort;
import com.openai.models.responses.EasyInputMessage;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputItem;
import java.util.List;
String semicolonsDevMsg = "Talk like a pirate.";
String semicolonsPrompt = "Are semicolons optional in JavaScript?";
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6.2-astra")
.input(
ResponseCreateParams.Input.ofResponse(
List.of(
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.DEVELOPER)
.content(semicolonsDevMsg)
.build()),
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content(semicolonsPrompt)
.build()))))
.reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())
.build();
client.responses().create(params).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text()));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
CreateResponseOptions options = new()
{
Model = "gpt-6.2-astra",
ReasoningOptions = new ResponseReasoningOptions
{
ReasoningEffortLevel = ResponseReasoningEffortLevel.Low,
},
};
options.InputItems.Add(
ResponseItem.CreateDeveloperMessageItem("Talk like a pirate.")
);
options.InputItems.Add(
ResponseItem.CreateUserMessageItem("Are semicolons optional in JavaScript?")
);
ResponseResult response = await client.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19require "openai"
client = OpenAI::Client.new
response = client.responses.create(
model: "gpt-6.2-astra",
reasoning: { effort: :low },
input: [
{
role: :developer,
content: "Talk like a pirate."
},
{
role: :user,
content: "Are semicolons optional in JavaScript?"
}
]
)
puts(response.output_text)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17curl "https://api.openai.com/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-6.2-astra",
"reasoning": {"effort": "low"},
"input": [
{
"role": "developer",
"content": "Talk like a pirate."
},
{
"role": "user",
"content": "Are semicolons optional in JavaScript?"
}
]
}'
对于仅适用于当前轮次的指令,请使用顶层 instructions 参数。串联多个响应时,如果使用 previous_response_id,最初的 developer 消息会保留在对话中。从 GPT-6.2 起,顶层 instructions 按未缓存输入的费率计费。第一条 developer 消息中的可复用指令可以使用提示词缓存。
OpenAI 模型规范说明了模型如何根据消息角色确定消息的优先级。
| developer | user | assistant |
|---|
developer 消息包含应用开发者提供的指令,其优先级高于用户消息。
| user 消息包含最终用户提供的指令,其优先级低于开发者消息。
| 模型生成的消息使用 assistant 角色。 |
一段多轮对话可能包含多条上述类型的消息,以及您和模型提供的其他类型的内容。有关详情,请参阅对话状态管理指南。
您可以把 developer 消息和 user 消息之间的关系理解为编程语言中函数与参数之间的关系。
developer 消息规定系统规则和业务逻辑,类似于函数定义。
user 消息提供输入和配置,类似于传给函数的参数。模型会按照 developer 消息中的指令处理这些输入和配置。
请将生产环境使用的提示词存放在应用代码中,避免创建可复用的提示词对象。通过代码管理提示词,您就可以利用带类型的输入、代码审查、测试和常规部署流程来调整模型行为。
OpenAI 正在逐步弃用 API 中的可复用提示词对象。自 2026 年 6 月 3 日起,OpenAI 将逐步淡化提示词创建功能,并计划于 2026 年 11 月 30 日关闭 v1/prompts。最新时间安排请参阅弃用公告。
开发新的文本生成功能时,请遵循以下做法:
- 将构建提示词的代码放在一个小模块中,位置靠近它所支持的功能代码。
- 使用带类型的函数参数或模式来定义动态值,例如客户数据、文件或任务选项。
- 将可复用的指令作为第一条
developer 消息放入 input,并通过 instructions 参数向 Responses API 传递仅适用于当前轮次的指令。
- 在修改生产环境的提示词之前,添加有代表性的测试数据、测试和评估检查。
- 通过部署系统发布提示词变更。如果需要分阶段发布,请使用功能开关或配置来控制发布进度。
如果现有集成已经通过提示词 ID 或版本号调用已保存的提示词,请按照提示词对象迁移指南将该提示词迁移到代码中。
了解文本输入和输出的基础知识后,您可以通过以下资源继续探索。
在 Playground 中编写并反复改进提示词。
确保模型输出的 JSON 数据符合指定的 JSON 模式。