会话会持续保留智能体的配置、对话和已保存的工作内容。复用同一会话,即可发送后续消息并继续工作。
轮次是会话中的一个工作周期。向空闲会话发送消息会启动新轮次。在轮次进行期间发送消息,则会引导该轮次的工作。
轮次以异步方式运行。您的应用可以通过流式传输跟踪进度,也可以通过 Webhook 接收会话状态变更通知。
使用智能体配置和初始 input 创建会话。将 stream 设为 true,即可在同一请求中接收首个轮次的事件。
配置好 API 密钥和 SDK 后,运行以下示例以创建并运行脚本。其运行环境由 OpenAI 管理:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20import OpenAI from "openai";
const client = new OpenAI();
const events = await client.beta.agents.sessions.create({
agent: {
model: "gpt-6-astra",
instructions: "Write clean code, run it, and report the actual output.",
},
environment: { type: "openai_hosted" },
input:
"Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output.",
stream: true,
});
try {
for await (const event of events) {
console.log(JSON.stringify(event));
}
} finally {
events.controller.abort();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14from openai import OpenAI
with OpenAI() as client:
with client.beta.agents.sessions.create(
agent={
"model": "gpt-6-astra",
"instructions": "Write clean code, run it, and report the actual output.",
},
environment={"type": "openai_hosted"},
input="Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output.",
stream=True,
) as events:
for event in events:
print(event.to_json(indent=None), flush=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
30import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
)
ctx := context.Background()
client := openai.NewClient()
events := client.Beta.Agents.Sessions.NewStreaming(ctx, openai.BetaAgentSessionNewParams{
Agent: openai.BetaAgentSessionNewParamsAgent{
Model: openai.String("gpt-6-astra"),
Instructions: openai.String("Write clean code, run it, and report the actual output."),
},
Environment: openai.EnvironmentParamUnion{OfParamOpenAIHosted: &openai.EnvironmentParamOpenAIHosted{}},
Input: openai.BetaAgentSessionNewParamsInputUnion{
OfString: openai.String("Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output."),
},
})
defer events.Close()
if events.Err() != nil {
panic(events.Err())
}
for events.Next() {
event := events.Current()
fmt.Println(event.RawJSON())
}
if err := events.Err(); err != nil {
panic(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
33import com.fasterxml.jackson.databind.json.JsonMapper;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.StreamResponse;
import com.openai.models.beta.agents.AgentSessionEvent;
import com.openai.models.beta.agents.EnvironmentParam;
import com.openai.models.beta.agents.sessions.SessionCreateParams;
OpenAIClient client = OpenAIOkHttpClient.fromEnv();
var json = new JsonMapper();
try (StreamResponse<AgentSessionEvent> events =
client
.beta()
.agents()
.sessions()
.createStreaming(
SessionCreateParams.builder()
.agent(
SessionCreateParams.Agent.builder()
.model("gpt-6-astra")
.instructions("Write clean code, run it, and report the actual output.")
.build())
.environment(EnvironmentParam.OpenAIHosted.builder().build())
.input(
"Create tree.py, a Python script that prints a readable tree of the files"
+ " in the current directory. Run it and show me the output.")
.build())) {
var iterator = events.stream().iterator();
while (iterator.hasNext()) {
var event = iterator.next();
System.out.println(json.writeValueAsString(event));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19require "openai"
require "json"
client = OpenAI::Client.new
events = client.beta.agents.sessions.create_streaming(
agent: {
model: "gpt-6-astra",
instructions: "Write clean code, run it, and report the actual output."
},
environment: { type: "openai_hosted" },
input: "Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output."
)
begin
events.each do |event|
puts JSON.generate(event.to_h)
end
ensure
events.close
end
1
2
3
4
5
6
7
8
9
10
11
12
13curl --no-buffer --fail-with-body https://api.openai.com/v1/agents/sessions \
-H "OpenAI-Beta: agents=v1" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"agent": {
"model": "gpt-6-astra",
"instructions": "Write clean code, run it, and report the actual output."
},
"environment": { "type": "openai_hosted" },
"input": "Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output.",
"stream": true
}'
将 session_id 与您应用的对话状态一同存储。使用它发送后续消息,并获取该对话中已保存的工作内容。
有关可复用的智能体设置,请参阅配置智能体;有关环境选择,请参阅架构。使用 environment.type: "none" 的会话必须提供初始输入。创建会话参考资料列出了请求字段。
智能体工作时,事件会报告输出和变化。请检查轮次的结果:完成、失败或取消。会话处于空闲状态本身并不意味着该轮次成功。
请关注 agent.session.turn.completed、agent.session.turn.failed 或 agent.session.turn.cancelled。同时也要检查智能体的输出:轮次完成并不保证每个工具都执行成功。
如果会话需要函数结果或环境连接,请获取该会话并检查 required_actions。您的代码必须处理函数调用或连接环境,工作才能继续。
有关事件类型和载荷,请参阅事件和条目。
向同一会话再发送一条 agent.session.input.message。如果智能体正在工作,这条消息会引导当前轮次。如果会话处于空闲状态,则会基于现有对话启动新轮次。
对已保存智能体的更新仅适用于新会话。要更改本会话后续轮次使用的模型、推理强度或服务层级,请更新此会话的设置。
使用该对话的会话 ID 发送输入。请在发送消息之前订阅其事件流,以便您的应用接收该轮次早期的事件。
将您的 API 客户端、会话 ID 和消息传递给应用中的函数:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21// Pass your saved session ID and message to this helper.
async function sendMessage(client, sessionId, text) {
await client.beta.agents.sessions.events.create(sessionId, {
events: [
{
type: "agent.session.input.message",
input: [
{
role: "user",
content: [
{
type: "input_text",
text,
},
],
},
],
},
],
});
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21# Pass your saved session ID and message to this helper.
def send_message(client: OpenAI, session_id: str, text: str) -> None:
client.beta.agents.sessions.events.create(
session_id,
events=[
{
"type": "agent.session.input.message",
"input": [
{
"role": "user",
"content": [
{
"type": "input_text",
"text": text,
}
],
}
],
}
],
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22// Pass your saved session ID and message to this helper.
func sendMessage(ctx context.Context, client *openai.Client, sessionID, text string) error {
return client.Beta.Agents.Sessions.Events.New(ctx,
sessionID,
openai.BetaAgentSessionEventNewParams{
Events: []openai.AgentSessionInputParamUnion{
{
OfParamAgentSessionInputMessage: &openai.AgentSessionInputParamAgentSessionInputMessage{
Input: []openai.AgentSessionInputMessageParam{
{
Content: []openai.InputContentParamUnion{
{
OfParamInputText: &openai.InputContentParamInputText{Text: text},
},
},
},
},
},
},
},
})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19// Pass your saved session ID and message to this helper.
public static void sendMessage(OpenAIClient client, String sessionId, String text) {
client
.beta()
.agents()
.sessions()
.events()
.create(
EventCreateParams.builder()
.sessionId(sessionId)
.addEvent(
AgentSessionInputParam.AgentSessionInputMessage.builder()
.addInput(
AgentSessionInputMessageParam.builder()
.addInputTextContent(text)
.build())
.build())
.build());
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22# Pass your saved session ID and message to this helper.
def send_message(client, session_id, text)
client.beta.agents.sessions.events.create(
session_id,
events: [
{
type: "agent.session.input.message",
input: [
{
role: "user",
content: [
{
type: "input_text",
text: text
}
]
}
]
}
]
)
end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23curl \
"https://api.openai.com/v1/agents/sessions/$session_id/events" \
-H "OpenAI-Beta: agents=v1" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"events": [
{
"type": "agent.session.input.message",
"input": [
{
"role": "user",
"content": [
{
"type": "input_text",
"text": "List the files in the current directory."
}
]
}
]
}
]
}'
有关将发送消息与流式接收事件结合使用的示例,请参阅事件和条目。
事件显示实时进度。条目则是已保存的消息和工具调用,其中包括已完成的响应。获取这些条目,即可显示之前的工作内容,或在轮次结束后检查结果:
1
2
3
4
5
6
7// Pass your saved session ID to this helper.
async function listItems(client, sessionId) {
return client.beta.agents.sessions.items.list(sessionId, {
order: "asc",
limit: 100,
});
}
1
2
3# Pass your saved session ID to this helper.
def list_items(client: OpenAI, session_id: str):
return client.beta.agents.sessions.items.list(session_id, order="asc", limit=100)
1
2
3
4
5
6
7
8
9// Pass your saved session ID to this helper.
func listItems(ctx context.Context, client *openai.Client, sessionID string) (*pagination.CursorPage[openai.AgentSessionItemUnion], error) {
return client.Beta.Agents.Sessions.Items.List(ctx,
sessionID,
openai.BetaAgentSessionItemListParams{
Order: "asc",
Limit: openai.Int(100),
})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14// Pass your saved session ID to this helper.
public static ItemListPage listItems(OpenAIClient client, String sessionId) {
return client
.beta()
.agents()
.sessions()
.items()
.list(
ItemListParams.builder()
.sessionId(sessionId)
.order(ItemListParams.Order.of("asc"))
.limit(100L)
.build());
}
1
2
3
4
5
6
7
8# Pass your saved session ID to this helper.
def list_items(client, session_id)
client.beta.agents.sessions.items.list(
session_id,
order: "asc",
limit: 100
)
end
1
2
3
4curl \
"https://api.openai.com/v1/agents/sessions/$session_id/items?order=asc&limit=100" \
-H "OpenAI-Beta: agents=v1" \
-H "Authorization: Bearer $OPENAI_API_KEY"
请参阅管理会话,了解如何检查会话状态和轮次结果。请参阅文件和产物,了解如何获取文件。
事件流不会重放错过的事件。连接断开后,请获取会话及其已保存的条目,以恢复工作内容。有关重新连接的步骤,请参阅恢复断开的事件流。
当您希望智能体停止工作时,请取消当前轮次。会话及其之前的工作内容仍然可用:
1
2
3
4
5
6// Pass your saved session ID to this helper.
async function cancelTurn(client, sessionId) {
await client.beta.agents.sessions.events.create(sessionId, {
events: [{ type: "agent.session.input.cancel" }],
});
}
1
2
3
4
5# Pass your saved session ID to this helper.
def cancel_turn(client: OpenAI, session_id: str) -> None:
client.beta.agents.sessions.events.create(
session_id, events=[{"type": "agent.session.input.cancel"}]
)
1
2
3
4
5
6
7
8
9
10// Pass your saved session ID to this helper.
func cancelTurn(ctx context.Context, client *openai.Client, sessionID string) error {
return client.Beta.Agents.Sessions.Events.New(ctx,
sessionID,
openai.BetaAgentSessionEventNewParams{
Events: []openai.AgentSessionInputParamUnion{
{OfParamAgentSessionInputCancel: &openai.AgentSessionInputParamAgentSessionInputCancel{}},
},
})
}
1
2
3
4
5
6
7
8
9
10
11
12
13// Pass your saved session ID to this helper.
public static void cancelTurn(OpenAIClient client, String sessionId) {
client
.beta()
.agents()
.sessions()
.events()
.create(
EventCreateParams.builder()
.sessionId(sessionId)
.addEventAgentSessionInputCancel()
.build());
}
1
2
3
4
5
6
7# Pass your saved session ID to this helper.
def cancel_turn(client, session_id)
client.beta.agents.sessions.events.create(
session_id,
events: [{ type: "agent.session.input.cancel" }]
)
end
1
2
3
4
5curl "https://api.openai.com/v1/agents/sessions/$session_id/events" \
-H "OpenAI-Beta: agents=v1" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"events":[{"type":"agent.session.input.cancel"}]}'