本指南使用 Cloudflare 提供的參考 Worker,透過 webhook 管理沙盒佈建。
請參閱 OpenAI Cookbook 中由應用程式管理佈建和透過 webhook 管理佈建的範例。
- 應用程式建立 Agents API 工作階段並傳送輸入。
- OpenAI 將工作階段的 webhook 傳送至你的 Cloudflare 帳戶中的 Worker。
- Worker 啟動該工作階段專用的容器,或重新連線至該容器。容器會執行
codex exec-server。執行器會主動向 OpenAI 建立連線,讓智慧體可以執行指令及操作檔案。
應用程式使用 Agents API,參考 Worker 則負責管理沙盒佈建。如需瞭解如何建立及恢復連線,請參閱沙盒生命週期。
你需要具備 Containers 存取權的 Cloudflare 帳戶。應用程式發送請求時,請使用 OPENAI_API_KEY。將 OPENAI_EXECUTOR_API_KEY 設為環境金鑰,並只將這把金鑰以 CODEX_API_KEY 的名稱傳入容器。
建立智慧體,並將其 ID 儲存為 OPENAI_AGENT_ID。應用程式和參考 Worker 必須使用相同的智慧體 ID。
Cloudflare 的參考 Worker 包含 webhook 處理常式、容器映像檔、部署設定和清理端點。
為清理端點產生密鑰,並將其儲存為 EXECUTOR_CLIENT_SECRET:
openssl rand -hex 32
在你的 Cloudflare 帳戶中部署 Worker:
部署至 Cloudflare
依提示輸入下列值:
| 變數 |
值 |
OPENAI_API_KEY |
Worker 用來取得工作階段狀態的金鑰 |
OPENAI_EXECUTOR_API_KEY |
以 CODEX_API_KEY 的名稱傳給執行器的環境金鑰 |
OPENAI_AGENT_ID |
此 Worker 所服務的智慧體的 ID |
OPENAI_WEBHOOK_SECRET |
首次部署時填入 pending-webhook-registration |
EXECUTOR_CLIENT_SECRET |
為清理端點產生的密鑰 |
將部署完成後的 Worker 網址儲存為 WORKER_URL。
依照 webhook 設定步驟,在你的 OpenAI 專案中註冊 $WORKER_URL/webhook。啟用 Cloudflare 參考整合列出的事件:
agent.session.created
agent.session.action_required
agent.session.in_progress
agent.session.idle
agent.session.failed
將 OPENAI_WEBHOOK_SECRET 的值改為 OpenAI 傳回的簽章密鑰,然後部署新版 Worker。接著檢查 Worker 的設定。下列範例使用標準 HTTP 用戶端呼叫 Worker:
1
2
3
4
5
6
7
8// Replace the illustrative IDs and URLs below with your own resource values.
const response = await fetch(
"https://worker.example.com".replace(/\/+$/, "") + "/health",
{ method: "GET" }
);
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
console.log(await response.text());
1
2
3
4
5
6
7# Replace the illustrative IDs and URLs below with your own resource values.
import urllib.request
url = "https://worker.example.com".rstrip("/") + "/health"
request = urllib.request.Request(url, method="GET")
with urllib.request.urlopen(request) as response:
print(response.read().decode())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24// Replace the illustrative IDs and URLs below with your own resource values.
import (
"io"
"net/http"
"os"
"strings"
)
endpoint := strings.TrimRight("https://worker.example.com", "/") + "/health"
request, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
panic(err)
}
response, err := http.DefaultClient.Do(request)
if err != nil {
panic(err)
}
defer response.Body.Close()
if response.StatusCode/100 != 2 {
panic(response.Status)
}
if _, err := io.Copy(os.Stdout, response.Body); err != nil {
panic(err)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15// Replace the illustrative IDs and URLs below with your own resource values.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
String endpoint = "https://worker.example.com".replaceAll("/+$", "") + "/health";
var request =
HttpRequest.newBuilder(URI.create(endpoint))
.method("GET", HttpRequest.BodyPublishers.noBody())
.build();
var response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() / 100 != 2)
throw new IllegalStateException("Request failed: " + response.statusCode());
System.out.println(response.body());
1
2
3
4
5
6
7
8
9
10# Replace the illustrative IDs and URLs below with your own resource values.
require "uri"
require "net/http"
uri = URI("https://worker.example.com".sub(%r{/+\z}, "") + "/health")
request = Net::HTTP::Get.new(uri)
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") { |http| http.request(request) }
raise "Request failed: #{response.code}" unless response.is_a?(Net::HTTPSuccess)
puts response.body
1curl --fail-with-body "$WORKER_URL/health"
回應應同時包含 "configured": true 和 "webhook_configured": true。
當工作階段要求執行 environment_connection 動作時,表示應重新連線至離線的執行器。僅憑閒置事件無法判定是否可安全關閉執行器,詳見生命週期行為。
依照執行工作階段的步驟,使用應用程式的 OPENAI_API_KEY,並使用與 Worker 設定相同的 OPENAI_AGENT_ID。建立自行託管的工作階段,請智慧體先寫入 /workspace/hello.txt,再讀取該檔案。
Worker 會接收工作階段的 webhook,並讓沙盒執行器建立連線。應用程式則透過 Agents API 以串流方式接收智慧體的輸出。
將工作階段 ID 儲存為 SESSION_ID。若要繼續對話,請先開啟工作階段的事件串流,再傳送後續輸入。如果執行器已離線,新的輸入會觸發環境連線請求,工作階段會等待 Worker 重新連線至執行器。重新連線不會自動還原先前容器中的檔案。
Cloudflare 的基本 Worker 應用程式使用 @openai/agents-api TypeScript SDK 建立工作階段、傳送初始與後續輸入,以及清理資源。呼叫此應用程式的 POST /demo 端點即可執行整個流程。
此應用程式也透過 webhook 管理沙盒佈建。即使應用程式在 Worker 中執行,也不必直接佈建沙盒。
當應用程式不再需要沙盒時,請呼叫參考 Worker 中需要驗證身分的清理端點:
1
2
3
4
5
6
7
8// Replace the illustrative IDs and URLs below with your own resource values.
const response = await fetch("https://worker.example.com/executors/sess_123", {
method: "DELETE",
headers: { Authorization: `Bearer ${process.env.EXECUTOR_CLIENT_SECRET}` },
});
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
console.log(await response.text());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17# Replace the illustrative IDs and URLs below with your own resource values.
import os
from urllib.parse import quote
import urllib.request
url = (
"https://worker.example.com".rstrip("/")
+ "/executors/"
+ quote("sess_123", safe="")
)
request = urllib.request.Request(
url,
method="DELETE",
headers={"Authorization": "Bearer " + os.environ["EXECUTOR_CLIENT_SECRET"]},
)
with urllib.request.urlopen(request) as response:
print(response.read().decode())
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// Replace the illustrative IDs and URLs below with your own resource values.
import (
"io"
"net/http"
"net/url"
"os"
"strings"
)
endpoint := strings.TrimRight("https://worker.example.com", "/") + "/executors/" + url.PathEscape("sess_123")
request, err := http.NewRequest("DELETE", endpoint, nil)
if err != nil {
panic(err)
}
request.Header.Set("Authorization", "Bearer "+os.Getenv("EXECUTOR_CLIENT_SECRET"))
response, err := http.DefaultClient.Do(request)
if err != nil {
panic(err)
}
defer response.Body.Close()
if response.StatusCode/100 != 2 {
panic(response.Status)
}
if _, err := io.Copy(os.Stdout, response.Body); 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// Replace the illustrative IDs and URLs below with your own resource values.
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
String endpoint =
"https://worker.example.com".replaceAll("/+$", "")
+ "/executors/"
+ URLEncoder.encode("sess_123", StandardCharsets.UTF_8).replace("+", "%20");
var request =
HttpRequest.newBuilder(URI.create(endpoint))
.header("Authorization", "Bearer " + System.getenv("EXECUTOR_CLIENT_SECRET"))
.method("DELETE", HttpRequest.BodyPublishers.noBody())
.build();
var response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() / 100 != 2)
throw new IllegalStateException("Request failed: " + response.statusCode());
System.out.println(response.body());
1
2
3
4
5
6
7
8
9
10
11# Replace the illustrative IDs and URLs below with your own resource values.
require "uri"
require "net/http"
uri = URI("https://worker.example.com".sub(%r{/+\z}, "") + "/executors/" + URI.encode_www_form_component("sess_123").gsub("+", "%20"))
request = Net::HTTP::Delete.new(uri)
request["Authorization"] = "Bearer #{ENV.fetch("EXECUTOR_CLIENT_SECRET")}"
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") { |http| http.request(request) }
raise "Request failed: #{response.code}" unless response.is_a?(Net::HTTPSuccess)
puts response.body
1
2
3
4curl --fail-with-body \
--request DELETE \
--header "Authorization: Bearer $EXECUTOR_CLIENT_SECRET" \
"$WORKER_URL/executors/$SESSION_ID"
另行刪除 Agents API 工作階段。刪除工作階段不會觸發 webhook,因此若要立即清理資源,請執行這兩項操作。釋放容器前,請先取回需要的檔案。
若要直接控制沙盒佈建,請使用 Cloudflare Sandbox SDK,並遵循由應用程式管理生命週期的步驟和執行器連線說明。每個工作階段只使用一個佈建控制器。