工作階段會持續保留智慧體的組態、對話和已儲存的工作成果。重複使用同一個工作階段,即可傳送後續訊息並繼續工作。
回合是工作階段中的一次工作週期。向閒置的工作階段傳送訊息會開始新回合;在回合進行期間傳送訊息,則會引導該回合的工作方向。
回合以非同步方式執行。應用程式可以透過串流追蹤進度,或透過 Webhooks 接收工作階段狀態的變更。
使用智慧體組態和初始 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 與應用程式的對話狀態一併儲存。使用此 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"}]}'