Build a coding assistant that writes tree.py, runs it, and shows a directory tree. OpenAI manages the agent, its conversation, and the sandbox where it works.
Prerequisites
Create an application API key in your OpenAI Platform project. Grant api.agents.read and api.agents.write for session operations, plus api.responses.write for model inference, then export it:
export OPENAI_API_KEY="your-api-key"
Keep this key outside the agent’s sandbox. See OpenAI-hosted sandboxes for sandbox configuration and limits.
Requests require the OpenAI-Beta: agents=v1 header. The OpenAI SDKs add it
automatically; include it explicitly when using cURL.
1. Run a task
Choose a language, install the OpenAI SDK, and run the example. The SDK examples use the beta.agents namespace. The request creates a session, submits a task, and streams progress.
Install or update the Python SDK:
pip install --upgrade openaiSave the example as 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)Run it from your terminal:
python quickstart.pyInstall the JavaScript SDK:
npm install openaiSave the example as 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();
}Run it from your terminal:
node quickstart.mjsIn a new directory, create a Go module and install the SDK:
go mod init agents-quickstart
go get github.com/openai/openai-go/v3@latestSave the example as 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)
}Run it from your terminal:
go run .Add the OpenAI SDK to your Maven project’s pom.xml:
<dependency>
<groupId>com.openai</groupId>
<artifactId>openai-java</artifactId>
<version>4.63.1</version>
</dependency>Save the example as 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));
}
}Run it from your terminal:
mvn compile exec:java -Dexec.mainClass=AgentsApiSessionsStreamConversationExampleInstall the Ruby SDK:
gem install openaiSave the example as 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
endRun it from your terminal:
ruby quickstart.rbUse cURL from your terminal; no SDK installation is needed:
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
}'2. Follow progress
The terminal shows streamed events. The SDK examples print JSON; cURL shows the raw event stream. On a successful run, the agent creates tree.py, executes it, and reports a directory tree containing that file. Other files and output depend on the sandbox.
Look for agent.session.turn.completed, then check the agent’s reported execution result. A completed turn does not guarantee every tool succeeded. Events ending in turn.failed, turn.cancelled, or session.failed indicate failure or cancellation; agent.session.idle alone does not mean success. If the stream disconnects early, retrieve the session and its saved items before retrying.
3. Continue the session
Save the session_id from the events. Use it to send a follow-up such as “Add a maximum-depth option to tree.py, run it, and show me the output.” Open the event stream before sending follow-up input so you don’t miss early events.
4. Clean up
Keep the session for more tasks, or delete it when you’re done. Save any files you need first.
Set OPENAI_SESSION_ID to the session ID you saved:
export OPENAI_SESSION_ID="your-session-id"import os
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(), os.environ["OPENAI_SESSION_ID"])
print(result.to_json())import OpenAI from "openai";
/**
* @param {OpenAI} client
* @param {string} sessionId
*/
async function deleteSession(client, sessionId) {
return client.beta.agents.sessions.delete(sessionId);
}
const result = await deleteSession(new OpenAI(), process.env.OPENAI_SESSION_ID);
console.log(result);package main
import (
"context"
"fmt"
"os"
"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, os.Getenv("OPENAI_SESSION_ID"))
if err != nil {
panic(err)
}
fmt.Println(result)
}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(), System.getenv("OPENAI_SESSION_ID"));
System.out.println(result);
}
}require "openai"
def delete_session(client, session_id)
client.beta.agents.sessions.delete(session_id)
end
puts delete_session(OpenAI::Client.new, ENV.fetch("OPENAI_SESSION_ID"))curl -X DELETE "https://api.openai.com/v1/agents/sessions/$OPENAI_SESSION_ID" \
-H "OpenAI-Beta: agents=v1" \
-H "Authorization: Bearer $OPENAI_API_KEY"Next steps
- Explore example applications.
- Configure an OpenAI-hosted sandbox: add packages and input files, control network access, and download artifacts.
- Compare release notes with subagents.
- Work with files and artifacts.
- Choose an environment, or connect your own sandbox.