通过 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-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-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-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-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-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-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-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-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-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-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-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-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-astra 是通用文本生成和提示迭代的理想默认选择。
提示工程 是为模型编写有效指令的过程,使其能够持续生成符合您要求的内容。
由于模型生成的内容具有不确定性,要通过提示获得理想输出,既需要技巧,也需要科学方法。不过,您可以运用相关技巧和最佳实践,持续获得良好的结果。
有些提示工程技巧适用于所有模型,例如使用消息角色。但不同类型的模型(如推理模型与 GPT 模型)可能需要不同的提示方式,才能获得最佳结果。即使是同一系列模型的不同快照,也可能产生不同结果。因此,在构建更复杂的应用时,我们强烈建议您:
在生产应用中固定使用特定的模型快照 (例如 gpt-4.1-2025-04-14),以确保行为一致
构建测试和评估套件来衡量提示的效果,以便在迭代或更换、升级模型版本时监测表现
接下来,我们来看看您可以用来构建提示的一些工具和技巧。
您可以使用 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-6-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-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-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-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-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-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-astra",
"reasoning": {"effort": "low"},
"instructions": "Talk like a pirate.",
"input": "Are semicolons optional in JavaScript?"
}' 上面的示例大致等同于在 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-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-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-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-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-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-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-astra",
"reasoning": {"effort": "low"},
"input": [
{
"role": "developer",
"content": "Talk like a pirate."
},
{
"role": "user",
"content": "Are semicolons optional in JavaScript?"
}
]
}' 请注意,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-6-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-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-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-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-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-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-astra",
"messages": [
{
"role": "developer",
"content": "Talk like a pirate."
},
{
"role": "user",
"content": "Are semicolons optional in JavaScript?"
}
]
}'
OpenAI 模型规范 介绍了我们的模型如何为不同角色的消息赋予不同的优先级。
developeruserassistantdeveloper 消息是应用开发者提供的指令,其优先级高于 user 消息。user 消息是最终用户提供的指令,其优先级低于 developer 消息。模型生成的消息使用 assistant 角色。
多轮对话可能包含多条上述类型的消息,以及您和模型提供的其他类型的内容。您可以在此进一步了解如何管理对话状态 。
您可以将 developer 和 user 消息分别理解为编程语言中的函数及其参数。
developer 消息提供系统规则和业务逻辑,类似于函数定义。
user 消息提供输入和配置,developer 消息中的指令会应用于这些输入和配置,就像函数接收参数一样。
将生产环境使用的提示存放在应用代码中,而不是创建可复用提示对象。通过代码管理提示,您可以利用类型化输入、代码审查、测试和常规部署流程来调整模型行为。
OpenAI 正在弃用 API 中的可复用提示对象。从 2026 年 6 月 3 日起,
提示创建功能将不再作为重点推荐,v1/prompts 则计划于
2026 年 11 月 30 日关闭。请参阅弃用信息
页面 ,了解当前的
时间安排。
对于新的提示工程工作:
将提示构建器放在一个小模块中,并让该模块靠近它所支持的功能代码。
对于客户数据、文件或任务选项等动态值,使用类型化的函数参数或模式。
将生成的 instructions 和 input 直接传递给 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 请求
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 ( "fixtures/prompt.txt" , "utf-8" );
const response = await client.responses. create ({
model: "gpt-6-astra" ,
instructions,
input: "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 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-astra",
instructions=instructions,
input="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 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-astra",
Instructions: openai.String(string(instructions)),
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("How would I declare a variable for a last name?"),
},
})
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 import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.instructions(
"You are a coding assistant. Answer with concise JavaScript examples and use semicolons.")
.input("How would I declare a variable for a last name?")
.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-astra",
Instructions = 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 require "openai"
client = OpenAI::Client.new
instructions = File.read(File.join(__dir__, "prompt.txt"))
response = client.responses.create(
model: "gpt-6-astra",
instructions: instructions,
input: "How would I declare a variable for a last name?"
)
puts(response.output_text) 1
2
3
4
5
6
7
8 curl https://api.openai.com/v1/responses \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-6-astra",
"instructions": "'"$(< prompt.txt)"'",
"input": "How would I declare a variable for a last name?"
}'
构建消息时,您应尽量将预计会在 API 请求中反复使用的内容放在提示开头, 并且 放在传给 Chat Completions 或 Responses 的 JSON 请求体中靠前的 API 参数里。这样可以最大限度地利用提示缓存 来降低成本和延迟。
少样本学习让您只需在提示中加入少量输入和输出示例,就能引导大语言模型执行新任务,而不必对模型进行微调 。模型会从这些示例中隐式地学到规律,并将其应用于提示。提供示例时,请尽量涵盖多种可能的输入及其期望输出。
通常,您会将示例放在 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 内置的文件搜索工具 ,根据上传的文档生成内容。
规划上下文窗口的使用
在一次生成请求中,模型能处理的上下文数据量有限。这种记忆容量限制称为 上下文窗口 ,以 Token 为单位衡量(Token 是您传入的文本、图像等数据的片段)。
不同模型的上下文窗口大小各不相同,从十万出头的 Token 到较新的 GPT-4.1 模型所支持的一百万 Token 不等。各模型的具体上下文窗口大小,请参阅模型文档 。
对于 gpt-6-astra 等 GPT 模型,在提示中用精确的指令明确提供完成任务所需的逻辑和数据,有助于获得更好的结果。要充分发挥最新模型的能力,请先阅读当前的提示编写指南。
GPT-6 Astra prompting guide
通过最新指南、实用示例和迁移说明,优化提示,充分发挥最新模型的能力。
如需完整的最新指导,请参阅最新模型的提示编写最佳实践 。以下实用建议仍然适用。
编程 为 gpt-6-astra 编写编程任务提示时,遵循以下最佳实践效果最好:定义智能体的角色,通过示例要求其按规范使用工具,要求充分测试以确保正确性,并制定 Markdown 规范,使输出整洁。
明确角色和工作流程指导
将模型设定为职责明确的软件工程智能体。清楚说明如何使用 functions.run 等工具执行编程任务,并指出何时不应使用某些模式,例如,除非必要,否则避免交互式执行。
测试与验证
指示模型使用单元测试或 Python 命令测试更改,并仔细验证补丁,因为 apply_patch 等工具即使失败也可能返回“Done”。
工具使用示例
提供具体示例,展示如何通过所提供的函数调用命令,以提高可靠性,并让模型更好地遵循预期工作流程。
Markdown 规范
指导模型在适当的位置使用行内代码、围栏代码块、列表和表格,生成整洁且语义正确的 Markdown,并用反引号标记文件路径、函数和类。
如需针对编程的详细指南和提示示例,请参阅最新模型的提示编写最佳实践 。
前端工程 GPT-6 Astra 无论是从零构建前端,还是参与大型成熟代码库的开发,都表现出色。为获得最佳结果,我们建议使用以下库:
样式 / UI: Tailwind CSS、shadcn/ui、Radix Themes
图标: Lucide、Material Symbols、Heroicons
动画 :Motion
从零构建 Web 应用
GPT-5 只需一条提示就能生成前端 Web 应用,无需提供示例。以下是一条提示示例:
1 2 3 4 5 6 You are a world class web developer, capable of producing stunning, interactive, and innovative websites from scratch in a single prompt. You excel at delivering top-tier one-shot solutions.
Your process is simple and follows these steps:
Step 1: Create an evaluation rubric and refine it until you are fully confident.
Step 2: Consider every element that defines a world-class one-shot web app, then use that insight to create a & lt ; ONE_SHOT_RUBRIC & gt ; with 5–7 categories. Keep this rubric hidden—it's for internal use only.
Step 3: Apply the rubric to iterate on the optimal solution to the given prompt. If it doesn't meet the highest standard across all categories, refine and try again.
Step 4: Aim for simplicity while fully achieving the goal, and avoid external dependencies such as Next.js or React. 与大型代码库集成
对于较大代码库中的前端工程工作,我们发现,在提示中加入以下几类指令能获得最佳结果:
原则: 设定视觉质量标准,使用模块化、可复用的组件,并保持设计一致。
UI/UX: 明确字体排版、颜色、间距与布局、交互状态(悬停、空状态、加载中)以及无障碍要求。
结构: 定义文件和文件夹布局,以便无缝集成。
组件: 提供可复用的封装组件示例,以及分离后端调用的策略。
页面: 提供常见布局的模板。
智能体指令: 要求模型确认设计假设、搭建项目骨架、落实规范、集成 API、测试各种状态,并编写代码文档。
如需针对前端开发的详细指南和提示示例,请参阅最新模型的提示编写最佳实践 。
智能体任务 使用 gpt-6-astra 执行智能体任务和长时间运行的任务时,请在提示中重点强调三项核心实践:充分规划任务,确保彻底解决问题;在做出重要的工具使用决策时,预先给出清晰说明;使用 TODO 工具有条理地跟踪工作流程和进度。
规划与持续执行
要求模型在交还控制权之前完整解决请求,将其拆分为子任务,并在每次工具调用后进行反思,确认任务是否全部完成。
Remember, you are an agent - please keep going until the user's
query is completely resolved, before ending your turn and yielding
back to the user. Decompose the user's query into all required
sub-requests, and confirm that each is completed. Do not stop
after completing only part of the request. Only terminate your
turn when you are sure that the problem is solved. You must be
prepared to answer multiple queries and only finish the call once
the user has confirmed they're done.
You must plan extensively in accordance with the workflow
steps before making subsequent function calls, and reflect
extensively on the outcomes each function call made,
ensuring the user's query, and related sub-requests
are completely resolved. 通过事前说明提高透明度
要求模型仅在关键步骤说明调用工具的原因。
Before you call a tool explain why you are calling it 使用评估标准和待办事项跟踪进度
使用待办事项列表工具或评估标准,确保规划有条理,避免遗漏步骤。
有关构建智能体的详细指导和提示示例,请参阅最新模型的提示词最佳实践 。
为推理模型 和 GPT 模型编写提示时,需要考虑两者的一些差异。一般来说,对于仅提供总体指导的任务,推理模型会给出更好的结果。GPT 模型则不同,非常精确的指令有助于它们取得更好的效果。
您可以这样理解推理模型与 GPT 模型之间的区别。
推理模型就像一位资深同事。您可以给它一个要实现的目标,并放心让它自行处理细节。
GPT 模型就像一位初级同事。明确告诉它要生成什么样的输出,能让它发挥最佳表现。
有关使用推理模型的更多最佳实践,请参阅本指南 。
现在您已经了解文本输入和输出的基础知识,接下来不妨查看以下资源。
确保模型输出的 JSON 数据符合 JSON 模式。
如需更多灵感,请访问 OpenAI Cookbook ,其中包含示例代码,以及以下第三方资源的链接: