透過 OpenAI API,你可以讓大型語言模型根據提示詞生成文字,就像使用 ChatGPT 一樣。模型幾乎可以生成任何類型的文字回應,例如程式碼、數學方程式、結構化的 JSON 資料,或讀起來像人寫的文章。
要直接向模型發出請求,請使用 Responses API。以下是生成文字的呼叫範例。
1
2
3
4
5
6
7
8
9import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-6-astra",
input: "Write a one-sentence bedtime story about a unicorn.",
});
console.log(response.output_text);
1
2
3
4
5
6
7
8
9
10from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6-astra",
input="Write a one-sentence bedtime story about a unicorn.",
)
print(response.output_text)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
resp, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say this is a test")},
})
if err != nil {
panic(err.Error())
}
fmt.Println(resp.OutputText())
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
public class Main {
public static void main(String[] args) {
OpenAIClient client = OpenAIOkHttpClient.fromEnv();
ResponseCreateParams params =
ResponseCreateParams.builder().input("Say this is a test").model("gpt-6-astra").build();
Response response = client.responses().create(params);
response.output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(outputText -> System.out.println(outputText.text()));
}
}
1
2
3
4
5
6
7
8
9
10
11
12using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
ResponseResult response = await client.CreateResponseAsync(
"gpt-6-astra",
"Say 'this is a test.'"
);
Console.WriteLine($"[ASSISTANT]: {response.GetOutputText()}");
1
2
3
4
5
6
7
8
9
10require "openai"
openai = OpenAI::Client.new
response = openai.responses.create(
model: "gpt-6-astra",
input: "Write a one-sentence bedtime story about a unicorn."
)
puts(response.output_text)
1
2
3
4
5openai responses create \
--model "gpt-6-astra" \
--input "Write a one-sentence bedtime story about a unicorn." \
--raw-output \
--transform 'output.#(type=="message").content.0.text'
1
2
3
4
5
6
7curl "https://api.openai.com/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-6-astra",
"input": "Write a one-sentence bedtime story about a unicorn."
}'
回應的 output 屬性是一個陣列,包含模型生成的內容。在這個簡單的範例中,陣列只有一個輸出項目,內容如下:
1234567891011121314[
{
"id": "msg_67b73f697ba4819183a15cc17d011509",
"type": "message",
"role": "assistant",
"content": [
{
"type": "output_text",
"text": "Under the soft glow of the moon, Luna the unicorn danced through fields of twinkling stardust, leaving trails of dreams for every child asleep.",
"annotations": []
}
]
}
]
回應中的 output 陣列通常包含多個項目! 其中可能包含工具呼叫、推理模型所生成的推理 Token 相關資料,以及其他項目。請勿假設模型輸出的文字一定位於 output[0].content[0].text。
部分官方 SDK 在模型回應中提供 output_text 屬性,會將模型輸出的所有文字合併成單一字串。你可以透過這個屬性快速取得模型輸出的文字。
除了純文字,你也可以讓模型以 JSON 格式傳回結構化資料。這項功能稱為結構化輸出。
提示工程是指為模型撰寫有效指示,讓模型能穩定生成符合需求的內容。
即使提示詞相同,模型每次生成的內容也可能不同。因此,要寫出能得到預期結果的提示詞,既需要經驗判斷,也需要有系統地實驗。運用適當的技巧和最佳做法,有助於穩定取得良好結果。
有些提示工程技巧適用於所有模型,例如使用訊息角色。不過,要取得最佳結果,可能需要針對不同模型調整提示詞的寫法。即使是同一系列模型的不同快照,也可能產生不同結果。開發較複雜的應用程式時,我們強烈建議採取以下做法:
- 讓正式環境中的應用程式固定使用特定的模型快照(例如
gpt-5.5-2026-04-23),以確保行為一致。
- 建立測試與評估套件,衡量模型在給定提示詞下的表現,以便在反覆調整提示詞或更換、升級模型版本時監控成效。
接下來,看看有哪些工具和技巧可以協助你撰寫提示詞。
OpenAI 提供多種模型和數個 API 供你選擇。推理模型(例如 gpt-6-astra)與對話模型的行為不同,適合的提示詞寫法也不同。搭配 Responses API 使用時,推理模型的表現更好,也能展現更高的智慧。
無論開發哪種文字生成應用程式,我們都建議優先使用 Responses API,而非較舊的 Chat Completions API。如果你使用的是推理模型,遷移至 Responses API 尤其有幫助。
你可以向模型提供不同權限層級的指示,做法是搭配使用 instructions API 參數與訊息角色。
透過 instructions 參數,你可以指定模型生成回應時應遵循的整體原則,例如設定語氣和目標,並提供正確回應的範例。以這種方式提供的指示,優先順序都高於 input 參數中的提示詞。
1
2
3
4
5
6
7
8
9
10
11import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-6-astra",
reasoning: { effort: "low" },
instructions: "Talk like a pirate.",
input: "Are semicolons optional in JavaScript?",
});
console.log(response.output_text);
1
2
3
4
5
6
7
8
9
10
11
12from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6-astra",
reasoning={"effort": "low"},
instructions="Talk like a pirate.",
input="Are semicolons optional in JavaScript?",
)
print(response.output_text)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Instructions: openai.String("Talk like a pirate."),
Reasoning: responses.ReasoningParam{
Effort: responses.ReasoningEffortLow,
},
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("Are semicolons optional in JavaScript?"),
},
})
if err != nil {
panic(err)
}
fmt.Println(response.OutputText())
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.Reasoning;
import com.openai.models.ReasoningEffort;
import com.openai.models.responses.ResponseCreateParams;
String semicolonsDevMsg = "Talk like a pirate.";
String semicolonsPrompt = "Are semicolons optional in JavaScript?";
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input(semicolonsPrompt)
.instructions(semicolonsDevMsg)
.reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())
.build();
client.responses().create(params).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text()));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
CreateResponseOptions options = new()
{
Model = "gpt-6-astra",
Instructions = "Talk like a pirate.",
ReasoningOptions = new ResponseReasoningOptions
{
ReasoningEffortLevel = ResponseReasoningEffortLevel.Low,
},
};
options.InputItems.Add(
ResponseItem.CreateUserMessageItem("Are semicolons optional in JavaScript?")
);
ResponseResult response = await client.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
1
2
3
4
5
6
7
8
9
10
11require "openai"
client = OpenAI::Client.new
response = client.responses.create(
model: "gpt-6-astra",
instructions: "Talk like a pirate.",
reasoning: { effort: :low },
input: "Are semicolons optional in JavaScript?"
)
puts(response.output_text)
1
2
3
4
5
6
7
8
9curl "https://api.openai.com/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-6-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
19import 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
14from 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
37package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Reasoning: responses.ReasoningParam{
Effort: responses.ReasoningEffortLow,
},
Input: responses.ResponseNewParamsInputUnion{
OfInputItemList: responses.ResponseInputParam{
responses.ResponseInputItemParamOfMessage(
"Talk like a pirate.",
responses.EasyInputMessageRoleDeveloper,
),
responses.ResponseInputItemParamOfMessage(
"Are semicolons optional in JavaScript?",
responses.EasyInputMessageRoleUser,
),
},
},
})
if err != nil {
panic(err)
}
fmt.Println(response.OutputText())
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.Reasoning;
import com.openai.models.ReasoningEffort;
import com.openai.models.responses.EasyInputMessage;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputItem;
import java.util.List;
String semicolonsDevMsg = "Talk like a pirate.";
String semicolonsPrompt = "Are semicolons optional in JavaScript?";
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input(
ResponseCreateParams.Input.ofResponse(
List.of(
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.DEVELOPER)
.content(semicolonsDevMsg)
.build()),
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content(semicolonsPrompt)
.build()))))
.reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())
.build();
client.responses().create(params).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text()));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
CreateResponseOptions options = new()
{
Model = "gpt-6-astra",
ReasoningOptions = new ResponseReasoningOptions
{
ReasoningEffortLevel = ResponseReasoningEffortLevel.Low,
},
};
options.InputItems.Add(
ResponseItem.CreateDeveloperMessageItem("Talk like a pirate.")
);
options.InputItems.Add(
ResponseItem.CreateUserMessageItem("Are semicolons optional in JavaScript?")
);
ResponseResult response = await client.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19require "openai"
client = OpenAI::Client.new
response = client.responses.create(
model: "gpt-6-astra",
reasoning: { effort: :low },
input: [
{
role: :developer,
content: "Talk like a pirate."
},
{
role: :user,
content: "Are semicolons optional in JavaScript?"
}
]
)
puts(response.output_text)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17curl "https://api.openai.com/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-6-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 不會出現在當前的上下文中。
你可以參閱 OpenAI 模型規格,瞭解模型如何依照訊息角色決定優先順序。
| developer | user | assistant |
|---|
developer 訊息包含應用程式開發者提供的指示,優先順序高於使用者訊息。
| user 訊息包含終端使用者提供的指示,優先順序低於開發者訊息。
| 模型生成的訊息使用 assistant 角色。 |
多輪對話可以包含多則上述類型的訊息,以及你和模型提供的其他類型內容。進一步瞭解如何管理對話狀態。
你可以把 developer 和 user 訊息想成程式語言中的函式及其引數。
developer 訊息訂定系統規則與業務邏輯,作用類似函式定義。
user 訊息提供輸入與設定,作用類似傳給函式的引數。模型會依照 developer 訊息中的指示處理這些輸入與設定。
請將正式環境使用的提示詞存放在應用程式的程式碼中,而不要建立可重複使用的提示詞物件。在程式碼中管理提示詞,就能運用有型別的輸入、程式碼審查、測試,以及既有的部署流程來調整模型行為。
OpenAI 正逐步棄用 API 中可重複使用的提示詞物件。自 2026 年 6 月 3 日起,建立提示詞物件將不再是主要做法,v1/prompts 預定於 2026 年 11 月 30 日停止服務。最新時程請參閱棄用公告。
開發新的文字生成功能時,請採用以下做法:
- 將建構提示詞的程式碼放在小型模組中,位置靠近使用它的功能。
- 針對客戶資料、檔案或任務選項等動態值,使用有型別的函式引數或結構描述。
- 將產生的
instructions 和 input 直接傳給 Responses API。
- 變更正式環境使用的提示詞前,先加入具代表性的測試資料、測試案例與評估檢查項目。
- 透過部署系統發布提示詞變更。需要分階段發布時,可使用功能旗標或組態設定。
如果現有的整合已透過提示詞 ID 或版本呼叫儲存的提示詞,請依照提示詞物件遷移指南將該提示詞移至程式碼中。
熟悉文字輸入與輸出的基本概念後,你可以透過下列資源進一步探索。
使用 Playground 撰寫並反覆調整提示詞。
確保模型輸出的 JSON 資料符合 JSON 結構描述。