使用 webhook 即可在工作階段狀態變更時採取相應動作,無須持續開啟事件串流。Webhook 處理常式可以啟動或重新連線至沙盒運算資源、更新應用程式或觸發工作流程。
| 事件 |
觸發時機 |
agent.session.created |
工作階段建立時。 |
agent.session.action_required |
工作階段需要函式執行結果、需要連線至環境,或需要使用者核准電腦操作時。 |
agent.session.in_progress |
工作階段開始處理一個回合時。 |
agent.session.idle |
工作階段處於閒置狀態且可接受更多輸入時。 |
agent.session.failed |
工作階段進入失敗狀態時。 |
agent.session.action_required 事件包含工作階段 ID,以及 required_action.type 欄位,其值為 function_call、environment_connection 或 computer_use_approval_request。
1234567{
"type": "agent.session.action_required",
"data": {
"id": "sess_abc123",
"required_action": { "type": "function_call" }
}
}
請取得工作階段資料,並查看 required_actions 中的呼叫 ID、引數、環境 ID 或電腦操作的核准詳情。Webhook 不含這些資料。針對電腦操作,巢狀欄位 request.type 會指出請求涉及瀏覽器來源存取權或身分驗證。請向使用者顯示目前的請求,再透過工作階段事件端點傳回使用者的回覆。請參閱電腦,瞭解請求與回應的格式。
請依照通用的 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 相同。請儲存環境 ID 和連線 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 這項必要動作。API 會發出 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,也不會停止供應商端的運算。