All guides
OpenAI

Agents API 快速入门

Checked 09/15/2026View original

AI translation, not an official translation. Refer to the original for technical details.

On this page

完整文档索引请参见 llms.txt。在页面 URL 后追加 .md 即可获取各文档页面的 Markdown 版本。

构建一个编程助手,它能编写 tree.py、运行代码并显示目录树。OpenAI 负责管理智能体、其对话以及运行环境所在的沙盒。

前提条件

在您的 OpenAI Platform 项目中创建一个应用程序 API 密钥。授予 api.agents.readapi.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

安装或更新 Python SDK:

pip install --upgrade openai

将示例保存为 quickstart.py

创建并运行 tree.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

安装 JavaScript SDK:

npm install openai

将示例保存为 quickstart.mjs

创建并运行 tree.py

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

在新目录中,创建 Go 模块并安装 SDK:

go mod init agents-quickstart
go get github.com/openai/openai-go/v3@latest

将示例保存为 main.go

创建并运行 tree.py

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 .

Java

将 OpenAI SDK 添加到您的 Maven 项目的 pom.xml 中:

<dependency>
  <groupId>com.openai</groupId>
  <artifactId>openai-java</artifactId>
  <version>${apiReferencePackageVersions.java}</version>
</dependency>

将示例保存为 src/main/java/AgentsApiSessionsStreamConversationExample.java

创建并运行 tree.py

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

安装 Ruby SDK:

gem install openai

将示例保存为 quickstart.rb

创建并运行 tree.py

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

直接在终端中使用 cURL,无需安装 SDK:

创建并运行 tree.py

curl --no-buffer --fail-with-body https://api.openai.com/v1/agents/sessions \\\n  -H "OpenAI-Beta: agents=v1" \\\n  -H "Authorization: Bearer $OPENAI_API_KEY" \\\n  -H "Content-Type: application/json" \\\n  -d \'{\n    "agent": {\n      "model": "gpt-6-astra",\n      "instructions": "Write clean code, run it, and report the actual output."\n    },\n    "environment": { "type": "openai_hosted" },\n    "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.",\n    "stream": true\n  }\'

不需要沙盒? 对于只需回答问题或调用外部工具、无需执行命令或处理本地文件的智能体,请将 environment.type 设置为 none了解更多

2. 跟踪进度

终端会显示流式传输的事件。SDK 示例输出 JSON;cURL 显示原始事件流。成功运行后,智能体会创建 tree.py、执行它,并报告包含该文件的目录树。其他文件和输出取决于沙盒环境。

请关注 agent.session.turn.completed,然后检查智能体报告的执行结果。一次完成的轮次并不保证每个工具都执行成功。以 turn.failedturn.cancelledsession.failed 结尾的事件表示失败或取消;仅凭 agent.session.idle 并不代表成功。如果流传输提前断开,请在重试前获取会话及其已保存的条目

3. 继续会话

从事件中保存 session_id。使用它发送后续消息,例如:"在 tree.py 中添加最大深度选项,运行它,并显示输出结果。"请在发送后续输入之前打开事件流,以免遗漏早期事件。

4. 清理

您可以保留会话以执行更多任务,或在完成后将其删除。请先保存所需的任何文件

将示例中用于说明的 sess_123 值替换为您保存的会话 ID。

Python

Delete the session
# 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())

JavaScript

Delete the session
// 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);

Go

Delete the session
// 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)
}

Java

Delete the session
// 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);
  }
}

Ruby

Delete the session
# 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

Delete the session
curl -X DELETE "https://api.openai.com/v1/agents/sessions/sess_123" \\\n  -H "OpenAI-Beta: agents=v1" \\\n  -H "Authorization: Bearer $OPENAI_API_KEY"

后续步骤