使用 webhooks 回應工作階段的狀態變更,無須持續開啟事件串流。Webhook 處理常式可以啟動或重新連線至沙盒運算資源、更新應用程式,或觸發工作流程。
| 事件 | 觸發時機 |
|---|
agent.session.created | 工作階段建立時。 |
agent.session.action_required | 工作階段需要函式結果、首次連線至環境,或重新連線時。 |
agent.session.in_progress | 工作階段開始處理一個回合時。 |
agent.session.idle | 工作階段處於閒置狀態,且已準備好接收更多輸入時。 |
agent.session.failed | 工作階段進入失敗狀態時。 |
agent.session.action_required 事件包含工作階段 ID,以及
值為 function_call 或 environment_connection 的 required_action.type。
1234567{
"type": "agent.session.action_required",
"data": {
"id": "sess_abc123",
"required_action": { "type": "function_call" }
}
}
擷取工作階段並檢查 required_actions,以取得呼叫 ID、引數或
環境 ID。Webhook 不包含這些詳細資訊。
按照共用的 webhook 設定指南建立端點,並選取 Agents API 事件。儲存端點的簽署密鑰,以便進行簽章驗證。
每當訂閱的事件發生時,OpenAI 都會傳送已簽署的 HTTP POST 請求:
1234567891011121314{
"id": "evt_123",
"object": "event",
"created_at": 1750287018,
"type": "agent.session.created",
"data": {
"id": "sess_abc123",
"environment_id": "ccarenv_abc123",
"environment_type": "self_hosted",
"connect": {
"remote_url": "https://api.openai.com/v1/agents/api"
}
}
}
佈建沙盒前,請先擷取工作階段的目前狀態。請參閱沙盒生命週期。
對於自行託管的工作階段,agent.session.created 包含啟動執行器所需的環境 ID 和連線 URL。將 ENVIRONMENT_ID 設為 data.environment_id,並將 REMOTE_URL 設為 data.connect.remote_url。這個 URL 與工作階段中 environment.remote_url 傳回的 URL 相同。請儲存這兩個值,並在重新連線時重複使用:
1234CODEX_API_KEY="$OPENAI_ENVIRONMENT_KEY" \
codex exec-server \
--remote "$REMOTE_URL" \
--environment-id "$ENVIRONMENT_ID"
使用環境金鑰作為 CODEX_API_KEY。請將應用程式的 API 金鑰保存在環境之外。
設定 OPENAI_API_KEY 和 OPENAI_WEBHOOK_SECRET。若使用 Python,請安裝 fastapi、uvicorn 和 openai。若使用 JavaScript,請安裝 express 和 openai。
處理常式會驗證簽章,並監聽連接埠 8000。設定 PORT 即可變更連接埠。在正式環境中,請將耗時較長的工作排入佇列。
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 express from "express";
import OpenAI from "openai";
const app = express();
const webhooks = new OpenAI({
webhookSecret: process.env.OPENAI_WEBHOOK_SECRET,
});
app.post(
"/webhooks/openai",
express.raw({ type: "application/json" }),
async (request, response) => {
const payload = request.body.toString("utf8");
try {
await webhooks.webhooks.verifySignature(payload, request.headers);
} catch {
response.status(400).send("Invalid signature");
return;
}
const event = JSON.parse(payload);
if (event.type === "agent.session.idle") {
const session = await webhooks.beta.agents.sessions.retrieve(
event.data.id
);
console.log("session idle event:", session.id);
} else {
console.log("session event:", event.type, event.data.id);
}
response.sendStatus(200);
}
);
app.listen(Number(process.env.PORT ?? 8000));
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
31import json
import os
import uvicorn
from fastapi import FastAPI, Request, Response
from openai import AsyncOpenAI, InvalidWebhookSignatureError
app = FastAPI()
webhooks = AsyncOpenAI(webhook_secret=os.environ["OPENAI_WEBHOOK_SECRET"])
@app.post("/webhooks/openai")
async def handle_webhook(request: Request):
payload = await request.body()
try:
webhooks.webhooks.verify_signature(payload=payload, headers=request.headers)
except (InvalidWebhookSignatureError, ValueError):
return Response("Invalid signature", status_code=400)
event = json.loads(payload)
if event["type"] == "agent.session.idle":
session_id = event["data"]["id"]
session = await webhooks.beta.agents.sessions.retrieve(session_id, timeout=10)
print("session idle event:", session.id)
else:
print("session event:", event["type"], event["data"]["id"])
return Response(status_code=200)
if __name__ == "__main__":
uvicorn.run(app, port=int(os.environ.get("PORT", "8000")))
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
54import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"github.com/openai/openai-go/v3"
)
client := openai.NewClient()
http.HandleFunc("/webhooks/openai", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Invalid body", http.StatusBadRequest)
return
}
if err := client.Webhooks.VerifySignature(body, r.Header); err != nil {
http.Error(w, "Invalid signature", http.StatusBadRequest)
return
}
var event struct {
Type string `json:"type"`
Data struct {
ID string `json:"id"`
} `json:"data"`
}
if err := json.Unmarshal(body, &event); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
if event.Type == "agent.session.idle" {
session, err := client.Beta.Agents.Sessions.Get(r.Context(), event.Data.ID)
if err != nil {
http.Error(w, "Could not retrieve session", http.StatusInternalServerError)
return
}
fmt.Println("session idle event:", session.ID)
} else {
fmt.Println("session event:", event.Type, event.Data.ID)
}
w.WriteHeader(http.StatusOK)
})
port := os.Getenv("PORT")
if port == "" {
port = "8000"
}
if err := http.ListenAndServe(":"+port, nil); 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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56import com.fasterxml.jackson.databind.json.JsonMapper;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.Headers;
import com.openai.errors.InvalidWebhookSignatureException;
import com.openai.models.webhooks.WebhookVerificationParams;
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
OpenAIClient client = OpenAIOkHttpClient.fromEnv();
var json = new JsonMapper();
int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "8000"));
var server = HttpServer.create(new InetSocketAddress(port), 0);
server.createContext(
"/webhooks/openai",
exchange -> {
try (exchange) {
if (!exchange.getRequestMethod().equals("POST")) {
exchange.sendResponseHeaders(405, -1);
return;
}
String payload =
new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
try {
client
.webhooks()
.verifySignature(
WebhookVerificationParams.builder()
.payload(payload)
.headers(Headers.builder().putAll(exchange.getRequestHeaders()).build())
.build());
} catch (InvalidWebhookSignatureException e) {
exchange.sendResponseHeaders(400, -1);
return;
}
var event = json.readTree(payload);
if (event.path("type").asText().equals("agent.session.idle")) {
var session =
client
.beta()
.agents()
.sessions()
.retrieve(event.path("data").path("id").asText());
System.out.println("session idle event: " + session.id());
} else {
System.out.println(
"session event: "
+ event.path("type").asText()
+ " "
+ event.path("data").path("id").asText());
}
exchange.sendResponseHeaders(200, -1);
}
});
server.start();
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
30require "openai"
require "webrick"
require "json"
client = OpenAI::Client.new
server = WEBrick::HTTPServer.new(Port: Integer(ENV.fetch("PORT", "8000")))
server.mount_proc "/webhooks/openai" do |request, response|
if request.request_method != "POST"
response.status = 405
next
end
payload = request.body
begin
client.webhooks.verify_signature(payload, request.header.transform_values(&:first))
rescue OpenAI::Errors::InvalidWebhookSignatureError
response.status = 400
response.body = "Invalid signature"
next
end
event = JSON.parse(payload)
if event["type"] == "agent.session.idle"
session = client.beta.agents.sessions.retrieve(event.fetch("data").fetch("id"))
puts "session idle event: #{session.id}"
else
puts "session event: #{event["type"]} #{event.dig("data", "id")}"
end
response.status = 200
end
trap("INT") { server.shutdown }
server.start
當初始或後續輸入需要使用尚未連線的自行託管執行器時,API 會新增一項 environment_connection 必要動作,並在 開始等待連線之前 發出 agent.session.action_required。
擷取工作階段,並確認 required_actions 仍要求建立連線。使用 session.environment.id 和 session.environment.remote_url 啟動執行器。此 webhook 不包含 connect.remote_url。如果執行器在等待逾時前連線,API 就會清除該必要動作,並繼續處理已提交的輸入,無須用戶端重新提交。
API 最多會等待五分鐘以建立連線。在等待期間,後續輸入請求可能會保持開啟狀態。請據此設定用戶端和 Proxy 的逾時時間。agent.session.in_progress 表示執行已開始,而非 API 正在等待連線。
如果等待逾時,提交就會失敗。初始輸入可能以非同步方式失敗,導致工作階段停留在 failed 狀態。等待連線的機制並不提供可持久保存的輸入佇列。如果程序當機或用戶端中斷連線,可能需要重試。
agent.session.idle 表示工作階段已準備好接收更多輸入,並不代表上一個回合成功。請檢查該回合的狀態,或觀察工作階段串流中的 agent.session.turn.completed、agent.session.turn.failed 或 agent.session.turn.cancelled。已完成的回合仍可能包含失敗的工具呼叫。請檢查工具結果及智慧體的最終回應。
agent.session.failed 回報的是工作階段失敗,而非每次回合失敗。刪除工作階段沒有對應的 webhook,也不會停止供應商端的運算資源。