用户可以在响应过程中补充要求或调整方向,无需等待响应结束。
通过 WebSocket 连接到 Responses API 时,GPT-6 系列模型支持在响应过程中调整方向。GPT-5.6 及更早的模型不支持此功能。
调整方向不会改写已发送到您应用的输出,也不会撤销先前的操作或取消已经开始执行的工具调用。
Java 示例需要 Java 17 或更高版本。有关连接设置和传输机制的说明,请参阅 WebSocket 模式。有关各事件的准确定义,请参阅 Responses WebSocket 事件参考。
使用 response.create 发起响应。收到该响应的 response.created 事件后,在同一连接上发送 response.steer,并将该响应的 ID 用作 previous_response_id:
12345{
"type": "response.steer",
"previous_response_id": "resp_1",
"input": "Keep the scope small enough for one developer to finish in two weeks."
}
该事件仅接受 type、previous_response_id 和 input 三个字段。将 input 设为字符串,或设为由用户消息组成的非空数组。数组中的消息必须使用受支持的内容类型。
API 通过 response.steer.accepted 确认输入已加入队列:
12345678{
"type": "response.steer.accepted",
"sequence_number": 4,
"steer": {
"id": "steer_0123456789abcdef0123456789abcdef",
"previous_response_id": "resp_1"
}
}
此事件仅确认输入已加入队列,模型可能尚未据此采取行动。除非还需要您的应用返回工具结果或审批结果,否则 API 会自动根据您的更新创建新响应。
在自动创建后续响应之前,服务器会先完成当前输出项以及已经开始执行的托管工具任务。请继续读取事件,以接收包含此次更新的响应。不要再次发送 response.create。
如果引导消息中断了原始响应,该响应将以 response.incomplete 事件结束,并带有 incomplete_details.reason: "steered"。如果原始响应先正常结束,它会保持已完成状态,API 仍可根据引导消息创建后续响应。
自动创建的后续响应会继承原始请求的设置。每个响应都有各自的 Token 限额和工具调用次数限制。
.NET SDK 未提供 Responses WebSocket 客户端,因此本示例没有 C# SDK 版本。
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
77
78
79
80
81
82
83
84// Set OPENAI_API_KEY before running this example.
// Install the SDK and WebSocket transport: npm install openai ws
import OpenAI from "openai";
import { ResponsesWS } from "openai/resources/responses/ws";
const client = new OpenAI();
const ws = new ResponsesWS(client, {
handshakeTimeout: 10_000,
});
let initialResponseId = "";
let successorResponseId = "";
let timeout;
try {
const output = await new Promise((resolve, reject) => {
timeout = setTimeout(() => {
reject(new Error("Timed out waiting for the steered response."));
ws.close();
}, 120_000);
ws.once("error", reject);
ws.once("close", () => {
reject(
new Error("Connection closed before the steered response finished.")
);
});
ws.on("event", (event) => {
try {
if (event.type === "response.created") {
if (!initialResponseId) {
initialResponseId = event.response.id;
// Simulate a user adding instructions while the response runs.
ws.send({
type: "response.steer",
previous_response_id: initialResponseId,
input:
"Keep the scope small enough for one developer to finish in two weeks.",
});
} else {
successorResponseId = event.response.id;
}
} else if (
["response.steer.failed", "response.failed", "error"].includes(
event.type
)
) {
reject(new Error(JSON.stringify(event)));
} else if (
event.type === "response.incomplete" &&
(event.response.id !== initialResponseId ||
event.response.incomplete_details?.reason !== "steered")
) {
reject(new Error(JSON.stringify(event)));
} else if (
event.type === "response.completed" &&
event.response.id === successorResponseId
) {
let text = "";
for (const item of event.response.output) {
if (item.type !== "message") continue;
for (const part of item.content) {
if (part.type === "output_text") text += part.text;
}
}
resolve(text);
}
// Acceptance only queues the input. Keep reading past the first response.
} catch (error) {
reject(error);
}
});
ws.send({
type: "response.create",
store: false,
model: "gpt-6-astra",
reasoning: { effort: "medium" },
input: "Draft a project plan for building a task-tracking app.",
});
});
console.log(output);
} finally {
clearTimeout(timeout);
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
53import asyncio
from openai import AsyncOpenAI
async def main():
client = AsyncOpenAI()
initial_response_id = None
successor_response_id = None
async with client.responses.connect() as connection:
await connection.response.create(
model="gpt-6-astra",
store=False,
reasoning={"effort": "medium"},
input="Draft a project plan for building a task-tracking app.",
)
async for event in connection:
if event.type == "response.created":
if initial_response_id is None:
initial_response_id = event.response.id
# Simulate a user adding instructions while the response runs.
await connection.response.steer(
previous_response_id=initial_response_id,
input="Keep the scope small enough for one developer to finish in two weeks.",
)
else:
successor_response_id = event.response.id
elif event.type in {"response.steer.failed", "response.failed", "error"}:
raise RuntimeError(event.to_json())
elif event.type == "response.incomplete":
response = event.response
if (
response.id != initial_response_id
or response.incomplete_details is None
or response.incomplete_details.reason != "steered"
):
raise RuntimeError(event.to_json())
elif (
event.type == "response.completed"
and event.response.id == successor_response_id
):
print(event.response.output_text)
return
# Acceptance only queues the input. Keep reading past the first response.
raise RuntimeError("Connection closed before the steered response finished.")
async def run():
await asyncio.wait_for(main(), timeout=120)
asyncio.run(run())
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
61ctx, 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-astra",
Reasoning: shared.ReasoningParam{
Effort: shared.ReasoningEffortMedium,
},
Store: openai.Bool(false),
Input: responses.ResponsesClientEventResponseCreateInputUnionParam{
OfString: openai.String("Draft a project plan for building a task-tracking app."),
},
}); err != nil {
log.Fatal(err)
}
initialID, successorID := "", ""
for {
event, err := conn.Recv(ctx)
if err != nil {
log.Fatal(err)
}
switch event.Type {
case "response.created":
id := event.OfResponsesServerEventResponseWsCreated.Response.ID
if initialID == "" {
initialID = id
err := conn.Send(ctx, responses.ResponsesClientEventUnionParam{
OfResponseSteer: &responses.ResponseSteerEventParam{
PreviousResponseID: id,
Input: responses.ResponseSteerInputUnionParam{
OfString: openai.String("Keep the scope small enough for one developer to finish in two weeks."),
},
},
})
if err != nil {
log.Fatal(err)
}
} else {
successorID = id
}
case "response.steer.failed", "response.failed", "error":
log.Fatal(event.RawJSON())
case "response.incomplete":
r := event.OfResponsesServerEventResponseWsIncomplete.Response
if r.ID != initialID || r.IncompleteDetails.Reason != "steered" {
log.Fatal(event.RawJSON())
}
case "response.completed":
r := event.OfResponsesServerEventResponseWsCompleted.Response
if successorID != "" && r.ID == successorID {
fmt.Println(r.OutputText())
return
}
}
// Steering acceptance only queues input. Wait for the successor to complete.
}
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
67import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.*;
import java.util.*;
var client = OpenAIOkHttpClient.fromEnv();
long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(120);
try (var conn =
client.async().responses().connect().get(10, java.util.concurrent.TimeUnit.SECONDS)) {
conn.send(
ResponsesClientEvent.ofResponseCreate(
ResponsesClientEvent.ResponseCreate.builder()
.model("gpt-6-astra")
.reasoning(
com.openai.models.Reasoning.builder()
.effort(com.openai.models.ReasoningEffort.MEDIUM)
.build())
.store(false)
.input("Draft a project plan for building a task-tracking app.")
.build()));
String initialId = null, successorId = null;
while (true) {
var event =
conn.receive()
.get(
Math.max(1, deadline - System.nanoTime()),
java.util.concurrent.TimeUnit.NANOSECONDS);
if (event.responseCreated().isPresent()) {
var id = event.responseCreated().orElseThrow().response().id();
if (initialId == null) {
initialId = id;
conn.send(
ResponsesClientEvent.ofResponseSteer(
ResponseSteerEvent.builder()
.previousResponseId(id)
.input(
"Keep the scope small enough for one developer to finish in two weeks.")
.build()));
} else {
successorId = id;
}
} else if (event.responseSteerFailed().isPresent()
|| event.responseFailed().isPresent()
|| event.error().isPresent()) {
throw new IllegalStateException(event.toString());
} else if (event.responseIncomplete().isPresent()) {
var response = event.responseIncomplete().orElseThrow().response();
if (!response.id().equals(initialId)
|| !response
.incompleteDetails()
.flatMap(Response.IncompleteDetails::reason)
.map(r -> r.toString().equals("steered"))
.orElse(false)) throw new IllegalStateException(event.toString());
} else if (event.responseCompleted().isPresent()
&& event.responseCompleted().orElseThrow().response().id().equals(successorId)) {
event.responseCompleted().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()));
break;
}
// Acceptance only queues input; follow the successor through completion.
}
} finally {
client.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
45require "async"
require "openai"
client = OpenAI::Client.new
Sync do |task|
task.with_timeout(120) do
client.responses.connect(request_options: { timeout: 10 }) do |connection|
connection.response.create(
model: "gpt-6-astra", store: false, reasoning: { effort: "medium" },
input: "Draft a project plan for building a task-tracking app."
)
state = {}
while (event = connection.receive)
case event
when OpenAI::Responses::ResponseCreatedEvent
response = event.response
if !state[:initial_id]
state[:initial_id] = response.id
connection.send_event(
type: "response.steer", previous_response_id: state[:initial_id],
input: "Keep the scope small enough for one developer to finish in two weeks."
)
else
state[:successor_id] = response.id
end
when OpenAI::Responses::ResponseSteerFailedEvent, OpenAI::Responses::ResponseFailedEvent, OpenAI::Responses::ResponsesServerEvent::ResponseWsError
raise "Steering failed: #{event.to_json}"
when OpenAI::Responses::ResponseIncompleteEvent
response = event.response
unless response.id == state[:initial_id] && response.incomplete_details&.reason.to_s == "steered"
raise "Response incomplete: #{event.to_json}"
end
when OpenAI::Responses::ResponseCompletedEvent
response = event.response
next unless state[:successor_id] && response.id == state[:successor_id]
puts(response.output_text)
state[:completed] = true
break
end
end
raise "Connection closed before the steered response finished" unless state[:completed]
end
end
end
本示例在收到第一个 response.created 事件后发送更新。在您的应用中,请在用户提供更新时发送。收到后续响应的 response.created 事件后,即可使用该响应的 ID 发送新的引导消息。
如果响应需要客户端返回工具结果或审批结果,API 会将引导消息保留在队列中。请在同一连接上继续执行常规的工具调用或审批流程。
例如,原始响应可以在完成时返回对 get_project_status 的调用。以下事件载荷仅列出相关字段:
123456789101112131415{
"type": "response.completed",
"response": {
"id": "resp_1",
"status": "completed",
"output": [
{
"type": "function_call",
"call_id": "call_project",
"name": "get_project_status",
"arguments": "{\"project\":\"task-tracker\"}"
}
]
}
}
原始响应完成后,如果已接受的引导消息仍需等待其他输入,API 会发送 response.steer.pending 事件。事件的 required_input 字段会列出 API 在应用更新前需要收到的工具结果或审批结果:
12345678910111213141516{
"type": "response.steer.pending",
"sequence_number": 12,
"steer": {
"id": "steer_0123456789abcdef0123456789abcdef",
"previous_response_id": "resp_1"
},
"reason": "waiting_for_required_input",
"required_input": [
{
"type": "function_call_output",
"call_id": "call_project",
"name": "get_project_status"
}
]
}
在同一连接上使用 response.create 返回所需输入,并将 previous_response_id 设为 resp_1。不要重复发送已被接受的引导消息。显式发送的 response.create 使用该请求自身的工具、指令和其他设置。
以下 JSONC 示例中的注释标出了服务器插入已排队更新的位置:
123456789101112131415161718{
"type": "response.create",
"model": "gpt-6-astra",
"previous_response_id": "resp_1",
"input": [
// The server implicitly prepends your accepted steer here:
// "Keep the scope small enough for one developer to finish in two weeks."
{
"type": "function_call_output",
"call_id": "call_project",
"output": "Design is complete. Development has not started.",
},
{
"role": "user",
"content": "Show me the updated plan before starting any work.",
},
],
}
返回工具结果时,无需等待 response.steer.pending。如果服务器已收到匹配的 response.create,它可以直接继续处理,无需先发送此通知。
response.steer.failed 表示 API 未能通过引导消息应用此次输入,之后也不会自动应用。该事件会返回原始的 input 和 previous_response_id,这两个字段位于 steer 对象中。事件还包含一个 error 对象,用于说明失败原因。
使用 steer.id 跟踪已被接受的引导消息。如果后续处理失败,失败事件会使用相同的 ID。
常见错误代码:
invalid_input:请仅使用受支持的事件字段,并以用户消息作为输入。
steering_not_supported:模型或请求参数可能不支持在响应过程中调整方向,也可能两者都不支持。
response_not_found:目标响应必须仍可在同一 WebSocket 连接上访问。
too_many_pending_steers:待处理的引导消息过多。如果需要返回工具结果或审批结果,请使用 response.create 返回。否则,请等到 API 自动创建后续响应后再提交新的引导消息。不要重新发送已被接受的引导消息。
队列中的引导输入仅存在于当前连接中,不会随原始响应一起保存。请记录您发送的引导输入,并在重新发送之前与响应事件和历史记录核对。不要假定断线后待处理的引导输入仍然存在。请参阅 WebSocket 连接恢复指南。