Responses API 是我們在 Chat Completions 的基礎上發展出的新一代基礎 API,可簡化整合作業,並提供建構智慧體所需的強大基本功能。
我們持續支援 Chat Completions,並建議所有新專案使用 Responses。
Responses API 提供統一的介面,讓你建構具備智慧體能力的強大應用程式。它提供下列功能:
與 Chat Completions 相比,Responses API 有以下優點:
模型表現更好 :使用 GPT-5 等推理模型時,模型在 Responses 上的表現優於 Chat Completions。內部評估顯示,使用相同提示詞和設定時,SWE-bench 的成績提升了 3%。
預設支援智慧體迴圈 :在單一 API 請求中,模型可以呼叫多種工具,包括 web_search、image_generation、file_search、code_interpreter、遠端 MCP 伺服器,以及你自訂的函式。
成本更低 :Responses 能更有效地利用快取,因而降低成本。在內部測試中,快取利用率比 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 將多種用途的資料放在同一個訊息物件中,而 Responses 會將它們區分為獨立的項目,更能反映模型上下文的基本單位。
此外,Chat Completions 可將多個平行生成的結果放在 choices 中傳回,結果數量由 n 參數指定。Responses API 沒有這個參數,每次只傳回一個生成結果。
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 傳回的欄位略有不同。原本會收到 message,改用 Responses API 後,則會收到具備明確型別的 response 物件,該物件有自己的 id。
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 起,在 Chat Completions 中,如果 reasoning_effort 的值不是 none,就無法呼叫工具。
兩種 API 定義結構化輸出的方式不同。請將 response_format 改為 Responses 使用的 text.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" | "user" ; content : string }[] = [
{ 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 : OpenAI . Chat . Completions . ChatCompletionMessageParam [] = [
{ 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
20
21 import { toResponseInputItems } from "openai/lib/responses/ResponseInputItems" ;
let context : OpenAI . Responses . ResponseInput = [
{ 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,API 仍會將回應鏈中先前各次回應的所有輸入 Token 按輸入 Token 計費。
Responses 預設會儲存回應。新帳戶使用 Chat Completions 時,預設也會儲存生成結果。如要停用任一 API 的儲存功能,請設定 store: false。
部分組織受合規要求或資料保留政策限制,例如必須符合零資料保留(ZDR)要求的組織,無法以保留狀態的方式使用 Responses API。為了支援這些情境,OpenAI 提供加密推理項目,讓工作流程在不儲存狀態的情況下仍能使用推理項目。
如要停止儲存狀態並繼續使用推理功能:
設定 store: false,即可透過 store 欄位 停用儲存功能。
保留並再次傳入所有傳回的推理項目。建立回應時,每個推理項目預設都包含 encrypted_content。
API 隨後會傳回加密的推理 Token。你可以像使用一般推理項目一樣,在後續請求中再次傳入這些 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 分別處理使用者介面或協調層所需的事件。
若要以串流方式接收文字,可以監聽的事件包括:
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 Terra,並停用推理。GPT-6 Astra 和
GPT-6.1 Sol 必須透過 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
25 async function web_search ( query : string ) {
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-terra" ,
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" ],
},
},
],
}); 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 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-terra",
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"],
},
}
],
) 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-terra",
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-terra")
.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-terra",
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 Beta 測試期間提供的意見,我們在 Responses API 中做了幾項重要改進,使其更靈活、速度更快,也更容易使用。Responses API 是未來在 OpenAI 平台上建構智慧體的方向。
Assistants API 已於 2026 年 8 月 26 日正式停止服務,目前已無法使用。請依照遷移指南 ,將現有整合更新為使用 Responses API。