透過 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),以確保行為一致。
建立測試與評估套件,衡量模型對提示詞的反應,以便在調整提示詞、更換或升級模型版本時監控表現。
接下來介紹幾種可用來撰寫提示詞的工具與技巧。
你可以透過 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-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 模型規格 說明模型如何依據角色決定訊息的優先順序。
developer
user
assistant
developer 訊息包含開發者提供的指示,優先順序高於 user 訊息。
user 訊息包含終端使用者提供的指示,優先順序低於 developer 訊息。
模型生成的訊息使用 assistant 角色。
多輪對話可以包含數則上述類型的訊息,以及你和模型提供的其他類型內容。進一步瞭解如何管理對話狀態 。
你可以把 developer 和 user 訊息的關係想成程式語言中函式與引數的關係。
developer 訊息提供系統規則與業務邏輯,就像函式定義。
user 訊息提供輸入與設定,就像傳給函式的引數。模型會將 developer 訊息中的指示套用到這些輸入與設定。
請直接將正式環境使用的提示詞存放在應用程式碼中,無須另外建立可重複使用的提示詞物件。在程式碼中管理提示詞,就能透過具型別的輸入、程式碼審查、測試及既有的部署流程來調整模型行為。
OpenAI 正逐步棄用 API 中可重複使用的提示詞物件。自 2026 年 6 月 3 日起,OpenAI 將不再著重推廣建立提示詞物件的做法,v1/prompts 預計於 2026 年 11 月 30 日停止服務。最新時程請見棄用公告 。
開始新的提示工程工作時,建議採取以下做法:
將建構提示詞的程式碼集中在小型模組中,放在所支援功能的程式碼附近。
使用具型別的函式引數或結構描述來定義動態值,例如客戶資料、檔案或任務選項。
將產生的 instructions 和 input 直接傳給 Responses API 。
變更正式環境的提示詞前,先加入具代表性的測試資料、測試及評估檢查。
透過部署系統推出提示詞變更。需要分階段發布時,可使用功能旗標或組態設定。
如果現有整合已透過提示詞 ID 或版本呼叫儲存的提示詞,請依照提示詞物件遷移指南 ,將該提示詞移至程式碼中。
撰寫 developer 和 user 訊息時,可以搭配使用 Markdown 格式與 XML 標籤 ,幫助模型辨識提示詞和上下文資料中各部分的界線。
Markdown 標題和清單有助於區分提示詞的各個區段,讓模型理解內容的層級關係,也能讓開發者更容易閱讀提示詞。XML 標籤可以標示一段內容的起點與終點,例如一份供模型參考的文件。你也可以使用 XML 屬性為提示詞中的內容定義中繼資料,供指示引用。
開發者訊息通常依照以下順序安排各個區段,但最合適的內容與順序可能因模型而異:
身分: 說明助理的用途、溝通風格及整體目標。
指示: 說明模型該如何生成你想要的回應。模型應遵循哪些規則?該做哪些事?哪些事絕對不能做?你可以視使用情境在此加入多個小節,例如說明模型該如何呼叫自訂函式 。
範例: 提供可能的輸入範例,以及你希望模型針對各項輸入產生的輸出。
上下文: 提供模型生成回應時可能需要的補充資訊,例如訓練資料未涵蓋的私人或專有資料,或其他你知道與任務特別相關的資料。不同的生成請求可能需要不同的上下文,因此這類內容通常最適合放在提示詞接近結尾處。
以下範例使用 Markdown 和 XML 標籤撰寫 developer 訊息,將內容分成不同區段,並附上相關範例。
Example prompt API request 提示詞範例
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 訊息透過範例示範如何判斷客服評論是正面還是負面。
# 身分
你是一位樂於助人的助理,負責將簡短的產品評論標記為 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 起,較新的 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 擅長從零開始建構前端,也能在既有的大型程式碼庫中開發功能。為取得最佳結果,建議使用以下程式庫:
樣式與使用者介面: Tailwind CSS、shadcn/ui、Radix Themes
圖示: Lucide、Material Symbols、Heroicons
動畫 :Motion
從零開始建構 Web 應用程式
GPT-5 只需一個提示詞就能生成前端 Web 應用程式,不需要提供範例。以下是提示詞範例:
1 2 3 4 5 6 你是世界一流的網站開發者,只需一個提示詞,就能從零開始打造視覺出色、可互動且富有創意的網站。你擅長一次就交付高品質的解決方案。
請依照以下步驟進行:
步驟 1:擬定一套評估準則,反覆修訂,直到你對這套準則有充分信心。
步驟 2:想想要憑一個提示詞做出一流的 Web 應用程式,必須兼顧哪些要素。據此建立一份包含 5 至 7 個類別的 & lt ; ONE_SHOT_RUBRIC & gt ; 。這套準則僅供內部使用,請勿對外顯示。
步驟 3:根據這套準則反覆改進方案,找出最符合提示詞要求的做法。只要有任何一個類別未達最高標準,就繼續改進並重新評估。
步驟 4:在完整達成目標的前提下,盡量讓方案保持簡單,並避免使用 Next.js 或 React 等外部相依套件。 與大型程式碼庫整合
我們發現,在較大型的程式碼庫中進行前端開發時,於提示詞中加入下列幾類指示,效果最好:
原則: 訂定視覺品質標準,使用模組化、可重複使用的元件,並保持設計一致。
UI/UX: 指定字體排印、配色、間距與版面配置、互動狀態(如滑鼠懸停、無內容及載入中),以及無障礙要求。
結構: 定義檔案與資料夾的配置,方便整合至現有專案。
元件: 提供可重複使用的包裝元件範例,並說明如何將後端呼叫邏輯獨立出來。
頁面: 為常見的版面配置提供範本。
智慧體指示: 要求模型確認設計假設、建立專案骨架、落實規範、整合 API、測試各種狀態,並為程式碼撰寫文件。
如需前端開發的詳細指引與提示詞範例,請參閱最新模型的提示詞最佳做法 。
智慧體任務 使用 gpt-6-astra 執行智慧體任務或需長時間執行的任務時,請要求模型從頭到尾規劃整項工作,在進行重要的工具呼叫前先說明原因,並使用任務清單工具追蹤進度。
規劃並持續執行任務
指示模型將使用者的請求拆成子任務,每次呼叫工具後都檢視結果,逐項確認完成情況。模型應在整個請求都處理完畢後才將控制權交還給使用者。
請記住,你是智慧體。請持續處理使用者的請求,直到整個請求都處理完畢,才結束這一輪回應並將控制權交還給使用者。將請求拆成所有必要的子任務,逐一確認是否完成。不要只完成一部分就停下來。只有在確定問題已解決後,才能結束這一輪回應。你必須準備好回答多個問題,並等到使用者確認沒有其他問題後,才能結束這次互動。
每次呼叫下一個函式前,都必須依照工作流程的步驟詳加規劃。每次呼叫函式後,都要仔細檢視結果,確保使用者的請求和相關子任務都已處理完畢。 事先說明工具用途,讓過程更透明
要求模型在呼叫工具前說明原因,但只需在重要步驟提供這類說明。
呼叫工具前,先說明為什麼要呼叫這項工具。 使用評估準則與任務清單追蹤進度
使用任務清單工具或評估準則,要求模型有條理地規劃任務,避免遺漏步驟。
如需建構智慧體的詳細指引與提示詞範例,請參閱最新模型的提示詞最佳做法 。
為推理模型 和 GPT 模型撰寫提示詞時,請考量兩者的差異。一般而言,只提供整體方向,推理模型就能在任務中取得較好的結果。GPT 模型則在收到精確的指示時表現更好。
你可以用以下比喻來理解推理模型與 GPT 模型的差異。
推理模型就像資深同事。你可以交代要達成的目標,放心讓對方自行處理細節。
GPT 模型就像資歷較淺的同事。明確說明如何產出指定的成果,對方就能有最好的表現。
如需進一步瞭解使用推理模型的最佳做法,請參閱這份指南 。
掌握文字輸入與輸出的基礎後,可以接著探索以下資源。
使用 Playground 開發並反覆調整提示詞。
確保模型輸出的 JSON 資料符合指定的 JSON 結構描述。
如需更多靈感,請瀏覽 OpenAI Cookbook 。其中收錄了程式碼範例,也提供以下第三方資源的連結: