打造一個程式設計助理,讓它編寫並執行 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,
) as events:
for event in events:
print(event.to_json(indent=None), flush=True)在終端中執行:
python quickstart.py安裝 JavaScript SDK:
npm install openai將範例儲存為 quickstart.mjs:
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,
});
try {
for await (const event of events) {
console.log(JSON.stringify(event));
}
} finally {
events.controller.abort();
}在終端中執行:
node quickstart.mjs在新目錄中建立 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()
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)
}在終端中執行:
go run .將 OpenAI SDK 加入 Maven 專案的 pom.xml:
<dependency>
<groupId>com.openai</groupId>
<artifactId>openai-java</artifactId>
<version>4.58.0</version>
</dependency>將範例儲存為 src/main/java/AgentsApiSessionsStreamConversationExample.java:
import 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));
}
}在終端中執行:
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.each do |event|
puts JSON.generate(event.to_h)
end
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。使用它傳送後續訊息,例如:「Add a maximum-depth option to tree.py, run it, and show me the output.」傳送後續輸入前,請先開啟事件串流,以免錯過初期事件。
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, sessionId) {
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 託管的沙盒:新增套件與輸入檔案、控制網路存取,以及下載產出物。
- 使用子代理程式比較版本資訊。
- 處理檔案與產出物。
- 選擇環境,或連接自己的沙盒。