Repository Public
1# Agents API quickstart23> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.45Build 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.67## Prerequisites89Create an [application API key](https://platform.openai.com/api-keys) 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:1011```bash12export OPENAI_API_KEY="your-api-key"13```1415Keep this key outside the agent's sandbox. See [OpenAI-hosted sandboxes](https://developers.openai.com/api/docs/guides/agents-api/environments/openai-hosted#configure-the-sandbox) for sandbox configuration and limits.1617Requests require the `OpenAI-Beta: agents=v1` header. The OpenAI SDKs add it18 automatically; include it explicitly when using cURL.1920## 1. Run a task2122Choose 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.23242526Python272829Install or update the Python SDK:3031```bash32pip install --upgrade openai33```3435Save the example as `quickstart.py`:3637Create and run tree.py3839```python40from openai import OpenAI4142with OpenAI() as client:43 with client.beta.agents.sessions.create(44 agent={45 "model": "gpt-6-astra",46 "instructions": "Write clean code, run it, and report the actual output.",47 },48 environment={"type": "openai_hosted"},49 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.",50 stream=True,51 ) as events:52 for event in events:53 print(event.to_json(indent=None), flush=True)54```555657Run it from your terminal:5859```bash60python quickstart.py61```6263 646566 6768 69JavaScript707172Install the JavaScript SDK:7374```bash75npm install openai76```7778Save the example as `quickstart.mjs`:7980Create and run tree.py8182```javascript83import OpenAI from "openai";8485const client = new OpenAI();86const events = await client.beta.agents.sessions.create({87 agent: {88 model: "gpt-6-astra",89 instructions: "Write clean code, run it, and report the actual output.",90 },91 environment: { type: "openai_hosted" },92 input:93 "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.",94 stream: true,95});96try {97 for await (const event of events) {98 console.log(JSON.stringify(event));99 }100} finally {101 events.controller.abort();102}103```104105106Run it from your terminal:107108```bash109node quickstart.mjs110```111112 113114115 116117 118Go119120121In a new directory, create a Go module and install the SDK:122123```bash124go mod init agents-quickstart125go get github.com/openai/openai-go/v3@latest126```127128Save the example as `main.go`:129130Create and run tree.py131132```go133import (134 "context"135 "fmt"136137 "github.com/openai/openai-go/v3"138)139140ctx := context.Background()141client := openai.NewClient()142events := client.Beta.Agents.Sessions.NewStreaming(ctx, openai.BetaAgentSessionNewParams{143 Agent: openai.BetaAgentSessionNewParamsAgent{144 Model: openai.String("gpt-6-astra"),145 Instructions: openai.String("Write clean code, run it, and report the actual output."),146 },147 Environment: openai.EnvironmentParamUnion{OfParamOpenAIHosted: &openai.EnvironmentParamOpenAIHosted{}},148 Input: openai.BetaAgentSessionNewParamsInputUnion{149 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."),150 },151})152defer events.Close()153if events.Err() != nil {154 panic(events.Err())155}156for events.Next() {157 event := events.Current()158 fmt.Println(event.RawJSON())159}160if err := events.Err(); err != nil {161 panic(err)162}163```164165166Run it from your terminal:167168```bash169go run .170```171172 173174175 176177 178Java179180181Add the OpenAI SDK to your Maven project's `pom.xml`:182183```xml184<dependency>185 <groupId>com.openai</groupId>186 <artifactId>openai-java</artifactId>187 <version>${apiReferencePackageVersions.java}</version>188</dependency>189```190191192Save the example as `src/main/java/AgentsApiSessionsStreamConversationExample.java`:193194Create and run tree.py195196```java197import com.fasterxml.jackson.databind.json.JsonMapper;198import com.openai.client.OpenAIClient;199import com.openai.client.okhttp.OpenAIOkHttpClient;200import com.openai.core.http.StreamResponse;201import com.openai.models.beta.agents.AgentSessionEvent;202import com.openai.models.beta.agents.EnvironmentParam;203import com.openai.models.beta.agents.sessions.SessionCreateParams;204205OpenAIClient client = OpenAIOkHttpClient.fromEnv();206var json = new JsonMapper();207try (StreamResponse<AgentSessionEvent> events =208 client209 .beta()210 .agents()211 .sessions()212 .createStreaming(213 SessionCreateParams.builder()214 .agent(215 SessionCreateParams.Agent.builder()216 .model("gpt-6-astra")217 .instructions("Write clean code, run it, and report the actual output.")218 .build())219 .environment(EnvironmentParam.OpenAIHosted.builder().build())220 .input(221 "Create tree.py, a Python script that prints a readable tree of the files"222 + " in the current directory. Run it and show me the output.")223 .build())) {224 var iterator = events.stream().iterator();225 while (iterator.hasNext()) {226 var event = iterator.next();227 System.out.println(json.writeValueAsString(event));228 }229}230```231232233Run it from your terminal:234235```bash236mvn compile exec:java -Dexec.mainClass=AgentsApiSessionsStreamConversationExample237```238239 240241242 243244 245Ruby246247248Install the Ruby SDK:249250```bash251gem install openai252```253254Save the example as `quickstart.rb`:255256Create and run tree.py257258```ruby259require "openai"260require "json"261262client = OpenAI::Client.new263events = client.beta.agents.sessions.create_streaming(264 agent: {265 model: "gpt-6-astra",266 instructions: "Write clean code, run it, and report the actual output."267 },268 environment: { type: "openai_hosted" },269 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."270)271begin272 events.each do |event|273 puts JSON.generate(event.to_h)274 end275ensure276 events.close277end278```279280281Run it from your terminal:282283```bash284ruby quickstart.rb285```286287 288289290 291292 293cURL294295296Use cURL from your terminal; no SDK installation is needed:297298Create and run tree.py299300```bash301curl --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 }\'302```303304305 306307308**Don't need a sandbox?** Set `environment.type` to `none` for agents that309 answer questions or call external tools without running commands or working310 with local files. [Learn311 more](https://developers.openai.com/api/docs/guides/agents-api/architecture#start-without-an-environment).312313## 2. Follow progress314315The 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.316317Look 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](https://developers.openai.com/api/docs/guides/agents-api/sessions#how-to-recover-a-disconnected-stream) before retrying.318319## 3. Continue the session320321Save the `session_id` from the events. Use it to [send a follow-up](https://developers.openai.com/api/docs/guides/agents-api/sessions#send-input) 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.322323324325326## 4. Clean up327328Keep the session for more tasks, or delete it when you're done. [Save any files you need](https://developers.openai.com/api/docs/guides/agents-api/environments/files) first.329330Replace the illustrative `sess_123` value in the example with the session ID you saved.331332 333334 335Python336337 Delete the session338339```python340# Replace the illustrative IDs and URLs below with your own resource values.341342from openai import OpenAI343344345def delete_session(client: OpenAI, session_id: str):346 return client.beta.agents.sessions.delete(session_id)347348349if __name__ == "__main__":350 result = delete_session(OpenAI(), "sess_123")351 print(result.to_json())352```353354 355356 357358 359JavaScript360361 Delete the session362363```javascript364// Replace the illustrative IDs and URLs below with your own resource values.365import OpenAI from "openai";366367async function deleteSession(client, sessionId) {368 return client.beta.agents.sessions.delete(sessionId);369}370371const result = await deleteSession(new OpenAI(), "sess_123");372console.log(result);373```374375 376377 378379 380Go381382 Delete the session383384```go385// Replace the illustrative IDs and URLs below with your own resource values.386package main387388import (389 "context"390 "fmt"391392 "github.com/openai/openai-go/v3"393)394395func deleteSession(ctx context.Context, client *openai.Client, sessionID string) (*openai.AgentSessionDeleted, error) {396 return client.Beta.Agents.Sessions.Delete(ctx, sessionID)397}398399func main() {400 client := openai.NewClient()401 result, err := deleteSession(context.Background(), &client, "sess_123")402 if err != nil {403 panic(err)404 }405 fmt.Println(result)406}407```408409 410411 412413 414Java415416 Delete the session417418```java419// Replace the illustrative IDs and URLs below with your own resource values.420import com.openai.client.OpenAIClient;421import com.openai.client.okhttp.OpenAIOkHttpClient;422import com.openai.models.beta.agents.AgentSessionDeleted;423import com.openai.models.beta.agents.sessions.SessionDeleteParams;424425public final class AgentsApiSessionsDeleteSessionExample {426 public static AgentSessionDeleted deleteSession(OpenAIClient client, String sessionId) {427 return client428 .beta()429 .agents()430 .sessions()431 .delete(SessionDeleteParams.builder().sessionId(sessionId).build());432 }433434 public static void main(String[] args) {435 var result = deleteSession(OpenAIOkHttpClient.fromEnv(), "sess_123");436 System.out.println(result);437 }438}439```440441 442443 444445 446Ruby447448 Delete the session449450```ruby451# Replace the illustrative IDs and URLs below with your own resource values.452require "openai"453454def delete_session(client, session_id)455 client.beta.agents.sessions.delete(session_id)456end457458puts delete_session(OpenAI::Client.new, "sess_123")459```460461 462463 464465 466cURL467468 Delete the session469470```bash471curl -X DELETE "https://api.openai.com/v1/agents/sessions/sess_123" \\\n -H "OpenAI-Beta: agents=v1" \\\n -H "Authorization: Bearer $OPENAI_API_KEY"472```473474475476## Next steps477478- [Explore example applications](https://developers.openai.com/api/docs/guides/agents-api/overview#try-an-example).479- [Configure an OpenAI-hosted sandbox](https://developers.openai.com/api/docs/guides/agents-api/environments/openai-hosted): add packages and input files, control network access, and download artifacts.480- [Compare release notes with subagents](https://developers.openai.com/api/docs/guides/agents-api/multi-agent#example-compare-release-notes).481- [Work with files and artifacts](https://developers.openai.com/api/docs/guides/agents-api/environments/files).482- [Choose an environment](https://developers.openai.com/api/docs/guides/agents-api/configuration#environment-settings), or [connect your own sandbox](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted).