构建一个编程助手,让它编写并运行 tree.py,然后展示目录树。OpenAI 负责管理智能体、智能体的对话以及它执行任务时使用的沙盒。
准备工作
在您的 OpenAI 平台项目中创建一个应用程序 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 .在 Maven 项目的 pom.xml 中添加 OpenAI SDK 依赖:
<dependency>
<groupId>com.openai</groupId>
<artifactId>openai-java</artifactId>
<version>4.111.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。使用该 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 托管的沙盒:添加软件包和输入文件、控制网络访问并下载产物。
- 使用子智能体比较发行说明。
- 处理文件和产物。
- 选择环境,或连接您自己的沙盒。