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 返回的响应在字段上略有不同。
您收到的不再是 message,而是一个带有类型和自身 id 的 response 对象。
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 输出条目 工具或函数结果 一个通过 call_id 与调用关联的 function_call_output 输入条目 使用 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。