保持对话前缀不变。 将新消息和工具结果追加到对话末尾。如果需要缩短某个工具结果,请在首次发送该结果之前精简内容。使用 GPT-6.2 Astra 和 Sol 时,如果您修改了较早的对话历史,Responses API 的保护机制可能会丢弃修改位置之后已保存的推理内容。模型可能需要花费额外的时间和 Token 重做这部分工作。如果模型无法还原先前的推理结果,回答质量可能会下降。
部署前,请运行一项多轮任务。检查每个响应的 input_transformations 字段,如果非空,就将其内容写入日志。如果看到 prefix_mismatch,请找出并修正导致前缀不匹配的改动 。在生产环境中,请跟踪前缀不匹配的发生频率 ,统计所有 GPT-6.2 响应中至少出现一次 prefix_mismatch 的响应所占的百分比。
始终优先使用 Responses API 。这是 OpenAI 的旗舰 API,也是使用最新模型能力、内置工具、有状态工作流和智能体功能的首选。
针对您的工作负载评估 GPT-6 系列模型 。需要最强能力时,使用 gpt-6-astra 。要以低于 Astra 的成本完成复杂的编程任务和专业工作,使用 gpt-6.1-sol 。要高效处理可重复执行的任务,使用 gpt-6-luna 。根据模型在代表性任务上的表现进行选择,避免将所有请求都发给能力最强的模型。
迁移到 GPT-6 时,在新模型支持的情况下,保留当前模型在工作负载中承担的角色及实际使用的推理强度。需要结合工具进行推理时,使用 Responses API。GPT-6 Astra 和 GPT-6.1 Sol 必须通过 Responses 调用工具。GPT-6 Sol 和 GPT-6 Luna 仅在设置 reasoning_effort: "none" 时支持在 Chat Completions 中调用函数。如果推理强度不是 none,请移除 temperature、top_p 和 top_logprobs,同时从 Chat Completions 请求中移除 logprobs,并将 message.output_text.logprobs 从 Responses 的 include 数组中移除。选择模型或处理层级之前,请确认其是否符合数据驻留条件 。其他兼容性检查请参阅模型迁移指南 。在更改提示词或添加新功能之前,先运行有代表性的评估。比较任务成功率、延迟、输入、输出、推理和缓存写入的 Token 数,以及每项成功任务的成本。
使用 reasoning.effort 控制模型在回答前投入多少推理工作。
GPT-6 Astra、GPT-6.1 Sol、GPT-6 Sol 和 GPT-6 Luna 均支持 low、medium、high、xhigh 和 max。GPT-6 Sol 和 GPT-6 Luna 还支持 none,GPT-6 Astra 和 GPT-6.1 Sol 则不支持。降低推理强度可加快响应,减少推理 Token 用量。提高推理强度可让模型有更多时间规划、调试、综合信息,以及在多个步骤中权衡取舍。
如果任务主要涉及提取信息、路由、分类或常规改写,请使用 low。如果模型需要诊断问题、比较选项、制定计划或分析代码,请使用 medium 或 high。仅当代表性评估表明质量提升值得付出额外的延迟和成本时,才使用 xhigh 或 max。如果原设置为 minimal,或原设置为 none 且要迁移到 GPT-6 Astra 或 GPT-6.1 Sol,请从 low 开始并比较结果。其他情况下,请保留当前实际使用的推理强度,并根据质量、延迟和成本目标测试调整后的效果。
对于最复杂且优先考虑质量的工作负载,还应在相同推理强度下比较 reasoning.mode: "pro" 与标准模式。推理模式和推理强度彼此独立。在 Pro 模式下,模型会在给出一个最终答案前投入更多计算资源。这可以提高可靠性,但也会增加延迟和 Token 用量。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 import OpenAI from "openai";
const openai = new OpenAI();
const prompt = [
"Our CI job started failing after a dependency bump.",
"",
"Error:",
"TypeError: Timeout.__init__() got an unexpected keyword argument 'connect'",
"",
"Identify the likeliest root cause and the smallest safe fix.",
].join("\n");
const response = await openai.responses.create({
model: "gpt-6.2-astra",
reasoning: { effort: "xhigh", mode: "pro" },
input: prompt,
});
console.log(response.output_text); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 from openai import OpenAI
client = OpenAI()
prompt = """
Our CI job started failing after a dependency bump.
Error:
TypeError: Timeout.__init__() got an unexpected keyword argument 'connect'
Identify the likeliest root cause and the smallest safe fix.
"""
response = client.responses.create(
model = "gpt-6.2-astra" ,
reasoning = { "effort" : "xhigh" , "mode" : "pro" },
input = prompt,
)
print (response.output_text) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package main
import (
"context"
"fmt"
"strings"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
"github.com/openai/openai-go/v3/shared"
)
func main() {
client := openai.NewClient()
prompt := strings.Join([]string{
"Our CI job started failing after a dependency bump.",
"",
"Error:",
"TypeError: Timeout.__init__() got an unexpected keyword argument 'connect'",
"",
"Identify the likeliest root cause and the smallest safe fix.",
}, "\n")
reasoning := shared.ReasoningParam{Effort: shared.ReasoningEffortXhigh}
reasoning.SetExtraFields(map[string]any{"mode": "pro"})
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6.2-astra",
Reasoning: reasoning,
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(prompt)},
})
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 import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.Reasoning;
import com.openai.models.ReasoningEffort;
import com.openai.models.responses.ResponseCreateParams;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6.2-astra")
.input(
"Our CI job started failing after a dependency bump. Error: TypeError: Timeout.__init__() got an unexpected keyword argument 'connect'. Identify the likeliest root cause and the smallest safe fix.")
.reasoning(
Reasoning.builder()
.effort(ReasoningEffort.XHIGH)
.putAdditionalProperty("mode", JsonValue.from("pro"))
.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 require "openai"
client = OpenAI::Client.new
prompt = <<~PROMPT
Our CI job started failing after a dependency bump.
Error:
TypeError: Timeout.__init__() got an unexpected keyword argument 'connect'
Identify the likeliest root cause and the smallest safe fix.
PROMPT
response = client.responses.create(
model: "gpt-6.2-astra",
reasoning: {
effort: :xhigh,
mode: :pro
},
input: prompt
)
puts(response.output_text)
对于以标准单智能体模式运行的 GPT-6 模型,可在下一条用户消息之前添加一个 configuration_update 输入项,在两次响应之间调整推理强度。保持请求级 reasoning.effort 不变,以便原提示词前缀仍可缓存。更新从下一次响应开始生效,直到被另一次更新覆盖。配置更新不能与自动压缩或自动截断结合使用,/responses/compact 也会拒绝包含配置更新的历史记录。要压缩历史记录,请加入一个 compaction_trigger 项,然后添加新的配置更新。
设置 text.verbosity
text.verbosity 是平衡简洁性与完整性的主要设置。如果产品需要快速给出简短答案,请降低详尽程度。如果回答需要更充分的解释、更清晰的结构或完整的背景信息,请提高详尽程度。降低详尽程度会减少输出 Token 数,模型生成的内容更少,返回结果也更快。
对于编程任务,medium 和 high 通常会生成更长、更有条理、结构更清晰的输出。low 会使回答更紧凑,只保留必要内容。
迁移时,请检查“请简明扼要”等笼统的指令是否仍然有效。优先使用 text.verbosity 控制默认的详尽程度,再通过提示词指定必要的内容、结构和长度。
提示词也会影响质量、Token 用量、成本和延迟。设置详尽程度时,请一并参阅最新模型的提示词最佳实践 ,包括其中针对编程智能体的测试和验证指南。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 import OpenAI from "openai";
const openai = new OpenAI();
const incident = [
"Summarize this incident for the next on-call engineer.",
"- checkout latency spiked from 220 ms to 4.8 s",
"- only us-east-1 was affected",
"- rollback is complete",
"- likely trigger: cache stampede after deploy",
].join("\n");
const response = await openai.responses.create({
model: "gpt-6.2-astra",
text: { verbosity: "low" },
input: incident,
});
console.log(response.output_text); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model = "gpt-6.2-astra" ,
text = { "verbosity" : "low" },
input = """
Summarize this incident for the next on-call engineer.
- checkout latency spiked from 220 ms to 4.8 s
- only us-east-1 was affected
- rollback is complete
- likely trigger: cache stampede after deploy
""" ,
)
print (response.output_text) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 package main
import (
"context"
"fmt"
"strings"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
incident := strings.Join([]string{
"Summarize this incident for the next on-call engineer.",
"- checkout latency spiked from 220 ms to 4.8 s",
"- only us-east-1 was affected",
"- rollback is complete",
"- likely trigger: cache stampede after deploy",
}, "\n")
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6.2-astra",
Text: responses.ResponseTextConfigParam{Verbosity: "low"},
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(incident)},
})
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 import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseTextConfig;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6.2-astra")
.input(
"Summarize this incident for the next on-call engineer: checkout latency spiked from 220 ms to 4.8 s, only us-east-1 was affected, rollback is complete, and the likely trigger was a cache stampede.")
.text(ResponseTextConfig.builder().verbosity(ResponseTextConfig.Verbosity.LOW).build())
.build();
client.responses().create(params).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text())); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 require "openai"
client = OpenAI::Client.new
incident = <<~INCIDENT
Summarize this incident for the next on-call engineer.
- checkout latency spiked from 220 ms to 4.8 s
- only us-east-1 was affected
- rollback is complete
- likely trigger: cache stampede after deploy
INCIDENT
response = client.responses.create(
model: "gpt-6.2-astra",
text: { verbosity: :low },
input: incident
)
puts(response.output_text)
phase 是对话历史中助手消息的标签,用于告知模型先前的助手消息是工作过程中的说明还是最终答案。对于进度更新、调用工具前的说明和其他中间消息,请使用 phase: "commentary"。对于已完成的回答,请使用 phase: "final_answer"。
例如,助手可能会这样说:
1
2
3
4
5 {
"role" : "assistant" ,
"phase" : "commentary" ,
"content" : "I'm checking the logs and comparing them to the last successful deploy."
}
这条消息只是进度说明。稍后,助手可能会给出这样的答案:
1
2
3
4
5 {
"role" : "assistant" ,
"phase" : "final_answer" ,
"content" : "The deploy failed because the migration referenced a column that does not exist in production."
}
在长时间运行或频繁调用工具的工作流中,助手可能会在完成任务前向用户报告进度,这时该标签尤为有用。在向 gpt-5.3-codex 及后续模型发送包含这段历史的后续请求时,请保留并重新发送助手消息中的 phase ,以便模型区分进度更新和最终结果。这样有助于减少提前停止的情况,让智能体更有可能持续工作,直到给出最终答案。
无需在每次请求中加载完整的工具目录。使用工具搜索 时,添加 {"type": "tool_search"},并为加载成本较高的工具定义设置 defer_loading: true。模型便可在运行时按需加载工具。请求开始时,模型只能看到搜索工具的名称和描述。如果模型判断需要某个延迟加载的工具,就会执行工具搜索。只有这时,相关工具定义才会载入上下文,模型才能调用这些工具。这样可以节省 Token,并保持缓存性能。
工具搜索有两种模式:
托管工具搜索 更简单。如果您事先就知道某个请求可以使用哪些工具,请使用此模式。
客户端执行的工具搜索 适用于由应用决定哪些工具可用的情况,例如根据用户所属的租户、项目、权限或内部注册表确定可用工具。
优先使用托管工具搜索 ,除非您的应用确实需要自行控制工具发现过程。
按用户意图为工具分组。尽可能使用命名空间或 MCP 服务器。与从一长串未分组的函数中选择相比,模型更容易在少数几个划分明确的组之间做出选择。为提高 Token 使用效率和模型性能,建议将每个命名空间中的函数控制在约 10 个以内。
命名空间的描述应简短,并能体现各组之间的区别。将详细指令放在延迟加载的工具定义中。避免将所有工具都放在一个庞大的命名空间里。
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61 import OpenAI from "openai";
const openai = new OpenAI();
const billingNamespace: OpenAI.Responses.NamespaceTool = {
type: "namespace",
name: "billing",
description: "Billing tools for invoices, payments, taxes, and credits.",
tools: [
{
type: "function",
name: "lookup_invoice",
description:
"Look up invoice state, taxes, credits, and payment attempts.",
parameters: {
type: "object",
properties: {
invoice_id: { type: "string" },
},
required: ["invoice_id"],
additionalProperties: false,
},
strict: true,
defer_loading: true,
},
],
};
const crmNamespace: OpenAI.Responses.NamespaceTool = {
type: "namespace",
name: "crm",
description:
"CRM tools for account ownership, plans, health, and payment history.",
tools: [
{
type: "function",
name: "get_account",
description: "Fetch account owner, plan, health, and payment history.",
parameters: {
type: "object",
properties: {
account_id: { type: "string" },
},
required: ["account_id"],
additionalProperties: false,
},
strict: true,
defer_loading: true,
},
],
};
const response = await openai.responses.create({
model: "gpt-6.2-astra",
input:
"Find the right billing tool and explain why invoice INV-1043 still " +
"shows overdue after a payment yesterday.",
tools: [billingNamespace, crmNamespace, { type: "tool_search" }],
});
console.log(response.output); 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60 from openai import OpenAI
client = OpenAI()
billing_namespace = {
"type" : "namespace" ,
"name" : "billing" ,
"description" : "Billing tools for invoices, payments, taxes, and credits." ,
"tools" : [
{
"type" : "function" ,
"name" : "lookup_invoice" ,
"description" : "Look up invoice state, taxes, credits, and payment attempts." ,
"parameters" : {
"type" : "object" ,
"properties" : {
"invoice_id" : { "type" : "string" },
},
"required" : [ "invoice_id" ],
"additionalProperties" : False ,
},
"strict" : True ,
"defer_loading" : True ,
}
],
}
crm_namespace = {
"type" : "namespace" ,
"name" : "crm" ,
"description" : "CRM tools for account ownership, plans, health, and payment history." ,
"tools" : [
{
"type" : "function" ,
"name" : "get_account" ,
"description" : "Fetch account owner, plan, health, and payment history." ,
"parameters" : {
"type" : "object" ,
"properties" : {
"account_id" : { "type" : "string" },
},
"required" : [ "account_id" ],
"additionalProperties" : False ,
},
"strict" : True ,
"defer_loading" : True ,
}
],
}
response = client.responses.create(
model = "gpt-6.2-astra" ,
input = (
"Find the right billing tool and explain why invoice INV-1043 still "
"shows overdue after a payment yesterday."
),
tools = [billing_namespace, crm_namespace, { "type" : "tool_search" }],
)
print (response.output) 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
47
48
49
50
51
52
53
54
55
56
57
58 package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
billing := namespaceTool(
"billing",
"Billing tools for invoices, payments, taxes, and credits.",
"lookup_invoice",
"Look up invoice state, taxes, credits, and payment attempts.",
"invoice_id",
)
crm := namespaceTool(
"crm",
"CRM tools for account ownership, plans, health, and payment history.",
"get_account",
"Fetch account owner, plan, health, and payment history.",
"account_id",
)
toolSearch := responses.ToolUnionParam{OfToolSearch: &responses.ToolSearchToolParam{}}
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6.2-astra",
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(
"Find the right billing tool and explain why invoice INV-1043 still shows overdue after a payment yesterday.",
)},
Tools: []responses.ToolUnionParam{billing, crm, toolSearch},
})
if err != nil {
panic(err)
}
fmt.Println(response.Output)
}
func namespaceTool(namespace, namespaceDescription, name, description, argument string) responses.ToolUnionParam {
parameters := map[string]any{
"type": "object",
"properties": map[string]any{
argument: map[string]any{"type": "string"},
},
"required": []string{argument},
"additionalProperties": false,
}
function := responses.NamespaceToolToolFunctionParam{
Name: name, Description: openai.String(description), Parameters: parameters, Strict: openai.Bool(true), DeferLoading: openai.Bool(true),
}
return responses.ToolParamOfNamespace(
namespaceDescription,
namespace,
[]responses.NamespaceToolToolUnionParam{{OfFunction: &function}},
)
} 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62 import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.NamespaceTool;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ToolSearchTool;
import java.util.List;
import java.util.Map;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6.2-astra")
.input(
"Find the right billing tool and explain why invoice INV-1043 still shows overdue after a payment yesterday.")
.addTool(
namespace(
"billing",
"Billing tools for invoices, payments, taxes, and credits.",
"lookup_invoice",
"Look up invoice state, taxes, credits, and payment attempts.",
"invoice_id"))
.addTool(
namespace(
"crm",
"CRM tools for account ownership, plans, health, and payment history.",
"get_account",
"Fetch account owner, plan, health, and payment history.",
"account_id"))
.addTool(ToolSearchTool.builder().execution(ToolSearchTool.Execution.SERVER).build())
.build();
client.responses().create(params).output().forEach(System.out::println);
private static NamespaceTool namespace(
String name,
String description,
String function,
String functionDescription,
String argument) {
return NamespaceTool.builder()
.name(name)
.description(description)
.addTool(
NamespaceTool.Tool.Function.builder()
.name(function)
.description(functionDescription)
.deferLoading(true)
.strict(true)
.parameters(
JsonValue.from(
Map.of(
"type",
"object",
"properties",
Map.of(argument, Map.of("type", "string")),
"required",
List.of(argument),
"additionalProperties",
false)))
.build())
.build();
} 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
47
48 require "openai"
def namespace_tool(name, description, function_name, function_description, argument)
{
type: :namespace,
name: name,
description: description,
tools: [
{
type: :function,
name: function_name,
description: function_description,
defer_loading: true,
strict: true,
parameters: {
type: "object",
properties: { argument => { type: "string" } },
required: [argument],
additionalProperties: false
}
}
]
}
end
client = OpenAI::Client.new
billing = namespace_tool(
"billing",
"Billing tools for invoices, payments, taxes, and credits.",
"lookup_invoice",
"Look up invoice state, taxes, credits, and payment attempts.",
"invoice_id"
)
crm = namespace_tool(
"crm",
"CRM tools for account ownership, plans, health, and payment history.",
"get_account",
"Fetch account owner, plan, health, and payment history.",
"account_id"
)
response = client.responses.create(
model: "gpt-6.2-astra",
input: "Find the right billing tool and explain why invoice INV-1043 still shows overdue after a payment yesterday.",
tools: [billing, crm, { type: :tool_search }]
)
puts(response.output)
程序化工具调用 允许支持此功能的模型编写 JavaScript,在托管运行环境中调用符合条件的工具并精简中间结果。如果某个阶段的范围明确,可用代码对大量工具结果进行筛选、关联、排序、去重、合并或检查,再将较小的结构化结果返回给模型,就适合使用此功能。
添加 programmatic_tool_calling 工具,并为每个符合条件的工具单独启用程序化调用。如果工具仅供程序调用,请设置 allowed_callers: ["programmatic"]。如果模型也可以直接调用该工具,请设置 allowed_callers: ["direct", "programmatic"]。如果每次调用的结果都可能改变模型的下一步决策、操作需要审批,或最终答案必须保留引用或原生产物,请继续使用直接调用。记录工具的返回字段和出错时的行为,让模型无需先查看结果就能编写正确的程序。
工具调用循环必须处理 program 和 program_output 项,还要处理程序发起的 function_call 项及其对应的 function_call_output 项。保留每个 call_id,并将函数调用的 caller 复制到对应输出中,以便服务恢复执行正确的程序。
请同时测试 program_output 和助手的最终消息。即使程序结果正确,最终答案仍可能不完整。针对同一工作流,比较程序化调用和直接工具调用的任务成功率、所需证据、Token 总数、延迟和成本。
多智能体 功能允许 GPT-6 等支持该功能的模型将相互独立的工作分配给子智能体,再综合各自的结果。如果研究、分析或实现工作可以拆分为具体且范围明确的任务,且这些任务可以使用各自的上下文并行执行,就适合使用此功能。
在请求中将 multi_agent.enabled 设置为 true。对于 HTTP,请通过测试版 Responses SDK 使用 client.beta.responses,并将 responses_multi_agent=v1 传入 betas。对于原始 HTTP 或 WebSocket 连接,请发送 OpenAI-Beta: responses_multi_agent=v1。多智能体功能处于测试阶段时,各项的数据结构可能会发生变化。
对于短任务、每一步都依赖上一步的有序任务链,或需要写入同一可变资源的工作,请优先使用单个智能体。子智能体可能会增加 Token 用量,因此请先使用 max_concurrent_subagents 的默认值 3,并衡量端到端质量、延迟和成本。对于频繁调用工具或长时间运行的多智能体工作流,WebSocket 模式可以降低继续执行时的开销。
启用多智能体功能前,请考虑其当前限制:不支持 /responses/compact、reasoning.summary 和 max_tool_calls。服务器会自动压缩根智能体及每个子智能体的上下文。
在 GPT-6 模型上,如果模型可以在应用执行工具的同时继续工作,请为函数工具或自定义工具设置 async: true。尽早启动耗时的工具调用,让模型同时处理与之无关的工作。应用仍需执行并跟踪调用,然后在后续 Responses 请求中使用原 call_id 返回结果。异步执行不适用于内置工具或程序化工具调用。在多智能体模式下,请勿将异步工具与并行工具调用结合使用。完整流程请参阅异步工具调用 。
内置工具 是 API 原生提供的能力。无需自行构建每个工具,您可以让模型使用已集成到 Responses API 中的工具,由模型决定何时调用。
OpenAI 持续推出新的原生工具。如果内置工具适合您的工作流,请优先使用。如果原生工具无法满足任务需求,再构建自定义工具。目前的内置工具及相关选项包括:
网页搜索 :搜索网页以获取最新信息
文件搜索 :搜索已上传的文件或向量存储库
代码解释器 :运行 Python 进行分析、数学计算、图表绘制和文件处理
Shell :在托管容器或您自己的运行环境中执行 shell 命令
计算机使用 :通过截屏、点击、输入和滚动来操作用户界面
图像生成 :生成或编辑图像
MCP/连接器 :将模型连接到外部服务和工具
技能 :附加可复用的指令包和工作流文件
应用补丁 :对代码进行结构化编辑
模型表现也是优先使用内置工具的原因。内置工具属于模型后训练所覆盖的数据分布,即模型已针对这些工具的接口形式、行为和输出接受过训练和评估。与使用新工具相比,OpenAI 模型使用内置工具时,工具选择更准确,执行更顺畅,失败也更少。
压缩 是一种上下文工程工具,用于决定模型在多轮对话中保留哪些信息。对于长时间运行的智能体,除了要考虑“是否会达到上下文上限”,还要考虑旧消息、工具日志、重试记录和过时细节是否会挤占空间,使模型无法保留所需的状态信息。
通过压缩,您可以在保留后续轮次所需状态的同时,有控制地缩小上下文。在完成调试阶段或缩小根因范围等重要节点,您可以压缩之前的上下文窗口,并从压缩后的输出继续。这样,下一轮对话就能围绕关键状态展开,模型也更容易保持专注,无需带上每一步中间推理、失败的命令和已经过时的推理分支。
您可以通过两种方式使用压缩:
交由服务器处理 :如果使用 previous_response_id,请启用 context_management 并设置 compact_threshold。对话过长时,服务器会自动压缩,您只需继续发送最新的用户消息。
自行处理 :如果您自行管理完整的输入数组,请调用 client.responses.compact()。它会返回一个较小的上下文窗口。请在下一次 responses.create() 调用中直接使用返回的输出。
请勿编辑压缩后的输出。 其中包含的是帮助模型继续工作的机器状态,而非供人阅读的摘要。请原样传递,然后添加下一条用户消息。
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 import OpenAI from "openai";
import { toResponseInputItems } from "openai/lib/responses/ResponseInputItems";
const openai = new OpenAI();
// Full window collected from a long debugging session:
// user messages, assistant outputs, tool calls, and tool outputs.
const longWindow = sessionItems;
const compacted = await openai.responses.compact({
model: "gpt-6.2-astra",
input: longWindow,
});
const nextResponse = await openai.responses.create({
model: "gpt-6.2-astra",
store: false,
input: [
// Preserve replayable compacted items.
...toResponseInputItems(compacted.output),
{
type: "message",
role: "user",
content:
"We found the bad cache invalidation path. Write the fix plan " +
"and the verification checklist.",
},
],
});
console.log(nextResponse.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 from openai import OpenAI
client = OpenAI()
# Full window collected from a long debugging session:
# user messages, assistant outputs, tool calls, and tool outputs.
long_window = session_items
compacted = client.responses.compact(
model = "gpt-6.2-astra" ,
input = long_window,
)
next_response = client.responses.create(
model = "gpt-6.2-astra" ,
store = False ,
input = [
* compacted.output, # Use compact output as-is.
{
"type" : "message" ,
"role" : "user" ,
"content" : (
"We found the bad cache invalidation path. Write the fix plan "
"and the verification checklist."
),
},
],
)
print (next_response.output_text) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51 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()
longWindow := []responses.ResponseInputItemUnionParam{
responses.ResponseInputItemParamOfMessage("Find the cache invalidation bug in this debugging session.", responses.EasyInputMessageRoleUser),
}
compacted, err := client.Responses.Compact(context.Background(), responses.ResponseCompactParams{
Model: "gpt-6.2-astra",
Input: responses.ResponseCompactParamsInputUnion{OfResponseInputItemArray: longWindow},
})
if err != nil {
panic(err)
}
input := append(outputAsInput(compacted.Output),
responses.ResponseInputItemParamOfMessage(
"We found the bad cache invalidation path. Write the fix plan and the verification checklist.",
responses.EasyInputMessageRoleUser,
),
)
nextResponse, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6.2-astra",
Store: openai.Bool(false),
Input: responses.ResponseNewParamsInputUnion{OfInputItemList: input},
})
if err != nil {
panic(err)
}
fmt.Println(nextResponse.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
41
42
43
44
45
46
47
48
49
50
51
52
53 import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.EasyInputMessage;
import com.openai.models.responses.ResponseCompactParams;
import com.openai.models.responses.ResponseCompactionItemParam;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputItem;
import java.util.ArrayList;
var compacted =
client
.responses()
.compact(
ResponseCompactParams.builder()
.model("gpt-6.2-astra")
.input("Find the cache invalidation bug in this debugging session.")
.build());
var input = new ArrayList<ResponseInputItem>();
for (var item : compacted.output()) {
item.message().map(ResponseInputItem::ofResponseOutputMessage).ifPresent(input::add);
item.reasoning().map(ResponseInputItem::ofReasoning).ifPresent(input::add);
item.compaction()
.map(
value ->
ResponseInputItem.ofCompaction(
ResponseCompactionItemParam.builder()
.id(value.id())
.encryptedContent(value.encryptedContent())
.build()))
.ifPresent(input::add);
}
input.add(
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content(
"We found the bad cache invalidation path. Write the fix plan and the verification checklist.")
.build()));
client
.responses()
.create(
ResponseCreateParams.builder()
.model("gpt-6.2-astra")
.inputOfResponse(input)
.store(false)
.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
18
19
20
21
22
23
24
25
26
27 require "openai"
client = OpenAI::Client.new
long_window = [
{
role: :user,
content: "Find the cache invalidation bug in this debugging session."
}
]
compacted = client.responses.compact(
model: "gpt-6.2-astra",
input: long_window
)
input = compacted.output.dup
input << {
role: :user,
content: "We found the bad cache invalidation path. Write the fix plan and the verification checklist."
}
response = client.responses.create(
model: "gpt-6.2-astra",
store: false,
input: input
)
puts(response.output_text)
如果多个请求复用相同的长前缀,提示词缓存 会自动降低延迟和成本。请将稳定的指令写入第一条 developer 消息,并将该消息放在 input 中。将共用的示例和参考资料放在用户特有的内容之前。保持工具定义及其顺序稳定,追加新的对话轮次时避免改写之前的上下文。
GPT-5.6 引入了显式提示词缓存。默认仍使用隐式缓存,但 GPT-5.6 及后续系列的模型也支持显式缓存断点和适用于整个请求的缓存策略。如果稳定前缀后跟着会变化的后缀,请在可复用部分的末尾显式添加 prompt_cache_breakpoint。只有当请求应仅使用您提供的断点、完全不使用隐式断点时,才将 prompt_cache_options.mode 设置为 explicit。较早的模型仍然只支持自动提示词缓存。
从 GPT-5.5 或更早的模型迁移时,请将 prompt_cache_retention 替换为 prompt_cache_options.ttl: "30m"。更改缓存设置前,请参阅不同模型的提示词缓存差异 。
在 GPT-5.6 及后续系列的模型上,写入缓存的单价为未缓存输入 Token 单价的 1.25 倍。记录 cached_tokens 和 cache_write_tokens,然后将写入量与后续缓存读取量进行比较,以衡量净成本并调整断点位置。
对于共享可复用前缀的请求,请使用稳定的 prompt_cache_key,以便将相关请求路由到同一缓存,提高 GPT-5.6 之前的模型的缓存命中率。如果某组请求流量较大,请参阅将流量分散到更多缓存键的指南 。
在 GPT-5.6 及后续模型上,prompt_cache_key 是可选的。即使不设置,也能达到最佳缓存命中率。您可以使用它按客户、用户或工作空间分别统计缓存用量,以便向各组说明其缓存 Token 用量和费用。为每个客户分配不同的键,并在该客户的相关请求中保持键不变。使用不同的键还有助于防止跨客户探测缓存命中情况。请参阅使用缓存键分别统计缓存用量 。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 import OpenAI from "openai";
const openai = new OpenAI();
const instructions = [
"You are the support agent for Acme.",
"Follow the Acme support policy and escalation rubric.",
"Use the same tone, safety rules, and tool plan for each ticket.",
].join("\n");
const response = await openai.responses.create({
model: "gpt-6.2-astra",
prompt_cache_key: "tenant-acme-support-agent",
input: [
{ role: "developer", content: instructions },
{
role: "user",
content: "Summarize the current escalation for the on-call lead.",
},
],
});
console.log(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 from openai import OpenAI
client = OpenAI()
instructions = """
You are the support agent for Acme.
Follow the Acme support policy and escalation rubric.
Use the same tone, safety rules, and tool plan for each ticket.
"""
response = client.responses.create(
model = "gpt-6.2-astra" ,
prompt_cache_key = "tenant-acme-support-agent" ,
input = [
{ "role" : "developer" , "content" : instructions},
{
"role" : "user" ,
"content" : "Summarize the current escalation for the on-call lead." ,
},
],
)
print (response.output_text) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33 package main
import (
"context"
"fmt"
"strings"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
instructions := strings.Join([]string{
"You are the support agent for Acme.",
"Follow the Acme support policy and escalation rubric.",
"Use the same tone, safety rules, and tool plan for each ticket.",
}, "\n")
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6.2-astra",
PromptCacheKey: openai.String("tenant-acme-support-agent"),
Input: responses.ResponseNewParamsInputUnion{
OfInputItemList: responses.ResponseInputParam{
responses.ResponseInputItemParamOfMessage(instructions, responses.EasyInputMessageRoleDeveloper),
responses.ResponseInputItemParamOfMessage("Summarize the current escalation for the on-call lead.", 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 import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.EasyInputMessage;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputItem;
import java.util.List;
String instructions =
"You are the support agent for Acme.\n"
+ "Follow the Acme support policy and escalation rubric.\n"
+ "Use the same tone, safety rules, and tool plan for each ticket.";
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6.2-astra")
.inputOfResponse(
List.of(
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.DEVELOPER)
.content(instructions)
.build()),
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content("Summarize the current escalation for the on-call lead.")
.build())))
.promptCacheKey("tenant-acme-support-agent")
.build();
client.responses().create(params).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text())); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
CreateResponseOptions options = new()
{
Model = "gpt-6.2-astra",
PromptCacheKey = "tenant-acme-support-agent",
};
options.InputItems.Add(ResponseItem.CreateDeveloperMessageItem("Follow the Acme support policy and escalation rubric."));
options.InputItems.Add(
ResponseItem.CreateUserMessageItem("Summarize the current escalation for the on-call lead.")
);
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 require "openai"
client = OpenAI::Client.new
instructions = <<~INSTRUCTIONS
You are the support agent for Acme.
Follow the Acme support policy and escalation rubric.
Use the same tone, safety rules, and tool plan for each ticket.
INSTRUCTIONS
response = client.responses.create(
model: "gpt-6.2-astra",
prompt_cache_key: "tenant-acme-support-agent",
input: [
{
role: :developer,
content: instructions
},
{
role: :user,
content: "Summarize the current escalation for the on-call lead."
}
]
)
puts(response.output_text)
使用 reasoning.encrypted_content
GPT-6 等支持此功能的模型可以跨调用保留推理内容 。当任务的目标、假设和优先级保持稳定时,请使用 reasoning.context: "all_turns"。如果之前的推理已不再相关,且可能让模型沿用过时的方法,请使用 current_turn。如果省略 reasoning.context 或将其设置为 auto,请检查响应中的 reasoning.context 字段,确认实际生效的模式。
保留推理内容 的前提是模型可以访问之前的推理项。对于已存储的响应,请使用 previous_response_id。如果您的零数据保留(ZDR) 要求不允许存储响应数据,可通过加密的推理内容在无状态调用之间传递信息。
响应输出中的推理项默认包含加密的推理内容。您可以从每个推理项的 encrypted_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 import OpenAI from "openai";
import { toResponseInputItems } from "openai/lib/responses/ResponseInputItems";
const openai = new OpenAI();
const history: OpenAI.Responses.ResponseInput = [
{
role: "user",
content: "Investigate why invoice INV-1043 has mismatched tax totals.",
},
];
const first = await openai.responses.create({
model: "gpt-6.2-astra",
store: false,
reasoning: { effort: "medium", context: "current_turn" },
input: history,
});
history.push(...toResponseInputItems(first.output));
history.push({
role: "user",
content: "Now write the customer-facing explanation in plain English.",
});
const second = await openai.responses.create({
model: "gpt-6.2-astra",
store: false,
reasoning: { effort: "medium", context: "all_turns" },
input: history,
});
console.log(second.output_text); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 from openai import OpenAI
client = OpenAI()
history = [
{
"role" : "user" ,
"content" : "Investigate why invoice INV-1043 has mismatched tax totals." ,
}
]
first = client.responses.create(
model = "gpt-6.2-astra" ,
store = False ,
reasoning = { "effort" : "medium" , "context" : "current_turn" },
input = history,
)
history.extend(item.to_dict() for item in first.output)
history.append(
{
"role" : "user" ,
"content" : "Now write the customer-facing explanation in plain English." ,
}
)
second = client.responses.create(
model = "gpt-6.2-astra" ,
store = False ,
reasoning = { "effort" : "medium" , "context" : "all_turns" },
input = history,
)
print (second.output_text) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55 package main
import (
"context"
"encoding/json"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
"github.com/openai/openai-go/v3/shared"
)
func main() {
client := openai.NewClient()
history := []responses.ResponseInputItemUnionParam{
responses.ResponseInputItemParamOfMessage("Investigate why invoice INV-1043 has mismatched tax totals.", responses.EasyInputMessageRoleUser),
}
first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6.2-astra",
Store: openai.Bool(false),
Reasoning: shared.ReasoningParam{Effort: shared.ReasoningEffortMedium, Context: shared.ReasoningContextCurrentTurn},
Include: []responses.ResponseIncludable{responses.ResponseIncludableReasoningEncryptedContent},
Input: responses.ResponseNewParamsInputUnion{OfInputItemList: history},
})
if err != nil {
panic(err)
}
history = append(history, outputAsInput(first.Output)...)
history = append(history, responses.ResponseInputItemParamOfMessage(
"Now write the customer-facing explanation in plain English.",
responses.EasyInputMessageRoleUser,
))
second, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6.2-astra",
Store: openai.Bool(false),
Reasoning: shared.ReasoningParam{Effort: shared.ReasoningEffortMedium, Context: shared.ReasoningContextAllTurns},
Input: responses.ResponseNewParamsInputUnion{OfInputItemList: history},
})
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62 import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.Reasoning;
import com.openai.models.responses.EasyInputMessage;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseIncludable;
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("Investigate why invoice INV-1043 has mismatched tax totals.")
.build()));
var first =
client
.responses()
.create(
ResponseCreateParams.builder()
.model("gpt-6.2-astra")
.inputOfResponse(history)
.store(false)
.reasoning(
Reasoning.builder()
.effort(com.openai.models.ReasoningEffort.MEDIUM)
.putAdditionalProperty("context", JsonValue.from("current_turn"))
.build())
.addInclude(ResponseIncludable.of("reasoning.encrypted_content"))
.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("Now write the customer-facing explanation in plain English.")
.build()));
client
.responses()
.create(
ResponseCreateParams.builder()
.model("gpt-6.2-astra")
.inputOfResponse(history)
.store(false)
.reasoning(
Reasoning.builder()
.effort(com.openai.models.ReasoningEffort.MEDIUM)
.putAdditionalProperty("context", JsonValue.from("all_turns"))
.build())
.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
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37 require "openai"
client = OpenAI::Client.new
history = [
{
role: :user,
content: "Investigate why invoice INV-1043 has mismatched tax totals."
}
]
first = client.responses.create(
model: "gpt-6.2-astra",
store: false,
reasoning: {
effort: :medium,
context: :current_turn
},
include: ["reasoning.encrypted_content"],
input: history
)
history.concat(first.output)
history << {
role: :user,
content: "Now write the customer-facing explanation in plain English."
}
second = client.responses.create(
model: "gpt-6.2-astra",
store: false,
reasoning: {
effort: :medium,
context: :all_turns
},
input: history
)
puts(second.output_text)
图像的 detail 默认为 auto,具体如何调整尺寸取决于模型。大图像可能消耗更多输入 Token,并增加延迟。请查看各模型的图像尺寸处理表 ,并在部署前使用所选模型实测图像的 Token 用量和上限。
根据任务选择 detail 。您可以调整图像尺寸,在精细的视觉细节不重要时使用 low,或在需要常规高保真图像理解时使用 high。处理大图或信息密集的图像,或执行对坐标精度要求较高的任务、OCR、定位或视觉检查时,如果模型支持 original 且额外细节有助于提高质量,请使用该设置。部署前,请测量最坏情况下的图像 Token 用量和延迟。
如果您的应用面向个人终端用户,请在每个请求中发送稳定且能保护隐私的 safety_identifier 。它有助于 OpenAI 检测滥用行为,也为您的团队提供了稳定的标识来追踪违规行为,还能降低单个用户的滥用行为影响整个组织访问服务的风险。
请发送用户名或电子邮件地址的哈希值,避免发送可识别身份的信息。对于未登录的用户,请使用稳定的会话 ID。
在设计 GPT-6 Astra 智能体工作流时,请考虑如何处理偏离预期行为的监控结果 。如果请求返回 403 并包含 misalignment_policy_violation,请停止为该对话分派操作,并且不要自动重试被阻止的工作流。也要处理流式传输期间出现的错误,并检查可能已经执行的操作。如果团队需要接收项目警报,请订阅 safety.alert.created。即使使用了 webhook,仍需处理请求错误。请查阅指南,了解哪些 Responses 请求可能被自动停止。
决定如何恢复之前,请检查 HTTP 状态码和 error.code。如果返回 429 且错误码为 slow_down,说明请求速率增长过快。如果响应中包含 Retry-After,请遵循其指定的等待时间。降低流量,然后再逐步增加。如果返回 503 且错误码为 server_is_overloaded,说明所请求的模型暂时过载。如果响应中包含 Retry-After,请等待指定时间后再重试。如果没有该响应头,请使用带随机抖动的指数退避策略,逐步延长重试间隔,并限制重试次数。对于计费、支出和配额错误,必须先解决问题才能重试。不要把所有 429 错误都当作临时速率限制。请参阅速率限制 和错误码 。
对于可能耗时较长的请求,请使用 background=True 。API 会启动作业并返回一个 ID,客户端无需保持连接。应用可以轮询该作业,直到作业完成、失败或被取消。此模式适用于大规模分析、耗时较长的工具调用,以及需要查询状态和重试的工作。
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 // Replace the illustrative IDs and URLs below with your own resource values.
import OpenAI from "openai";
const openai = new OpenAI();
const logBundleFileId = "file_123";
let job = await openai.responses.create({
model: "gpt-6.2-astra",
background: true,
store: false,
input: "Analyze this large log bundle and cluster the primary failure modes.",
tools: [
{
type: "code_interpreter",
container: {
type: "auto",
file_ids: [logBundleFileId],
},
},
],
});
while (job.status === "queued" || job.status === "in_progress") {
await new Promise((resolve) => setTimeout(resolve, 2000));
job = await openai.responses.retrieve(job.id);
}
console.log(job.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 # Replace the illustrative IDs and URLs below with your own resource values.
from openai import OpenAI
import time
client = OpenAI()
log_bundle_file_id = "file_123"
job = client.responses.create(
model = "gpt-6.2-astra" ,
background = True ,
store = False ,
input = "Analyze this large log bundle and cluster the primary failure modes." ,
tools = [
{
"type" : "code_interpreter" ,
"container" : {
"type" : "auto" ,
"file_ids" : [log_bundle_file_id],
},
}
],
)
while job.status in { "queued" , "in_progress" }:
time.sleep( 2 )
job = client.responses.retrieve(job.id)
print (job.output_text) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35 package main
import (
"context"
"fmt"
"time"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
tool := responses.ToolParamOfCodeInterpreter(responses.ToolCodeInterpreterContainerCodeInterpreterContainerAutoParam{
FileIDs: []string{"file_abc123"},
})
job, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6.2-astra",
Background: openai.Bool(true),
Store: openai.Bool(false),
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Analyze this large log bundle and cluster the primary failure modes.")},
Tools: []responses.ToolUnionParam{tool},
})
if err != nil {
panic(err)
}
for job.Status == responses.ResponseStatusQueued || job.Status == responses.ResponseStatusInProgress {
time.Sleep(2 * time.Second)
job, err = client.Responses.Get(context.Background(), job.ID, responses.ResponseGetParams{})
if err != nil {
panic(err)
}
}
fmt.Println(job.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 import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseStatus;
import com.openai.models.responses.Tool;
String fileId = "file_abc123";
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6.2-astra")
.input("Analyze this large log bundle and cluster the primary failure modes.")
.background(true)
.store(false)
.addCodeInterpreterTool(
Tool.CodeInterpreter.Container.CodeInterpreterToolAuto.builder()
.addFileId(fileId)
.build())
.build();
var response = client.responses().create(params);
while (response.status().filter(ResponseStatus.QUEUED::equals).isPresent()
|| response.status().filter(ResponseStatus.IN_PROGRESS::equals).isPresent()) {
Thread.sleep(1000);
response = client.responses().retrieve(response.id());
}
if (response.status().filter(ResponseStatus.COMPLETED::equals).isEmpty()) {
throw new IllegalStateException(
"Research ended with status: " + response.status().orElseThrow());
}
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 require "openai"
client = OpenAI::Client.new
job = client.responses.create(
model: "gpt-6.2-astra",
background: true,
store: false,
input: "Analyze this large log bundle and cluster the primary failure modes.",
tools: [
{
type: :code_interpreter,
container: {
type: :auto,
file_ids: ["file_abc123"]
}
}
]
)
while [:queued, :in_progress].include?(job.status)
sleep(2)
job = client.responses.retrieve(job.id)
end
puts(job.output_text)
您可以结合 stream=True 接收进度事件,但与普通请求相比,首个事件可能需要更长时间才会到达。
在用户界面上,后台模式可以这样呈现:“任务正在运行。这里显示当前状态,完成后结果也会显示在这里。”
WebSocket 模式 专为长时间运行且频繁调用工具的工作流设计。您可以保持持久连接,只需发送新的输入项和 previous_response_id 即可继续执行。对于包含 20 次或更多工具调用的工作流,我们观察到端到端执行速度最高可提升约 40%。
工作原理 :第一条消息与普通的 Responses 请求类似,包含模型、指令、工具和用户输入。服务器以流式方式返回事件。如果模型请求调用工具,应用就执行该工具。接下来,无需发起新的 HTTP 请求,只需通过同一个套接字发送另一个 response.create 事件,在 previous_response_id 中填入上一次响应的 ID,并附上新输入项。使用普通 HTTP 时,每次后续调用都是一个新请求。使用 WebSocket 模式时,连接保持打开,最近一次响应的状态仍保留在该连接的内存中,可立即使用。下一轮从该响应继续时,服务需要做的准备工作更少,因此延迟更低。
如果工作流是一次请求对应一个答案,请继续使用 HTTP 。如果工作流像智能体一样长时间运行,可以尝试 WebSocket 模式。
在同一连接上并行处理多个对话时,请为每个对话使用不同的 stream_id 值,并按 stream_id 分发交错到达的事件。一个连接最多支持 16 个正在执行的响应,同一数据流中的请求按顺序执行。连接最长可持续 60 分钟。继续执行时,previous_response_id 的用法与 HTTP 模式相同,连接会在本地缓存每个数据流的最新响应。
注意:WebSocket 模式支持 ZDR,因为您的数据仅保存在内存中,不会写入磁盘。
Python 示例使用 pip install "openai[realtime]>=3.8.0"。
TypeScript 示例使用 npm install openai@^7.10.0 ws。
Ruby 示例使用 gem install openai async-websocket。
对于 Go,请运行 go get github.com/openai/openai-go/v3@v3.104.0。
对于 Java,请添加 Maven 依赖项 com.openai:openai-java:4.105.0。
上述版本的 Go 和 Java SDK 均原生支持通过 WebSocket 使用 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76 import OpenAI from "openai";
import { ResponsesWS } from "openai/resources/responses/ws";
const testLogTool: OpenAI.Responses.FunctionTool = {
type: "function",
name: "search_test_logs",
description: "Search test logs for a query.",
parameters: {
type: "object",
properties: { query: { type: "string" } },
required: ["query"],
additionalProperties: false,
},
strict: true,
};
const codeSearchTool: OpenAI.Responses.FunctionTool = {
type: "function",
name: "search_code",
description: "Search the codebase for a query.",
parameters: {
type: "object",
properties: { query: { type: "string" } },
required: ["query"],
additionalProperties: false,
},
strict: true,
};
const openai = new OpenAI();
const ws = new ResponsesWS(openai);
try {
ws.send({
type: "response.create",
model: "gpt-6.2-astra",
store: false,
input: [
{
type: "message",
role: "user",
content: [
{
type: "input_text",
text:
"Find the flaky test in this run, call the tools you need, " +
"and keep going until you can explain the root cause.",
},
],
},
],
tools: [testLogTool, codeSearchTool],
});
let completed = false;
for await (const event of ws) {
if (event.type === "error") throw event.error;
if (event.type !== "message") continue;
const message = event.message;
if (message.type === "response.completed") {
console.log(JSON.stringify(message.response.output));
completed = true;
break;
}
if (
message.type === "response.failed" ||
message.type === "response.incomplete"
) {
throw new Error(JSON.stringify(message));
}
}
if (!completed) {
throw new Error("Connection closed before the response finished.");
}
} finally {
ws.close();
} 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61 from openai import OpenAI
from openai.types.responses import FunctionToolParam
test_log_tool: FunctionToolParam = {
"type" : "function" ,
"name" : "search_test_logs" ,
"description" : "Search test logs." ,
"parameters" : {
"type" : "object" ,
"properties" : { "query" : { "type" : "string" }},
"required" : [ "query" ],
"additionalProperties" : False ,
},
"strict" : True ,
}
code_search_tool: FunctionToolParam = {
"type" : "function" ,
"name" : "search_code" ,
"description" : "Search source code." ,
"parameters" : {
"type" : "object" ,
"properties" : { "query" : { "type" : "string" }},
"required" : [ "query" ],
"additionalProperties" : False ,
},
"strict" : True ,
}
client = OpenAI()
with client.responses.connect() as connection:
# Use the same typed parameters as client.responses.create(...).
connection.response.create(
model = "gpt-6.2-astra" ,
store = False ,
input = [
{
"type" : "message" ,
"role" : "user" ,
"content" : [
{
"type" : "input_text" ,
"text" : (
"Find the flaky test in this run, call the tools "
"you need, and keep going until you can explain "
"the root cause."
),
}
],
}
],
tools = [test_log_tool, code_search_tool],
)
for event in connection:
if event.type == "response.completed" :
print (event.response.output)
break
if event.type in { "response.failed" , "response.incomplete" , "error" }:
raise RuntimeError (event.to_json())
else :
raise RuntimeError ( "Connection closed before the response finished." ) 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
47
48
49
50
51
52
53
54
55
56
57 tools := []responses.ToolUnionParam{}
for _, name := range []string{
"search_test_logs",
"search_code",
} {
tools = append(tools, responses.ToolUnionParam{
OfFunction: &responses.FunctionToolParam{
Name: name,
Description: openai.String("Search for a query."),
Parameters: map[string]any{
"type": "object",
"properties": map[string]any{
"query": map[string]any{
"type": "string",
},
},
"required": []string{
"query",
},
"additionalProperties": false,
},
Strict: openai.Bool(true),
},
})
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
client := openai.NewClient()
conn, err := client.Responses.Connect(ctx, responses.ResponseConnectionOptions{})
if err != nil {
log.Fatal(err)
}
defer conn.Close()
if err := conn.Create(ctx, responses.ResponsesClientEventResponseCreateParam{
Model: "gpt-6.2-astra",
Store: openai.Bool(false),
Input: responses.ResponsesClientEventResponseCreateInputUnionParam{
OfString: openai.String("Find the flaky test in this run, call the tools you need, and keep going until you can explain the root cause."),
},
Tools: tools,
}); err != nil {
log.Fatal(err)
}
response, err := conn.FinalResponse(ctx)
if err != nil {
log.Fatal(err)
}
if response.Status != responses.ResponseStatusCompleted {
log.Fatalf("Response ended with status %s", response.Status)
}
output := make([]json.RawMessage, 0, len(response.Output))
for _, item := range response.Output {
output = append(output, json.RawMessage(item.RawJSON()))
}
if err := json.NewEncoder(os.Stdout).Encode(output); err != nil {
log.Fatal(err)
} 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.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.*;
import java.util.*;
var tools = new ArrayList<Tool>();
for (var name : List.of("search_test_logs", "search_code"))
tools.add(
Tool.ofFunction(
FunctionTool.builder()
.name(name)
.description("Search for a query.")
.strict(true)
.parameters(
FunctionTool.Parameters.builder()
.putAdditionalProperty("type", JsonValue.from("object"))
.putAdditionalProperty(
"properties",
JsonValue.from(Map.of("query", Map.of("type", "string"))))
.putAdditionalProperty("required", JsonValue.from(List.of("query")))
.putAdditionalProperty("additionalProperties", JsonValue.from(false))
.build())
.build()));
try (var conn = client.responses().connect()) {
conn.send(
ResponsesClientEvent.ofResponseCreate(
ResponsesClientEvent.ResponseCreate.builder()
.model("gpt-6.2-astra")
.store(false)
.input(
"Find the flaky test in this run, call the tools you need, and keep going until you can explain the root cause.")
.tools(tools)
.build()));
var response = conn.finalResponse();
if (response.status().filter(ResponseStatus.COMPLETED::equals).isEmpty())
throw new IllegalStateException(
"Response ended with status " + response.status().orElse(null));
System.out.println(response.output());
} 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
47
48
49
50
51
52
53
54
55
56
57
58 require "async"
require "openai"
require "json"
def wait_for_response(connection)
while (event = connection.receive)
case event.type.to_s
when "response.completed" then return event.response
when "response.failed", "response.incomplete", "error"
raise "Response failed: #{event.to_json}"
end
end
raise "Connection closed before the response finished"
end
test_log_tool = {
type: "function",
name: "search_test_logs",
description: "Search test logs.",
parameters: {
type: "object",
properties: { query: { type: "string" } },
required: ["query"],
additionalProperties: false
},
strict: true
}
code_search_tool = {
type: "function",
name: "search_code",
description: "Search source code.",
parameters: {
type: "object",
properties: { query: { type: "string" } },
required: ["query"],
additionalProperties: false
},
strict: true
}
client = OpenAI::Client.new
Sync do |task|
task.with_timeout(120) do
client.responses.connect(request_options: { timeout: 10 }) do |connection|
connection.response.create(
stream_id: "main", model: "gpt-6.2-astra", store: false,
input: [
{
role: "user",
content: "Find the flaky test in this run, call the tools you need, and keep going until you can explain the root cause."
}
],
tools: [test_log_tool, code_search_tool]
)
puts(JSON.pretty_generate(wait_for_response(connection).output.map(&:to_h)))
end
end
end
如果用户可能在 GPT-6 模型工作期间补充要求,请通过 WebSocket 连接到 Responses API。发送 response.steer,在 previous_response_id 中填入当前正在执行的响应 ID,并附上新的用户输入。继续读取后续执行过程中产生的事件。收到 response.steer.accepted 表示更新已进入队列。中途调整方向不会更改已发送到应用的输出,也不会撤销已启动的工具调用。有关事件流程和工具结果的处理方式,请参阅在当前轮次中途调整方向 。
Responses API 是构建更智能、功能更强的 OpenAI 应用的基础。开发者可以从一次性提示词入手,进而构建能持续运行、调用工具并利用上下文的工作流,让工作流适应任务的复杂程度。按照本指南选择适合您工作负载的设计,可以提升实际部署中的性能。