Responses API 是我們全新的 API 基礎介面,由 Chat Completions 演進而來,讓整合更簡單,並提供強大的智慧體基礎功能。
我們仍持續支援 Chat Completions,但建議所有新專案使用 Responses。
Responses API 提供統一介面,可用來建構具備智慧體能力的強大應用程式。它包含:
相較於 Chat Completions,Responses API 具備多項優勢:
表現更好 :使用 GPT-5 等推理模型時,搭配 Responses 能比搭配 Chat Completions 發揮更高的模型智慧。我們的內部評估顯示,在使用相同提示詞與設定的情況下,SWE-bench 表現提升了 3%。
預設具備智慧體能力 :Responses API 透過智慧體迴圈,讓模型在單次 API 請求中呼叫多項工具,例如 web_search、image_generation、file_search、code_interpreter、遠端 MCP 伺服器,以及你自己的自訂函式。
成本更低 :提高快取利用率,進而降低成本(內部測試顯示,快取利用率比 Chat Completions 提升 40% 至 80%)。
保留上下文狀態 :使用 store: true 在各輪互動之間維持狀態,保留推理與工具的上下文。
靈活的輸入方式 :透過 input 傳入字串或訊息清單;使用 instructions 提供系統層級的指引。
加密推理 :即使選擇不保留狀態,仍可享有進階推理的優勢。
為未來做好準備 :已為即將推出的模型做好準備。
能力 Chat Completions API Responses API 文字生成 音訊 即將推出 視覺 結構化輸出 函式呼叫 網頁搜尋 檔案搜尋 電腦 程式碼解譯器 MCP 圖像生成 推理摘要
查看 Responses API 與 Chat Completions API 在特定情境下的差異。
這兩個 API 都能讓你輕鬆透過我們的模型生成輸出。呼叫 Chat Completions 時,輸入與傳回結果都是 訊息 陣列,
而 Responses API 使用的是 項目 。項目是多種類型的聯集,代表模型可能執行的各種動作。
message 是一種項目類型,function_call 和 function_call_output 也是。Chat Completions 的訊息會將多種用途的內容整合在同一個物件中,
項目則彼此獨立,更能代表模型上下文的基本單位。
此外,Chat Completions 可使用 n 參數,以 choices 傳回多個平行生成的結果。在 Responses 中,我們已移除此參數,每次只會生成一個結果。
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-6-astra" ,
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 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 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 require "openai"
client = OpenAI::Client.new
response = client.responses.create(
model: "gpt-6-astra",
input: "Write a one-sentence bedtime story about a unicorn."
)
puts(response.output_text)
Responses API 傳回的回應欄位略有不同。
你收到的是具有明確類型及自身 id 的 response 物件,而非 message。
Responses 預設會儲存回應。對於新帳戶,Chat Completions 也預設會儲存回應。
使用任一 API 時,若要停用儲存功能,請設定 store: false。
這兩個 API 傳回的物件略有不同。在 Chat Completions 中,你會收到
choices 陣列,每個元素都包含一個 message。在 Responses 中,你會收到標示為 output 的項目陣列。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 {
"id" : "chatcmpl-C9EDpkjH60VPPIB86j2zIhiR8kWiC" ,
"object" : "chat.completion" ,
"created" : 1756315657 ,
"model" : "gpt-5.5" ,
"choices" : [
{
"index" : 0 ,
"message" : {
"role" : "assistant" ,
"content" : "Under a blanket of starlight, a sleepy unicorn tiptoed through moonlit meadows, gathering dreams like dew to tuck beneath its silver mane until morning." ,
"refusal" : null ,
"annotations" : []
},
"finish_reason" : "stop"
}
],
...
} 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 {
"id" : "resp_68af4030592c81938ec0a5fbab4a3e9f05438e46b5f69a3b" ,
"object" : "response" ,
"created_at" : 1756315696 ,
"model" : "gpt-5.5" ,
"output" : [
{
"id" : "rs_68af4030baa48193b0b43b4c2a176a1a05438e46b5f69a3b" ,
"type" : "reasoning" ,
"content" : [],
"summary" : []
},
{
"id" : "msg_68af40337e58819392e935fb404414d005438e46b5f69a3b" ,
"type" : "message" ,
"status" : "completed" ,
"content" : [
{
"type" : "output_text" ,
"annotations" : [],
"logprobs" : [],
"text" : "Under a quilt of moonlight, a drowsy unicorn wandered through quiet meadows, brushing blossoms with her glowing horn so they sighed soft lullabies that carried every dreamer gently to sleep."
}
],
"role" : "assistant"
}
],
...
}
Responses 預設會儲存回應。對於新帳戶,Chat Completions 也預設會儲存回應。若要在任一 API 中停用儲存功能,請設定 store: false。
Responses API 改善了工具使用能力 ,為推理 模型提供更完整的使用體驗。從 GPT-5.4 開始,當 reasoning_effort 的值不是 none 時,Chat Completions 不支援工具呼叫。
結構化輸出的 API 結構有所不同。在 Responses 中,請使用 text.format 取代 response_format。如需詳細資訊,請參閱結構化輸出 指南。
函式呼叫的 API 結構有所不同,包括請求中的函式設定,以及回應中傳回的函式呼叫。如需完整的差異說明,請參閱函式呼叫指南 。
Responses SDK 提供 output_text 輔助功能,Chat Completions SDK 則沒有。
在 Chat Completions 中,你必須手動管理對話狀態。Responses API 可搭配 Conversations API 持續保存對話,也能透過傳入 previous_response_id 輕鬆串接多個回應。
遷移包含三項相關變更:將請求傳送至 /v1/responses、從具有明確類型的 output 陣列讀取輸出,以及決定應用程式如何在各輪互動之間延續狀態。
首先,將生成端點從 post /v1/chat/completions 更新為 post /v1/responses。
如果你未使用函式或多模態輸入,簡單的訊息輸入可在這兩個 API 之間通用:
1
2
3
4
5
6
7
8
9
10
11
12
13
14 const context = [
{ role: "system" , content: "You are a helpful assistant." },
{ role: "user" , content: "Hello!" },
];
const completion = await client.chat.completions. create ({
model: "gpt-6-astra" ,
messages: context,
});
const response = await client.responses. create ({
model: "gpt-6-astra" ,
input: context,
}); 1
2
3
4
5
6
7
8 context = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"},
]
completion = client.chat.completions.create(model="gpt-6-astra", messages=context)
response = client.responses.create(model="gpt-6-astra", input=context) 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()
completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{
Model: "gpt-6-astra",
Messages: []openai.ChatCompletionMessageParamUnion{
openai.SystemMessage("You are a helpful assistant."),
openai.UserMessage("Hello!"),
},
})
if err != nil {
panic(err)
}
fmt.Println(completion.Choices[0].Message.Content)
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{
responses.ResponseInputItemParamOfMessage("You are a helpful assistant.", responses.EasyInputMessageRoleSystem),
responses.ResponseInputItemParamOfMessage("Hello!", 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
38
39
40
41
42
43
44
45
46 import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import com.openai.models.responses.EasyInputMessage;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputItem;
import java.util.List;
var completion =
client
.chat()
.completions()
.create(
ChatCompletionCreateParams.builder()
.model("gpt-6-astra")
.addSystemMessage("You are a helpful assistant.")
.addUserMessage("Hello!")
.build());
completion.choices().stream()
.flatMap(choice -> choice.message().content().stream())
.forEach(System.out::println);
var response =
client
.responses()
.create(
ResponseCreateParams.builder()
.model("gpt-6-astra")
.inputOfResponse(
List.of(
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.SYSTEM)
.content("You are a helpful assistant.")
.build()),
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content("Hello!")
.build())))
.build());
response.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
25
26
27 using OpenAI.Chat;
using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "gpt-6-astra";
ChatClient chat = new(model, key);
ChatCompletion completion = await chat.CompleteChatAsync(
[
new SystemChatMessage("You are a helpful assistant."),
new UserChatMessage("Hello!"),
]
);
Console.WriteLine(completion.Content[0].Text);
ResponsesClient responses = new(key);
ResponseResult response = await responses.CreateResponseAsync(
model,
[
ResponseItem.CreateSystemMessageItem("You are a helpful assistant."),
ResponseItem.CreateUserMessageItem("Hello!"),
]
);
Console.WriteLine(response.GetOutputText()); 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 require "openai"
client = OpenAI::Client.new
messages = [
{
role: :system,
content: "You are a helpful assistant."
},
{
role: :user,
content: "Hello!"
}
]
completion = client.chat.completions.create(
model: "gpt-6-astra",
messages: messages
)
puts(completion.choices.fetch(0).message.content)
response = client.responses.create(
model: "gpt-6-astra",
input: messages
)
puts(response.output_text) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 INPUT='[
{ "role": "system", "content": "You are a helpful assistant." },
{ "role": "user", "content": "Hello!" }
]'
curl -s https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d "{
\"model\": \"gpt-6-astra\",
\"messages\": $INPUT
}"
curl -s https://api.openai.com/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d "{
\"model\": \"gpt-6-astra\",
\"input\": $INPUT
}"
Chat Completions Responses
Chat Completions
使用 Chat Completions 時,你需要建立
messages 陣列,
並從
completion.choices[0].message.content 讀取模型產生的文字。
1
2
3
4
5
6
7
8
9
10
11 import OpenAI from "openai" ;
const client = new OpenAI ({ apiKey: process.env. OPENAI_API_KEY });
const completion = await client.chat.completions. create ({
model: "gpt-6-astra" ,
messages: [
{ role: "system" , content: "You are a helpful assistant." },
{ role: "user" , content: "Hello!" },
],
});
console. log (completion.choices[ 0 ].message.content); 1
2
3
4
5
6
7
8
9
10
11
12 from openai import OpenAI
client = OpenAI()
completion = client.chat.completions.create(
model="gpt-6-astra",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"},
],
)
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 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.SystemMessage("You are a helpful assistant."),
openai.UserMessage("Hello!"),
},
})
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 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")
.addSystemMessage("You are a helpful assistant.")
.addUserMessage("Hello!")
.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 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 SystemChatMessage("You are a helpful assistant."),
new UserChatMessage("Hello!"),
]
);
Console.WriteLine(completion.Content[0].Text); 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
completion = client.chat.completions.create(
model: "gpt-6-astra",
messages: [
{
role: :system,
content: "You are a helpful assistant."
},
{
role: :user,
content: "Hello!"
}
]
)
puts(completion.choices.fetch(0).message.content) 1
2
3
4
5
6
7
8
9
10 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": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
]
}'
Responses
使用 Responses 時,你可以在最上層分別設定
instructions 和
input,
並從
response.output_text 讀取生成的文字。
1
2
3
4
5
6
7
8
9
10 import OpenAI from "openai" ;
const client = new OpenAI ({ apiKey: process.env. OPENAI_API_KEY });
const response = await client.responses. create ({
model: "gpt-6-astra" ,
instructions: "You are a helpful assistant." ,
input: "Hello!" ,
});
console. log (response.output_text); 1
2
3
4
5
6
7
8 from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6-astra", instructions="You are a helpful assistant.", input="Hello!"
)
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()
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Instructions: openai.String("You are a helpful assistant."),
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Hello!")},
})
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 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")
.input("Hello!")
.instructions("You are a helpful assistant.")
.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 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 = "You are a helpful assistant.",
};
options.InputItems.Add(ResponseItem.CreateUserMessageItem("Hello!"));
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: "You are a helpful assistant.",
input: "Hello!"
)
puts(response.output_text) 1
2
3
4
5
6
7
8 curl https://api.openai.com/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-6-astra",
"instructions": "You are a helpful assistant.",
"input": "Hello!"
}'
Chat Completions 的輸入和輸出皆使用 messages。Responses 則使用 input 和 output 陣列,其中包含具有明確類型的項目。message 是其中一種項目類型,其他類型包括 reasoning、function_call 和 function_call_output。
Chat Completions 概念 Responses 對應方式 messages[]input,可以是字串或輸入項目陣列系統或開發人員指示 最上層的 instructions;若需保留既有對話紀錄,也可使用相容的訊息項目 使用者訊息 帶有 role: "user" 的輸入訊息項目 助理訊息 response.output 中的輸出訊息項目;若自行管理狀態,請將該項目放入 input 傳回工具或函式呼叫 function_call 輸出項目工具或函式結果 function_call_output 輸入項目,透過 call_id 與呼叫建立關聯使用 n 生成多個結果 Responses 不支援此功能;若需要多個候選輸出,請分別傳送請求
若只需要最終文字,請使用 SDK 的 output_text 輔助功能。若工作流程涉及推理、工具或多模態輸出,請逐一走訪 response.output,並依各項目的 type 進行處理。
如果你的應用程式有多輪對話,請更新上下文處理邏輯。Responses 提供三種常見的狀態管理方式:
若希望由 OpenAI 管理先前回應的上下文,請使用 previous_response_id。每次請求都要重新傳送固定的 instructions,因為 previous_response_id 不會沿用上一個回應最上層的 instructions。
若需自行管理或刪減上下文,請在下一次請求中傳回先前的 output 項目。
若需要持續保存的對話物件,請使用 Conversations API 。
Chat Completions Responses
Chat Completions
使用 Chat Completions 時,你需要儲存對話紀錄,並在每次請求中傳送累積的
messages 陣列。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 let messages = [
{ role: "system" , content: "You are a helpful assistant." },
{ role: "user" , content: "What is the capital of France?" },
];
const res1 = await client.chat.completions. create ({
model: "gpt-6-astra" ,
messages,
});
messages = messages. concat ([res1.choices[ 0 ].message]);
messages. push ({ role: "user" , content: "And its population?" });
const res2 = await client.chat.completions. create ({
model: "gpt-6-astra" ,
messages,
}); 1
2
3
4
5
6
7
8
9
10 messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is the capital of France?"},
]
res1 = client.chat.completions.create(model="gpt-6-astra", messages=messages)
messages += [res1.choices[0].message]
messages += [{"role": "user", "content": "And its population?"}]
res2 = client.chat.completions.create(model="gpt-6-astra", messages=messages) 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 package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
)
func main() {
client := openai.NewClient()
messages := []openai.ChatCompletionMessageParamUnion{
openai.SystemMessage("You are a helpful assistant."),
openai.UserMessage("What is the capital of France?"),
}
first, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{Model: "gpt-6-astra", Messages: messages})
if err != nil {
panic(err)
}
messages = append(messages, openai.AssistantMessage(first.Choices[0].Message.Content), openai.UserMessage("And its population?"))
second, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{Model: "gpt-6-astra", Messages: messages})
if err != nil {
panic(err)
}
fmt.Println(second.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 import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
var params =
ChatCompletionCreateParams.builder()
.model("gpt-6-astra")
.addSystemMessage("You are a helpful assistant.")
.addUserMessage("What is the capital of France?")
.build();
var first = client.chat().completions().create(params);
var second =
client
.chat()
.completions()
.create(
params.toBuilder()
.addAssistantMessage(first.choices().get(0).message().content().orElseThrow())
.addUserMessage("And its population?")
.build());
second.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
16
17
18 using OpenAI.Chat;
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "gpt-6-astra";
ChatClient client = new(model, key);
List<ChatMessage> messages =
[
new SystemChatMessage("You are a helpful assistant."),
new UserChatMessage("What is the capital of France?"),
];
ChatCompletion first = await client.CompleteChatAsync(messages);
messages.Add(new AssistantChatMessage(first));
messages.Add(new UserChatMessage("And its population?"));
ChatCompletion second = await client.CompleteChatAsync(messages);
Console.WriteLine(second.Content[0].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 require "openai"
client = OpenAI::Client.new
messages = [
{
role: :system,
content: "You are a helpful assistant."
},
{
role: :user,
content: "What is the capital of France?"
}
]
first = client.chat.completions.create(
model: "gpt-6-astra",
messages: messages
)
messages << {
role: :assistant,
content: first.choices.fetch(0).message.content
}
messages << {
role: :user,
content: "And its population?"
}
second = client.chat.completions.create(
model: "gpt-6-astra",
messages: messages
)
puts(second.choices.fetch(0).message.content)
Responses
使用 Responses 時,你可以手動將一個回應的輸出
作為另一個回應的輸入。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 import { toResponseInputItems } from "openai/lib/responses/ResponseInputItems" ;
let context = [{ role: "user" , content: "What is the capital of France?" }];
const res1 = await client.responses. create ({
model: "gpt-6-astra" ,
input: context,
});
// Append the first response’s output to context
context = context. concat ( toResponseInputItems (res1.output));
// Add the next user message
context. push ({ role: "user" , content: "And its population?" });
const res2 = await client.responses. create ({
model: "gpt-6-astra" ,
input: context,
}); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 context = [{"role": "user", "content": "What is the capital of France?"}]
res1 = client.responses.create(
model="gpt-6-astra",
input=context,
)
# Append the first response's output to context
context += res1.output
# Add the next user message
context += [{"role": "user", "content": "And its population?"}]
res2 = client.responses.create(
model="gpt-6-astra",
input=context,
) 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
38
39
40
41
42
43
44
45
46 package main
import (
"context"
"encoding/json"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
contextItems := responses.ResponseInputParam{
responses.ResponseInputItemParamOfMessage("What is the capital of France?", responses.EasyInputMessageRoleUser),
}
first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{OfInputItemList: contextItems},
})
if err != nil {
panic(err)
}
contextItems = append(contextItems, outputAsInput(first.Output)...)
contextItems = append(contextItems, responses.ResponseInputItemParamOfMessage("And its population?", responses.EasyInputMessageRoleUser))
second, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{OfInputItemList: contextItems},
})
if err != nil {
panic(err)
}
fmt.Println(second.OutputText())
}
func outputAsInput(output []responses.ResponseOutputItemUnion) []responses.ResponseInputItemUnionParam {
input := make([]responses.ResponseInputItemUnionParam, 0, len(output))
for _, item := range output {
var converted responses.ResponseInputItemUnion
if err := json.Unmarshal([]byte(item.RawJSON()), &converted); err != nil {
panic(err)
}
input = append(input, converted.ToParam())
}
return input
} 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
38
39
40 import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.EasyInputMessage;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputItem;
import java.util.ArrayList;
var history = new ArrayList<ResponseInputItem>();
history.add(
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content("What is the capital of France?")
.build()));
var first =
client
.responses()
.create(
ResponseCreateParams.builder().model("gpt-6-astra").inputOfResponse(history).build());
first.output().stream()
.map(item -> JsonValue.from(item).convert(ResponseInputItem.class))
.forEach(history::add);
history.add(
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content("And its population?")
.build()));
client
.responses()
.create(ResponseCreateParams.builder().model("gpt-6-astra").inputOfResponse(history).build())
.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 using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
List<ResponseItem> history =
[
ResponseItem.CreateUserMessageItem("What is the capital of France?"),
];
ResponseResult first = await client.CreateResponseAsync("gpt-6-astra", history);
history.AddRange(first.OutputItems);
history.Add(ResponseItem.CreateUserMessageItem("And its population?"));
ResponseResult second = await client.CreateResponseAsync("gpt-6-astra", history);
Console.WriteLine(second.GetOutputText()); 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 require "openai"
client = OpenAI::Client.new
context = [
{
role: :user,
content: "What is the capital of France?"
}
]
first = client.responses.create(
model: "gpt-6-astra",
input: context
)
context.concat(first.output)
context << {
role: :user,
content: "And its population?"
}
second = client.responses.create(
model: "gpt-6-astra",
input: context
)
puts(second.output_text) 你也可以使用 previous_response_id 參照上一個回應,
建立回應鏈或分支。
1
2
3
4
5
6
7
8
9
10
11
12 const res1 = await client.responses. create ({
model: "gpt-6-astra" ,
input: "What is the capital of France?" ,
store: true ,
});
const res2 = await client.responses. create ({
model: "gpt-6-astra" ,
input: "And its population?" ,
previous_response_id: res1.id,
store: true ,
}); 1
2
3
4
5
6
7
8
9
10 res1 = client.responses.create(
model="gpt-6-astra", input="What is the capital of France?", store=True
)
res2 = client.responses.create(
model="gpt-6-astra",
input="And its population?",
previous_response_id=res1.id,
store=True,
) 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 package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Store: openai.Bool(true),
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What is the capital of France?")},
})
if err != nil {
panic(err)
}
second, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Store: openai.Bool(true),
PreviousResponseID: openai.String(first.ID),
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("And its population?")},
})
if err != nil {
panic(err)
}
fmt.Println(second.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 import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
var first =
client
.responses()
.create(
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("What is the capital of France?")
.store(true)
.build());
var second =
client
.responses()
.create(
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("And its population?")
.previousResponseId(first.id())
.store(true)
.build());
second.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 using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
ResponseResult first = await client.CreateResponseAsync(
"gpt-6-astra",
"What is the capital of France?"
);
ResponseResult second = await client.CreateResponseAsync(
"gpt-6-astra",
"And its population?",
previousResponseId: first.Id
);
Console.WriteLine(second.GetOutputText()); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 require "openai"
client = OpenAI::Client.new
first = client.responses.create(
model: "gpt-6-astra",
input: "What is the capital of France?",
store: true
)
second = client.responses.create(
model: "gpt-6-astra",
previous_response_id: first.id,
input: "And its population?",
store: true
)
puts(second.output_text)
即使使用 previous_response_id,回應鏈中先前所有回應的輸入 Token,仍會在 API 中以輸入 Token 計費。
Responses 預設會儲存回應。對新帳戶而言,Chat Completions 預設也會儲存回應。若要停用任一 API 的儲存功能,請設定 store: false。
部分組織(例如有零資料保留 (ZDR) 要求的組織)受合規要求或資料保留政策限制,無法以保留狀態的方式使用 Responses API。為支援這些情況,OpenAI 提供加密的推理項目,讓你的工作流程無須保留狀態,仍能享有推理項目的優勢。
若要停用狀態保留功能,同時繼續運用推理:
在 store 欄位 中設定 store: false。
保留並在後續請求中重新傳入每個傳回的推理項目。建立回應時,每個項目預設都會包含 encrypted_content。
API 接著會傳回加密的推理 Token,你可以像一般推理項目一樣,在後續請求中將其傳回。
對於 ZDR 組織,OpenAI 會自動強制套用 store: false。當請求包含 encrypted_content 時,系統會在記憶體中將其解密,用來生成下一個回應,然後安全地捨棄。任何新產生的推理 Token 都會立即加密並傳回給你,確保不會持續儲存任何中間狀態。
Chat Completions 與 Responses 的函式定義方式有兩個細微但需要注意的差異。
在 Chat Completions 中,函式定義採用外部標記;在 Responses 中,則採用內部標記。
在 Chat Completions 中,函式預設採用非嚴格模式。在 Responses 中,若省略 strict,系統會嘗試使用嚴格模式;若無法將結構描述調整為相容格式,Responses 就會改用非嚴格模式,盡力完成函式呼叫,並在傳回的最終工具定義中設定 strict: false。若要明確保留 Responses 的非嚴格模式行為,請設定 strict: false。
右側的 Responses API 函式範例與左側的 Chat Completions 範例在功能上相同。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 {
"type" : "function" ,
"function" : {
"name" : "get_weather" ,
"description" : "Determine weather in my location" ,
"strict" : true ,
"parameters" : {
"type" : "object" ,
"properties" : {
"location" : {
"type" : "string"
}
},
"additionalProperties" : false ,
"required" : [
"location"
]
}
}
} 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 {
"type" : "function" ,
"name" : "get_weather" ,
"description" : "Determine weather in my location" ,
"parameters" : {
"type" : "object" ,
"properties" : {
"location" : {
"type" : "string"
}
},
"additionalProperties" : false ,
"required" : [
"location"
]
}
}
在 Responses 中,工具呼叫及其輸出是兩種不同類型的項目,透過 call_id 建立關聯。如需進一步瞭解 Responses 中函式呼叫的運作方式,請參閱
函式呼叫文件 。
在 Responses API 中,結構化輸出定義已從 response_format 移至 text.format:
Chat Completions Responses Chat Completions
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 const completion = await openai.chat.completions. create ({
model: "gpt-6-astra" ,
messages: [
{
role: "user" ,
content: "Jane, 54 years old" ,
},
],
response_format: {
type: "json_schema" ,
json_schema: {
name: "person" ,
strict: true ,
schema: {
type: "object" ,
properties: {
name: {
type: "string" ,
minLength: 1 ,
},
age: {
type: "number" ,
minimum: 0 ,
maximum: 130 ,
},
},
required: [ "name" , "age" ],
additionalProperties: false ,
},
},
},
reasoning_effort: "medium" ,
}); 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 from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-6-astra",
messages=[
{
"role": "user",
"content": "Jane, 54 years old",
}
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "person",
"strict": True,
"schema": {
"type": "object",
"properties": {
"name": {"type": "string", "minLength": 1},
"age": {"type": "number", "minimum": 0, "maximum": 130},
},
"required": ["name", "age"],
"additionalProperties": False,
},
},
},
reasoning_effort="medium",
) 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
38
39 package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/shared"
)
func main() {
client := openai.NewClient()
schema := map[string]any{
"type": "object",
"properties": map[string]any{
"name": map[string]any{"type": "string", "minLength": 1},
"age": map[string]any{"type": "number", "minimum": 0, "maximum": 130},
},
"required": []string{"name", "age"},
"additionalProperties": false,
}
completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{
Model: "gpt-6-astra",
ReasoningEffort: openai.ReasoningEffortMedium,
Messages: []openai.ChatCompletionMessageParamUnion{
openai.UserMessage("Jane, 54 years old"),
},
ResponseFormat: openai.ChatCompletionNewParamsResponseFormatUnion{
OfJSONSchema: &shared.ResponseFormatJSONSchemaParam{JSONSchema: shared.ResponseFormatJSONSchemaJSONSchemaParam{
Name: "person", Strict: openai.Bool(true), Schema: schema,
}},
},
})
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
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44 import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.ReasoningEffort;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import java.util.List;
import java.util.Map;
ChatCompletionCreateParams params =
ChatCompletionCreateParams.builder()
.model("gpt-6-astra")
.reasoningEffort(ReasoningEffort.MEDIUM)
.addUserMessage("Jane, 54 years old")
.putAdditionalBodyProperty(
"response_format",
JsonValue.from(
Map.of(
"type",
"json_schema",
"json_schema",
Map.of(
"name",
"person",
"strict",
true,
"schema",
Map.of(
"type",
"object",
"properties",
Map.of(
"name",
Map.of("type", "string", "minLength", 1),
"age",
Map.of("type", "number", "minimum", 0, "maximum", 130)),
"required",
List.of("name", "age"),
"additionalProperties",
false)))))
.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
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36 using OpenAI.Chat;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "gpt-6-astra";
ChatClient client = new(model, key);
BinaryData schema = BinaryData.FromString(
"""
{
"type": "object",
"properties": {
"name": { "type": "string", "minLength": 1 },
"age": { "type": "number", "minimum": 0, "maximum": 130 }
},
"required": ["name", "age"],
"additionalProperties": false
}
"""
);
ChatCompletionOptions options = new()
{
ReasoningEffortLevel = ChatReasoningEffortLevel.Medium,
ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat(
"person",
schema,
jsonSchemaIsStrict: true
),
};
ChatCompletion completion = await client.CompleteChatAsync(
[new UserChatMessage("Jane, 54 years old")],
options
);
Console.WriteLine(completion.Content[0].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
38
39
40 require "openai"
client = OpenAI::Client.new
schema = {
type: "object",
properties: {
name: {
type: "string",
minLength: 1
},
age: {
type: "number",
minimum: 0,
maximum: 130
}
},
required: ["name", "age"],
additionalProperties: false
}
completion = client.chat.completions.create(
model: "gpt-6-astra",
reasoning_effort: :medium,
messages: [
{
role: :user,
content: "Jane, 54 years old"
}
],
response_format: {
type: :json_schema,
json_schema: {
name: "person",
strict: true,
schema: schema
}
}
)
puts(completion.choices.fetch(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
28
29
30
31
32
33
34
35
36
37
38
39 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": "user",
"content": "Jane, 54 years old"
}
],
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "person",
"strict": true,
"schema": {
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"age": {
"type": "number",
"minimum": 0,
"maximum": 130
}
},
"required": [
"name",
"age"
],
"additionalProperties": false
}
}
},
"reasoning_effort": "medium"
}' Responses
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 const response = await openai.responses. create ({
model: "gpt-6-astra" ,
input: "Jane, 54 years old" ,
text: {
format: {
type: "json_schema" ,
name: "person" ,
strict: true ,
schema: {
type: "object" ,
properties: {
name: {
type: "string" ,
minLength: 1 ,
},
age: {
type: "number" ,
minimum: 0 ,
maximum: 130 ,
},
},
required: [ "name" , "age" ],
additionalProperties: false ,
},
},
},
}); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 response = client.responses.create(
model="gpt-6-astra",
input="Jane, 54 years old",
text={
"format": {
"type": "json_schema",
"name": "person",
"strict": True,
"schema": {
"type": "object",
"properties": {
"name": {"type": "string", "minLength": 1},
"age": {"type": "number", "minimum": 0, "maximum": 130},
},
"required": ["name", "age"],
"additionalProperties": False,
},
}
},
) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
schema := map[string]any{
"type": "object",
"properties": map[string]any{
"name": map[string]any{"type": "string", "minLength": 1},
"age": map[string]any{"type": "number", "minimum": 0, "maximum": 130},
},
"required": []string{"name", "age"},
"additionalProperties": false,
}
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Jane, 54 years old")},
Text: responses.ResponseTextConfigParam{Format: responses.ResponseFormatTextConfigUnionParam{
OfJSONSchema: &responses.ResponseFormatTextJSONSchemaConfigParam{Name: "person", Schema: schema, Strict: openai.Bool(true)},
}},
})
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
38
39
40
41
42
43
44
45
46 import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseFormatTextJsonSchemaConfig;
import com.openai.models.responses.ResponseTextConfig;
import java.util.List;
import java.util.Map;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("Jane, 54 years old")
.text(
ResponseTextConfig.builder()
.format(
ResponseFormatTextJsonSchemaConfig.builder()
.name("person")
.strict(true)
.schema(
ResponseFormatTextJsonSchemaConfig.Schema.builder()
.putAdditionalProperty("type", JsonValue.from("object"))
.putAdditionalProperty(
"properties",
JsonValue.from(
Map.of(
"name",
Map.of("type", "string", "minLength", 1),
"age",
Map.of(
"type", "number", "minimum", 0, "maximum",
130))))
.putAdditionalProperty(
"required", JsonValue.from(List.of("name", "age")))
.putAdditionalProperty(
"additionalProperties", JsonValue.from(false))
.build())
.build())
.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
25
26
27
28
29
30
31
32
33
34
35
36
37
38 using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
BinaryData schema = BinaryData.FromString(
"""
{
"type": "object",
"properties": {
"name": { "type": "string", "minLength": 1 },
"age": { "type": "number", "minimum": 0, "maximum": 130 }
},
"required": ["name", "age"],
"additionalProperties": false
}
"""
);
CreateResponseOptions options = new()
{
Model = "gpt-6-astra",
TextOptions = new ResponseTextOptions
{
TextFormat = ResponseTextFormat.CreateJsonSchemaFormat(
"person",
schema,
jsonSchemaIsStrict: true
),
},
};
options.InputItems.Add(
ResponseItem.CreateUserMessageItem("Jane, 54 years old")
);
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
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 require "openai"
client = OpenAI::Client.new
schema = {
type: "object",
properties: {
name: {
type: "string",
minLength: 1
},
age: {
type: "number",
minimum: 0,
maximum: 130
}
},
required: ["name", "age"],
additionalProperties: false
}
response = client.responses.create(
model: "gpt-6-astra",
input: "Jane, 54 years old",
text: {
format: {
type: :json_schema,
name: "person",
strict: true,
schema: schema
}
}
)
puts(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 curl https://api.openai.com/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-6-astra",
"input": "Jane, 54 years old",
"text": {
"format": {
"type": "json_schema",
"name": "person",
"strict": true,
"schema": {
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"age": {
"type": "number",
"minimum": 0,
"maximum": 130
}
},
"required": [
"name",
"age"
],
"additionalProperties": false
}
}
}
}'
Chat Completions 串流會逐步傳回包含 delta 欄位的區塊。Responses 串流則使用具有明確類型的伺服器傳送事件。請更新串流接收端,依每個事件的 type 分別處理 UI 或編排層所需的事件。
處理文字串流時,請監聽下列事件:
response.created
response.output_text.delta
response.completed
error
函式呼叫串流也可能發出 response.function_call_arguments.delta 和 response.function_call_arguments.done 等事件。請參閱 Responses 串流指南 和 Responses 串流事件參考資料 。
如果應用程式的使用案例適合使用 OpenAI 原生工具 ,你可以更新工具呼叫,直接使用 OpenAI 提供的工具。
Chat Completions Responses
Chat Completions
Chat Completions 不原生支援 OpenAI 託管的工具,
因此你必須自行撰寫工具整合程式碼。
此範例使用 GPT-5.6,因為 GPT-6 Astra 必須透過 Responses API
才能呼叫工具。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 async function web_search ( query ) {
const res = await fetch ( `https://api.example.com/search?q=${ query }` );
const data = await res. json ();
return data.results;
}
const completion = await client.chat.completions. create ({
model: "gpt-5.6" ,
messages: [
{ role: "system" , content: "You are a helpful assistant." },
{ role: "user" , content: "Who is the current president of France?" },
],
functions: [
{
name: "web_search" ,
description: "Search the web for information" ,
parameters: {
type: "object" ,
properties: { query: { type: "string" } },
required: [ "query" ],
},
},
],
}); 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 import requests
def web_search(query):
r = requests.get(f"https://api.example.com/search?q={query}")
return r.json().get("results", [])
completion = client.chat.completions.create(
model="gpt-5.6",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Who is the current president of France?"},
],
functions=[
{
"name": "web_search",
"description": "Search the web for information",
"parameters": {
"type": "object",
"properties": {"query": {"type": "string"}},
"required": ["query"],
},
}
],
) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/shared"
)
func main() {
client := openai.NewClient()
completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{
Model: "gpt-5.6",
Messages: []openai.ChatCompletionMessageParamUnion{
openai.SystemMessage("You are a helpful assistant."),
openai.UserMessage("Who is the current president of France?"),
},
Functions: []openai.ChatCompletionNewParamsFunction{{
Name: "web_search",
Description: openai.String("Search the web for information"),
Parameters: map[string]any{
"type": "object",
"properties": map[string]any{"query": map[string]any{"type": "string"}},
"required": []string{"query"},
},
}},
ReasoningEffort: shared.ReasoningEffortNone,
})
if err != nil {
panic(err)
}
fmt.Println(completion.Choices[0].Message)
} 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 import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.FunctionParameters;
import com.openai.models.ReasoningEffort;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import java.util.List;
import java.util.Map;
ChatCompletionCreateParams params =
ChatCompletionCreateParams.builder()
.model("gpt-5.6")
.reasoningEffort(ReasoningEffort.NONE)
.addSystemMessage("You are a helpful assistant.")
.addUserMessage("Who is the current president of France?")
.addFunction(
ChatCompletionCreateParams.Function.builder()
.name("web_search")
.description("Search the web for information")
.parameters(
FunctionParameters.builder()
.putAdditionalProperty("type", JsonValue.from("object"))
.putAdditionalProperty(
"properties",
JsonValue.from(Map.of("query", Map.of("type", "string"))))
.putAdditionalProperty("required", JsonValue.from(List.of("query")))
.build())
.build())
.build();
client.chat().completions().create(params).choices().stream()
.map(choice -> choice.message())
.forEach(System.out::println); 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 require "openai"
client = OpenAI::Client.new
completion = client.chat.completions.create(
model: "gpt-5.6",
reasoning_effort: :none,
messages: [
{
role: :system,
content: "You are a helpful assistant."
},
{
role: :user,
content: "Who is the current president of France?"
}
],
functions: [
{
name: "web_search",
description: "Search the web for information",
parameters: {
type: "object",
properties: { query: { type: "string" } },
required: ["query"]
}
}
]
)
puts(completion.choices.fetch(0).message) 1
2
3
4 curl https://api.example.com/search \
-G \
--data-urlencode "q=your+search+term" \
--data-urlencode "key=$SEARCH_API_KEY"
Responses
使用 Responses 時,你可以指定希望模型使用的工具。
1
2
3
4
5
6
7 const answer = await client.responses. create ({
model: "gpt-6-astra" ,
input: "Who is the current president of France?" ,
tools: [{ type: "web_search" }],
});
console. log (answer.output_text); 1
2
3
4
5
6
7 answer = client.responses.create(
model="gpt-6-astra",
input="Who is the current president of France?",
tools=[{"type": "web_search"}],
)
print(answer.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 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",
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Who is the current president of France?")},
Tools: []responses.ToolUnionParam{
responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch),
},
})
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;
import com.openai.models.responses.WebSearchTool;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("Who is the current president of France?")
.addTool(WebSearchTool.builder().type(WebSearchTool.Type.WEB_SEARCH).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 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" };
options.Tools.Add(ResponseTool.CreateWebSearchTool());
options.InputItems.Add(
ResponseItem.CreateUserMessageItem("Who is the current president of France?")
);
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",
input: "Who is the current president of France?",
tools: [{ type: :web_search }]
)
puts(response.output_text) 1
2
3
4
5
6
7
8 curl https://api.openai.com/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-6-astra",
"input": "Who is the current president of France?",
"tools": [{"type": "web_search"}]
}'
將程式碼從 Chat Completions 遷移至 Responses 時,請留意下列問題:
讀取 choices[0].message.content,而非 response.output_text 或 response.output。
將每個 output 項目都視為訊息。推理、工具呼叫和函式呼叫各自屬於不同的項目類型。
手動將上下文帶入下一個回應時,遺漏推理、函式呼叫或函式呼叫輸出項目。
傳送函式結果時,未附上對應的 call_id。
在 Responses 請求中使用 response_format,而非 text.format。
沿用 Chat Completions 的串流區塊處理常式,卻未處理 Responses 中具有明確類型的事件。
誤以為使用 previous_response_id 就不會對先前的上下文計費。回應鏈中先前的輸入 Token 仍會按輸入 Token 計費。
Chat Completions 仍受支援,因此你可以一次遷移一個使用者流程。
我們建議逐步將所有流程遷移至 Responses API,以使用 OpenAI 最新的功能與改進。
我們根據開發人員對 Assistants API 測試版的回饋,將重要改進納入 Responses API,使其更靈活、更快速,也更容易使用。Responses API 代表未來在 OpenAI 上建構智慧體的發展方向。
Assistants API 已於 2026 年 8 月 26 日正式停止服務,目前已無法使用。請依照遷移指南 ,將你的整合更新為使用 Responses API。