通过 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-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
10 from 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
23 package 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
20 import 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
12 using 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
10 require "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
5 openai 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
7 curl "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 属性是一个数组,其中包含模型生成的内容。本例只有一个输出项,内容如下:
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 数组通常包含多个元素! 其中可能包含工具调用、有关推理模型 生成的推理 Token 的数据,以及其他内容。请勿假定 output[0].content[0].text 一定包含模型输出的文本。
为了便于使用,部分官方 SDK 在模型响应中提供了 output_text 属性,将模型输出的所有文本合并为一个字符串。您可以通过该属性快速获取模型的文本输出。
除了纯文本,您还可以让模型以 JSON 格式返回结构化数据。这项功能称为结构化输出 。
下面是一个使用 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.5" ,
messages: [
{
role: "user" ,
content: "Write a one-sentence bedtime story about a unicorn." ,
},
],
});
console. log (completion.choices[ 0 ].message.content); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 from openai import OpenAI
client = OpenAI()
completion = client.chat.completions.create(
model="gpt-5.5",
messages=[
{
"role": "user",
"content": "Write a one-sentence bedtime story about a unicorn.",
}
],
)
print(completion.choices[0].message.content) 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 package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
)
func main() {
client := openai.NewClient()
completion, err := client.Chat.Completions.New(
context.Background(),
openai.ChatCompletionNewParams{
Model: "gpt-6.2-astra",
Messages: []openai.ChatCompletionMessageParamUnion{
openai.UserMessage("Write a one-sentence bedtime story about a unicorn."),
},
},
)
if err != nil {
panic(err)
}
fmt.Println(completion.Choices[0].Message.Content)
} 1
2
3
4
5
6
7
8
9
10
11
12
13 import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
ChatCompletionCreateParams params =
ChatCompletionCreateParams.builder()
.model("gpt-6.2-astra")
.addUserMessage("Write a one-sentence bedtime story about a unicorn.")
.build();
client.chat().completions().create(params).choices().stream()
.flatMap(choice -> choice.message().content().stream())
.forEach(System.out::println); 1
2
3
4
5
6
7
8
9
10
11 using OpenAI.Chat;
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "gpt-6.2-astra";
ChatClient client = new(model, key);
ChatCompletion completion = await client.CompleteChatAsync(
new UserChatMessage("Write a one-sentence bedtime story about a unicorn.")
);
Console.WriteLine(completion.Content[0].Text); 1
2
3
4
5
6
7
8
9
10
11
12
13
14 require "openai"
client = OpenAI::Client.new
completion = client.chat.completions.create(
model: "gpt-6.2-astra",
messages: [
{
role: :user,
content: "Write a one-sentence bedtime story about a unicorn."
}
]
)
puts(completion.choices.fetch(0).message.content) 1
2
3
4
5
6
7
8
9
10
11
12 curl "https://api.openai.com/v1/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-5.5",
"messages": [
{
"role": "user",
"content": "Write a one-sentence bedtime story about a unicorn."
}
]
}' 响应的 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 格式返回结构化数据。这项功能称为结构化输出 。
通过 API 生成内容时,选择模型是一项重要决定。上面代码示例中的 model 参数指定了要使用的模型。查看全部可用模型 。选择用于文本生成的模型时,可以考虑以下因素。
推理模型 会在内部生成思维链来分析输入的提示词,擅长理解复杂任务和制定多步骤计划。与 GPT 模型相比,推理模型通常速度较慢,使用成本也较高。
GPT 模型 速度快、性价比高,能力也很强。明确说明如何完成任务,有助于这类模型取得更好的结果。
大型模型和小型模型(mini 或 nano) 在速度、成本和能力上各有取舍。大型模型更擅长理解提示词和解决跨领域问题,小型模型通常速度更快、成本更低。
如果您不确定选哪个模型,gpt-6.2-astra 是通用文本生成和提示词迭代的理想默认选择。
提示词工程 是为模型编写有效指令,使其持续生成符合您要求的内容的过程。
模型生成的内容具有不确定性,因此,要通过提示词获得预期输出,既需要经验判断,也需要系统的方法。运用适当的技巧和最佳实践,可以持续获得良好的结果。
有些提示词工程技巧适用于所有模型,例如使用消息角色。但不同类型的模型(例如推理模型和 GPT 模型)可能需要不同的提示方式才能取得最佳效果。即使是同一系列模型的不同快照,生成结果也可能不同。在构建更复杂的应用时,我们强烈建议您:
在生产应用中固定使用特定的模型快照 (例如 gpt-4.1-2025-04-14),以确保模型行为一致。
建立测试和评估套件,衡量模型在给定提示词下的表现,以便在迭代提示词或切换、升级模型版本时监测效果。
下面介绍一些可用于构建提示词的工具和技巧。
您可以向模型提供不同优先级 的指令,具体方式是使用 API 的 instructions 参数或消息角色 。
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-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
12 from 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
29 package 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
23 import 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
22 using 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
11 require "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
9 curl "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
19 import 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
14 from 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
37 package 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
37 import 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
24 using 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
19 require "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
17 curl "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 消息就会保留在对话中。
您可以向模型提供不同优先级 的指令(提示词),具体方式是使用消息角色 。
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-6.2-astra" ,
messages: [
{
role: "developer" ,
content: "Talk like a pirate." ,
},
{
role: "user" ,
content: "Are semicolons optional in JavaScript?" ,
},
],
});
console. log (completion.choices[ 0 ].message); 1
2
3
4
5
6
7
8
9
10
11
12
13
14 from openai import OpenAI
client = OpenAI()
completion = client.chat.completions.create(
model="gpt-6.2-astra",
reasoning_effort="low",
messages=[
{"role": "developer", "content": "Talk like a pirate."},
{"role": "user", "content": "Are semicolons optional in JavaScript?"},
],
)
print(completion.choices[0].message.content) 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 package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
)
func main() {
client := openai.NewClient()
completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{
Model: "gpt-6.2-astra",
Messages: []openai.ChatCompletionMessageParamUnion{
openai.DeveloperMessage("Talk like a pirate."),
openai.UserMessage("Are semicolons optional in JavaScript?"),
},
})
if err != nil {
panic(err)
}
fmt.Println(completion.Choices[0].Message.Content)
} 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
String semicolonsDevMsg = "Talk like a pirate.";
String semicolonsPrompt = "Are semicolons optional in JavaScript?";
ChatCompletionCreateParams params =
ChatCompletionCreateParams.builder()
.model("gpt-6.2-astra")
.addDeveloperMessage(semicolonsDevMsg)
.addUserMessage(semicolonsPrompt)
.build();
client.chat().completions().create(params).choices().stream()
.flatMap(choice -> choice.message().content().stream())
.forEach(System.out::println); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 using OpenAI.Chat;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "gpt-6.2-astra";
ChatClient client = new(model, key);
ChatCompletion completion = await client.CompleteChatAsync(
[
new DeveloperChatMessage("Talk like a pirate."),
new UserChatMessage("Are semicolons optional in JavaScript?"),
]
);
Console.WriteLine(completion.Content[0].Text); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 require "openai"
client = OpenAI::Client.new
completion = client.chat.completions.create(
model: "gpt-6.2-astra",
messages: [
{
role: :developer,
content: "Talk like a pirate."
},
{
role: :user,
content: "Are semicolons optional in JavaScript?"
}
]
)
puts(completion.choices.fetch(0).message.content) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 curl "https://api.openai.com/v1/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-6.2-astra",
"messages": [
{
"role": "developer",
"content": "Talk like a pirate."
},
{
"role": "user",
"content": "Are semicolons optional in JavaScript?"
}
]
}'
OpenAI 模型规范 说明了模型如何根据消息角色确定消息的优先级。
developer
user
assistant
developer 消息包含开发者提供的指令,优先级高于 user 消息。
user 消息包含最终用户提供的指令,优先级低于 developer 消息。
模型生成的消息使用 assistant 角色。
多轮对话可以包含多条上述类型的消息,以及您和模型提供的其他类型的内容。进一步了解如何管理对话状态 。
您可以把 developer 消息与 user 消息的关系理解为编程语言中函数与参数的关系。
developer 消息规定系统的规则和业务逻辑,相当于函数定义。
user 消息提供输入和配置,相当于传给函数的参数。模型会将 developer 消息中的指令应用于这些输入和配置。
请将生产环境使用的提示词保存在应用代码中,无需创建可复用的提示词对象。在代码中管理提示词,您就可以利用带类型的输入、代码审查、测试和常规部署流程来调整模型行为。
OpenAI 正在弃用 API 中的可复用提示词对象。自 2026 年 6 月 3 日起,创建提示词对象将不再是重点,v1/prompts 计划于 2026 年 11 月 30 日停用。有关最新时间安排,请参阅弃用公告 。
开展新的提示词工程工作时:
将构建提示词的逻辑放在一个小模块中,与使用它的功能代码放在一起。
使用带类型的函数参数或模式来定义动态值,例如客户数据、文件或任务选项。
将可复用的指令作为第一条 developer 消息放入 input,并通过 instructions 向 Responses API 传入仅适用于当前轮次的指令。
在更改生产环境的提示词之前,添加有代表性的测试数据、测试用例和评估检查。
通过部署系统发布提示词更改。需要分阶段发布时,请使用功能开关或配置。
如果您的集成已通过提示词 ID 或版本调用已保存的提示词,请参阅提示词对象迁移指南 ,将该提示词迁移到代码中。
编写 developer 和 user 消息时,您可以结合使用 Markdown 格式和 XML 标签 ,帮助模型分辨提示词和上下文数据中各部分的逻辑边界。
Markdown 标题和列表可以标出提示词中的不同部分,让模型了解其层级关系,也有助于您在开发过程中阅读提示词。XML 标签可以明确标出某段内容的起止位置,例如一份供模型参考的文档。您还可以使用 XML 属性为提示词中的内容定义元数据,并在指令中引用这些元数据。
开发者消息通常按以下顺序组织,但最合适的内容和顺序可能因模型而异:
身份: 说明助手的用途、沟通风格和总体目标。
指令: 说明模型应如何生成您想要的回复。它需要遵循哪些规则?应该做什么?哪些事情绝不能做?您可以根据使用场景将这部分细分为多个小节,例如说明模型应如何调用自定义函数 。
示例: 给出可能的输入,以及您希望模型针对每个输入生成的输出。
上下文: 提供模型生成回复时可能需要的补充信息,例如训练数据中没有的私有或专有数据,或您知道与任务密切相关的其他数据。不同的生成请求可能需要不同的上下文,因此通常最好将这部分内容放在提示词靠近末尾的位置。
下面的示例使用 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>
API 请求
将示例提示词保存为
prompt.txt。运行 curl 示例前,请先安装
jq。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 import fs from "fs/promises" ;
import OpenAI from "openai" ;
const client = new OpenAI ();
const instructions = await fs. readFile ( "fixtures/prompt.txt" , "utf-8" );
const response = await client.responses. create ({
model: "gpt-6.2-astra" ,
input: [
{ role: "developer" , content: instructions },
{
role: "user" ,
content: "How would I declare a variable for a last name?" ,
},
],
});
console. log (response.output_text); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 from openai import OpenAI
client = OpenAI()
with open("prompt.txt", "r", encoding="utf-8") as f:
instructions = f.read()
response = client.responses.create(
model="gpt-6.2-astra",
input=[
{"role": "developer", "content": instructions},
{"role": "user", "content": "How would I declare a variable for a last name?"},
],
)
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 package main
import (
"context"
"fmt"
"os"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
instructions, err := os.ReadFile("prompt.txt")
if err != nil {
panic(err)
}
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6.2-astra",
Input: responses.ResponseNewParamsInputUnion{
OfInputItemList: responses.ResponseInputParam{
responses.ResponseInputItemParamOfMessage(string(instructions), responses.EasyInputMessageRoleDeveloper),
responses.ResponseInputItemParamOfMessage("How would I declare a variable for a last name?", 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 import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.EasyInputMessage;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputItem;
import java.util.List;
String instructions =
"You are a coding assistant. Answer with concise JavaScript examples and use semicolons.";
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6.2-astra")
.inputOfResponse(
List.of(
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.DEVELOPER)
.content(instructions)
.build()),
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content("How would I declare a variable for a last name?")
.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 using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
string instructions = await File.ReadAllTextAsync("prompt.txt");
CreateResponseOptions options = new()
{
Model = "gpt-6.2-astra",
};
options.InputItems.Add(ResponseItem.CreateDeveloperMessageItem(instructions));
options.InputItems.Add(
ResponseItem.CreateUserMessageItem("How would I declare a variable for a last name?")
);
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
19 require "openai"
client = OpenAI::Client.new
instructions = File.read(File.join(__dir__, "prompt.txt"))
response = client.responses.create(
model: "gpt-6.2-astra",
input: [
{
role: :developer,
content: instructions
},
{
role: :user,
content: "How would I declare a variable for a last name?"
}
]
)
puts(response.output_text) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 set -euo pipefail
request=$(jq -n --rawfile instructions prompt.txt '
{
model: "gpt-6.2-astra",
input: [
{role: "developer", content: $instructions},
{role: "user", content: "How would I declare a variable for a last name?"}
]
}')
curl --fail-with-body --silent --show-error https://api.openai.com/v1/responses \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d "$request" |
jq -er '[.output[]? | select(.type == "message") | .content[]? | select(.type == "output_text") | .text] | join("")'
将可复用的指令写入第一条 developer 消息。使用 Responses API 时,将这条消息放在 input 数组中;使用 Chat Completions API 时,将其放在 messages 数组中。将反复使用的示例和参考资料放在每次请求中可能变化的用户输入之前。这样,各请求共有的前缀就可以利用提示词缓存 。
少样本学习让您只需在提示词中加入少量输入和输出示例,就能引导大语言模型执行新任务,无需微调 模型。模型会自行从示例中归纳规律,并在处理提示词时应用这些规律。选择示例时,尽量覆盖多种可能的输入,并为每种输入提供预期输出。
通常,您可以在 API 请求的 developer 消息中提供示例。下面的 developer 消息通过示例向模型演示如何区分正面和负面的客服评价。
# 身份
您是一名乐于助人的助手,负责为简短的产品评价标注 Positive、Negative 或 Neutral 标签。
# 指令
* 回复只能包含一个单词,不加任何格式或说明。
* 根据给定产品评价的情感倾向,从“Positive”、“Negative”和“Neutral”中选取一个作为回复。
# 示例
<product_review id="example-1">
我太喜欢这副耳机了,音质棒极了!
</product_review>
<assistant_response id="example-1">
Positive
</assistant_response>
<product_review id="example-2">
续航还行,但耳垫摸起来很廉价。
</product_review>
<assistant_response id="example-2">
Neutral
</assistant_response>
<product_review id="example-3">
客服太差了,我再也不会买他们家的东西了。
</product_review>
<assistant_response id="example-3">
Negative
</assistant_response>
在发给模型的提示词中加入补充上下文,往往有助于模型生成回复。常见的原因有:
让模型能够使用专有数据,或使用其训练数据集以外的其他数据。
限定模型回复所依据的资料范围,让模型只使用您认为最有帮助的资料。
在模型生成请求中补充相关上下文的技术有时称为检索增强生成(RAG) 。您可以通过多种方式向提示词添加上下文,例如查询向量数据库并将返回的文本加入提示词,或使用 OpenAI 内置的文件搜索工具 ,根据上传的文档生成内容。
在一次生成请求中,模型能够处理的上下文数据量有限。这个容量上限称为上下文窗口 ,以 Token 为单位。Token 是传入模型的数据片段,可以来自文本、图像等不同类型的输入。
不同模型的上下文窗口大小各不相同,从十几万 Token 到较新的 GPT-4.1 模型支持的一百万 Token 不等。有关各模型的具体上下文窗口大小,请参阅模型文档 。
对于 gpt-6.2-astra 等 GPT 模型,在提示词中给出精确的指令,明确说明完成任务所需的逻辑并提供相应数据,可以改善输出效果。要充分发挥最新模型的能力,请先阅读当前的提示词指南。
GPT-6.2 Astra prompting guide
参考最新指南、实用示例和迁移说明,为最新模型编写更有效的提示词。
完整的最新说明请参阅最新模型的提示词最佳实践 。以下建议仍然适用。
编程 使用 gpt-6.2-astra 执行编程任务时,以下做法最有效:明确智能体的角色,用示例规定工具的使用流程,要求模型通过充分测试验证正确性,并制定 Markdown 格式规范,让输出清晰易读。
明确角色和工作流程
将模型设定为职责明确的软件工程智能体。清楚说明如何使用 functions.run 等工具执行编程任务,并指出何时不应使用某些模式。例如,仅在必要时使用交互式执行模式。
测试与验证
要求模型运行单元测试或 Python 命令来测试更改,并仔细验证补丁,因为 apply_patch 等工具即使执行失败也可能返回“Done”。
工具使用示例
给出具体示例,演示如何通过提供的函数调用命令。这样可以提高可靠性,让模型更准确地遵循预期的工作流程。
Markdown 规范
要求模型生成清晰、语义正确的 Markdown,在适当的位置使用行内代码、围栏代码块、列表和表格,并用反引号标记文件路径、函数名和类名。
有关编程任务的详细指南和提示词示例,请参阅最新模型的提示词最佳实践 。
前端工程 GPT-6.2 Astra 既擅长从零构建前端,也能在成熟的大型代码库中完成开发任务。为获得最佳效果,我们建议使用以下库:
样式和界面: Tailwind CSS、shadcn/ui、Radix Themes
图标: Lucide、Material Symbols、Heroicons
动画 :Motion
从零构建 Web 应用
只需一条提示词,GPT-5 就能生成前端 Web 应用,无需提供示例。以下是一条示例提示词:
1 2 3 4 5 6 您是一名世界一流的 Web 开发者,能根据一条提示词从零构建视觉出众、交互丰富且富有创意的网站,擅长一次就交付高质量的解决方案。
请按以下步骤工作:
第 1 步:制定一套评估标准,反复完善,直到对这套标准完全有把握。
第 2 步:考虑一次生成的 Web 应用要达到世界一流水平需要具备哪些要素,据此制定一份涵盖 5–7 个评估维度的 & lt ; ONE_SHOT_RUBRIC & gt ; 。这份评估标准仅供内部使用,切勿对外展示。
第 3 步:对照标准反复改进解决方案,使其尽可能满足给定提示词的要求。只要还有一个维度未达到最高标准,就继续改进并重新评估。
第 4 步:在完整实现目标的前提下,尽量简化方案,避免使用 Next.js 或 React 等外部依赖。 与大型代码库集成
在大型代码库中进行前端开发时,我们发现,在提示词中加入以下几类指令效果最好:
原则: 设定视觉质量标准,使用模块化、可复用的组件,并保持设计一致。
界面与用户体验: 明确排版、配色、间距和布局、交互状态(如悬停、空状态和加载状态),以及无障碍要求。
结构: 定义文件和文件夹的组织方式,便于将新代码集成到现有代码库中。
组件: 给出可复用的封装示例,并说明如何将后端调用与组件逻辑分离。
页面: 提供常见布局的模板。
智能体指令: 要求模型确认设计假设、搭建项目骨架、执行既定标准、集成 API、测试各种状态,并编写代码文档。
有关前端开发的详细指南和提示词示例,请参阅最新模型的提示词最佳实践 。
智能体任务 使用 gpt-6.2-astra 执行智能体任务或长时间运行的任务时,请要求模型规划从开始到完成的全部步骤,在进行重要的工具调用前说明调用原因,并使用任务列表工具跟踪进度。
规划并持续执行任务
要求模型将请求拆分为子任务,每次调用工具后检查结果,逐项核实完成情况,直至整个请求得到解决后再将控制权交还给用户。
请记住,作为智能体,您必须持续处理用户的请求,直到请求得到完整解决,再结束当前轮次,将控制权交还给用户。将请求拆分为所有需要处理的子任务,并逐项确认已经完成。不要只完成一部分就停下。只有在确信问题已经解决时,才能结束当前轮次。请做好处理多个请求的准备。只有用户确认没有其他请求后,才能结束整个交互。
在继续调用函数之前,必须按照工作流程的各个步骤做好详细规划。每次调用函数后,都要仔细检查调用结果,确保用户的请求及其各项子任务都得到完整解决。 在关键步骤前说明原因
要求模型说明调用工具的原因,但只需在关键步骤作此说明。
在调用工具之前,先说明为什么要调用这个工具。 使用评估标准和任务列表跟踪进度
使用任务列表工具或评估标准,确保模型有条理地制定计划,避免遗漏步骤。
有关构建智能体的详细指南和提示词示例,请参阅最新模型的提示词最佳实践 。
为推理模型 和 GPT 模型编写提示词时,请考虑两者的差异。一般来说,只给出总体指导,推理模型往往能取得更好的结果。对于 GPT 模型,精确的指令有助于取得更好的结果。
您可以这样理解推理模型与 GPT 模型的区别:
推理模型就像一位资深同事。您可以告诉它要实现的目标,相信它能自行处理细节。
GPT 模型就像一位经验较少的同事。给出明确的指令,说明具体要产出什么,它的表现会最好。
有关使用推理模型的更多最佳实践,请参阅这份指南 。
了解文本输入和输出的基础知识后,您可以继续探索以下资源。
确保模型输出的 JSON 数据符合指定的 JSON 模式。
如需更多灵感,请访问 OpenAI Cookbook 。其中包含示例代码,以及以下第三方资源的链接: