透過 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
從零打造網頁應用程式
GPT-5 只需一個提示詞就能生成前端網頁應用程式,不需要提供範例。以下是一個提示詞範例:
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 模型就像資淺同事。明確指示它產生特定輸出,最能發揮它的能力。
如需進一步了解使用推理模型的最佳實務,請參閱本指南 。
了解文字輸入與輸出的基本概念後,你可以接著參閱以下資源。
使用 Playground 開發並反覆改進提示詞。
確保模型輸出的 JSON 資料符合 JSON 結構描述。
如需更多靈感,請瀏覽 OpenAI Cookbook ,其中收錄了範例程式碼,以及下列第三方資源的連結: