建立一個程式設計助理,讓它撰寫並執行 tree.py,以樹狀結構顯示目錄內容。OpenAI 會管理智慧體、它的對話,以及它執行任務的沙盒。
事前準備
在你的 OpenAI Platform 專案中建立應用程式 API 金鑰。授予金鑰 api.agents.read 和 api.agents.write 權限,以便操作工作階段,並授予 api.responses.write 權限,以便執行模型推論。接著將金鑰匯出為環境變數:
export OPENAI_API_KEY="your-api-key"
請將金鑰保存在智慧體的沙盒外。如需瞭解沙盒的設定與限制,請參閱 OpenAI 託管的沙盒。
每個請求都必須包含 OpenAI-Beta: agents=v1 標頭。OpenAI SDK 會自動加入此標頭,使用 cURL 時則須自行加入。
1. 執行任務
選擇程式語言,安裝 OpenAI SDK,然後執行範例。SDK 範例使用 beta.agents 命名空間。這個請求會建立工作階段、提交任務,並以串流方式傳回進度。
安裝或更新 Python SDK:
pip install --upgrade openai將範例儲存為 quickstart.py:
from 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,
).with_result_collection() as stream:
for event in stream:
print(event.to_json(indent=None), flush=True)
result = stream.get_final_result()
print(result.output_text)
session_id = result.session_id在終端執行範例:
python quickstart.py請使用 Node.js 22.6 或更新版本,並安裝 TypeScript SDK:
npm install openai將範例儲存為 quickstart.mts:
import 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,
});
events.withResultCollection();
try {
for await (const event of events) {
console.log(JSON.stringify(event));
}
const result = await events.finalResult();
console.log(result.output_text);
console.log("Session:", result.session_id);
} finally {
events.controller.abort();
}在終端執行範例:
node --experimental-strip-types quickstart.mts在新目錄中建立 Go 模組並安裝 SDK:
go mod init agents-quickstart
go get github.com/openai/openai-go/v3@latest將範例儲存為 main.go:
import (
"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()
openai.BetaAgentSessionWithResultCollection(events)
if events.Err() != nil {
panic(events.Err())
}
for events.Next() {
event := events.Current()
fmt.Println(event.RawJSON())
}
result, err := openai.BetaAgentSessionFinalResult(events)
if err != nil {
panic(err)
}
fmt.Println(result.OutputText())
sessionID := result.SessionID()
fmt.Println("Session:", sessionID)在終端執行範例:
go run .將 OpenAI SDK 加入 Maven 專案的 pom.xml:
<dependency>
<groupId>com.openai</groupId>
<artifactId>openai-java</artifactId>
<version>4.105.0</version>
</dependency>將範例儲存為 src/main/java/AgentsApiSessionsStreamConversationExample.java:
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.ObjectMappers;
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;
import com.openai.services.beta.agents.AgentTurnResults;
OpenAIClient client = OpenAIOkHttpClient.fromEnv();
var json = ObjectMappers.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())) {
AgentTurnResults.withResultCollection(events);
var iterator = events.stream().iterator();
while (iterator.hasNext()) {
var event = iterator.next();
System.out.println(json.writeValueAsString(event));
}
var result = AgentTurnResults.getFinalResult(events);
System.out.println(result.outputText());
String sessionId = result.sessionId();
System.out.println(sessionId);
}在終端執行範例:
mvn compile exec:java -Dexec.mainClass=AgentsApiSessionsStreamConversationExample安裝 Ruby SDK:
gem install openai將範例儲存為 quickstart.rb:
require "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.with_result_collection
events.each do |event|
puts JSON.generate(event.to_h)
end
result = events.get_final_result
puts result.output_text
session_id = result.session_id
puts "Session: #{session_id}"
ensure
events.close
end在終端執行範例:
ruby quickstart.rb直接在終端使用 cURL,無須安裝 SDK:
curl --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
}'不需要沙盒嗎? 如果智慧體只需回答問題或呼叫外部工具,無須執行指令或處理本機檔案,請將 environment.type 設為 none。瞭解詳情。
2. 查看進度
終端會即時顯示串流傳來的事件。SDK 範例會輸出 JSON,cURL 則會顯示原始事件串流。任務順利執行時,智慧體會建立並執行 tree.py,然後以樹狀結構列出目錄內容,其中會包含該檔案。其他檔案與輸出內容會因沙盒而異。
看到 agent.session.turn.completed 事件後,請查看智慧體回報的執行結果。即使回合已完成,仍可能有工具執行失敗。事件名稱若以 turn.failed、turn.cancelled 或 session.failed 結尾,表示執行失敗或已取消。單憑 agent.session.idle 無法判定執行成功。如果串流提早中斷,請先擷取工作階段及其中已儲存的項目,再重試。
3. 繼續使用工作階段
儲存事件中的 session_id,用它來傳送後續訊息,例如「請在 tree.py 中加入設定最大深度的選項,執行程式並顯示輸出結果。」傳送後續訊息前,請先開啟事件串流,以免錯過最初的事件。
4. 清理工作階段
你可以保留工作階段以執行其他任務,也可以在使用完畢後刪除。刪除前請先儲存需要的檔案。
將範例中的 sess_123 替換為你先前儲存的工作階段 ID。
# Replace the illustrative IDs and URLs below with your own resource values.
from openai import OpenAI
def delete_session(client: OpenAI, session_id: str):
return client.beta.agents.sessions.delete(session_id)
if __name__ == "__main__":
result = delete_session(OpenAI(), "sess_123")
print(result.to_json())// Replace the illustrative IDs and URLs below with your own resource values.
import OpenAI from "openai";
async function deleteSession(client: OpenAI, sessionId: string) {
return client.beta.agents.sessions.delete(sessionId);
}
const result = await deleteSession(new OpenAI(), "sess_123");
console.log(result);// Replace the illustrative IDs and URLs below with your own resource values.
package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
)
func deleteSession(ctx context.Context, client *openai.Client, sessionID string) (*openai.AgentSessionDeleted, error) {
return client.Beta.Agents.Sessions.Delete(ctx, sessionID)
}
func main() {
client := openai.NewClient()
result, err := deleteSession(context.Background(), &client, "sess_123")
if err != nil {
panic(err)
}
fmt.Println(result)
}// Replace the illustrative IDs and URLs below with your own resource values.
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.agents.AgentSessionDeleted;
import com.openai.models.beta.agents.sessions.SessionDeleteParams;
public final class AgentsApiSessionsDeleteSessionExample {
public static AgentSessionDeleted deleteSession(OpenAIClient client, String sessionId) {
return client
.beta()
.agents()
.sessions()
.delete(SessionDeleteParams.builder().sessionId(sessionId).build());
}
public static void main(String[] args) {
var result = deleteSession(OpenAIOkHttpClient.fromEnv(), "sess_123");
System.out.println(result);
}
}# Replace the illustrative IDs and URLs below with your own resource values.
require "openai"
def delete_session(client, session_id)
client.beta.agents.sessions.delete(session_id)
end
puts delete_session(OpenAI::Client.new, "sess_123")curl -X DELETE "https://api.openai.com/v1/agents/sessions/sess_123" \
-H "OpenAI-Beta: agents=v1" \
-H "Authorization: Bearer $OPENAI_API_KEY"後續步驟
- 探索範例應用程式。
- 設定 OpenAI 託管的沙盒,加入套件與輸入檔案、控制網路存取權限,並下載產出物。
- 使用子代理程式比較版本資訊。
- 處理檔案與產出物。
- 選擇環境,或連接自己的沙盒。