构建一个编程助手,让它编写 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 托管的沙盒:添加软件包和输入文件、控制网络访问,以及下载产物。
- 使用子智能体比较发行说明。
- 处理文件和产物。
- 选择环境,或连接您自己的沙盒。