Repository Public
1# Run and continue sessions23> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.45A session keeps an agent's configuration, conversation, and saved work over time. Reuse the same session to send follow-up messages and continue the work.678910## Sessions and turns1112A turn is one cycle of work within a session. A message sent to an idle session starts a new turn. A message sent during an active turn steers that turn.1314Turns run asynchronously. Your application can follow progress through streaming or receive session state changes through [webhooks](https://developers.openai.com/api/docs/guides/agents-api/sessions/webhooks).1516171819## Start work2021Create a session with an agent configuration and initial `input`. Set `stream` to `true` to receive events from the first turn in the same request.2223With your [API key and SDK configured](https://developers.openai.com/api/docs/guides/agents-api/quickstart#prerequisites), run this example to create and run a script. OpenAI manages its environment:2425Create a session and stream its first turn2627```javascript28import OpenAI from "openai";2930const client = new OpenAI();31const events = await client.beta.agents.sessions.create({32 agent: {33 model: "gpt-6-astra",34 instructions: "Write clean code, run it, and report the actual output.",35 },36 environment: { type: "openai_hosted" },37 input:38 "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.",39 stream: true,40});41try {42 for await (const event of events) {43 console.log(JSON.stringify(event));44 }45} finally {46 events.controller.abort();47}48```4950```python51from openai import OpenAI5253with OpenAI() as client:54 with client.beta.agents.sessions.create(55 agent={56 "model": "gpt-6-astra",57 "instructions": "Write clean code, run it, and report the actual output.",58 },59 environment={"type": "openai_hosted"},60 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.",61 stream=True,62 ) as events:63 for event in events:64 print(event.to_json(indent=None), flush=True)65```6667```go68import (69 "context"70 "fmt"7172 "github.com/openai/openai-go/v3"73)7475ctx := context.Background()76client := openai.NewClient()77events := client.Beta.Agents.Sessions.NewStreaming(ctx, openai.BetaAgentSessionNewParams{78 Agent: openai.BetaAgentSessionNewParamsAgent{79 Model: openai.String("gpt-6-astra"),80 Instructions: openai.String("Write clean code, run it, and report the actual output."),81 },82 Environment: openai.EnvironmentParamUnion{OfParamOpenAIHosted: &openai.EnvironmentParamOpenAIHosted{}},83 Input: openai.BetaAgentSessionNewParamsInputUnion{84 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."),85 },86})87defer events.Close()88if events.Err() != nil {89 panic(events.Err())90}91for events.Next() {92 event := events.Current()93 fmt.Println(event.RawJSON())94}95if err := events.Err(); err != nil {96 panic(err)97}98```99100```java101import com.fasterxml.jackson.databind.json.JsonMapper;102import com.openai.client.OpenAIClient;103import com.openai.client.okhttp.OpenAIOkHttpClient;104import com.openai.core.http.StreamResponse;105import com.openai.models.beta.agents.AgentSessionEvent;106import com.openai.models.beta.agents.EnvironmentParam;107import com.openai.models.beta.agents.sessions.SessionCreateParams;108109OpenAIClient client = OpenAIOkHttpClient.fromEnv();110var json = new JsonMapper();111try (StreamResponse<AgentSessionEvent> events =112 client113 .beta()114 .agents()115 .sessions()116 .createStreaming(117 SessionCreateParams.builder()118 .agent(119 SessionCreateParams.Agent.builder()120 .model("gpt-6-astra")121 .instructions("Write clean code, run it, and report the actual output.")122 .build())123 .environment(EnvironmentParam.OpenAIHosted.builder().build())124 .input(125 "Create tree.py, a Python script that prints a readable tree of the files"126 + " in the current directory. Run it and show me the output.")127 .build())) {128 var iterator = events.stream().iterator();129 while (iterator.hasNext()) {130 var event = iterator.next();131 System.out.println(json.writeValueAsString(event));132 }133}134```135136```ruby137require "openai"138require "json"139140client = OpenAI::Client.new141events = client.beta.agents.sessions.create_streaming(142 agent: {143 model: "gpt-6-astra",144 instructions: "Write clean code, run it, and report the actual output."145 },146 environment: { type: "openai_hosted" },147 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."148)149begin150 events.each do |event|151 puts JSON.generate(event.to_h)152 end153ensure154 events.close155end156```157158```bash159curl --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 }\'160```161162163Store the `session_id` with your application's conversation state. Use it to send follow-up messages and retrieve saved work for that conversation.164165See [Configuring Agents](https://developers.openai.com/api/docs/guides/agents-api/configuration) for reusable agent settings and [Architecture](https://developers.openai.com/api/docs/guides/agents-api/architecture) for environment choices. Sessions with `environment.type: "none"` require initial input. The [Create session reference](https://developers.openai.com/api/reference/resources/beta/subresources/agents/subresources/sessions/methods/create) lists the request fields.166167168169170## Follow progress and handle outcomes171172Events report output and changes as the agent works. Check the turn's outcome: completion, failure, or cancellation. An idle session alone does not mean the turn succeeded.173174Look for `agent.session.turn.completed`, `agent.session.turn.failed`, or `agent.session.turn.cancelled`. Inspect the agent's output too: a completed turn does not guarantee every tool succeeded.175176If the session needs a function result or an environment connection, retrieve it and inspect `required_actions`. Your code must [handle the function call](https://developers.openai.com/api/docs/guides/agents-api/tools/functions) or [connect the environment](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted) so work can continue.177178See [Events and Items](https://developers.openai.com/api/docs/guides/agents-api/sessions/events) for event types and payloads.179180181182183184185## Continue or steer the work186187Send another `agent.session.input.message` to the same session. If the agent is working, the message steers the active turn. If the session is idle, it starts a new turn with the existing conversation.188189Saved-agent updates apply only to new sessions. To change the model, reasoning effort, or service tier for later turns in this session, [update its settings](https://developers.openai.com/api/docs/guides/agents-api/configuration#update-settings-for-an-existing-session).190191Use the conversation's session ID to send input. Subscribe to its [event stream](https://developers.openai.com/api/reference/resources/beta/subresources/agents/subresources/sessions/subresources/events/methods/stream) before sending the message so your application receives the turn's early events.192193Pass your API client, session ID, and message to a function in your application:194195Send a follow-up message196197```javascript198// Pass your saved session ID and message to this helper.199async function sendMessage(client, sessionId, text) {200 await client.beta.agents.sessions.events.create(sessionId, {201 events: [202 {203 type: "agent.session.input.message",204 input: [205 {206 role: "user",207 content: [208 {209 type: "input_text",210 text,211 },212 ],213 },214 ],215 },216 ],217 });218}219```220221```python222# Pass your saved session ID and message to this helper.223def send_message(client: OpenAI, session_id: str, text: str) -> None:224 client.beta.agents.sessions.events.create(225 session_id,226 events=[227 {228 "type": "agent.session.input.message",229 "input": [230 {231 "role": "user",232 "content": [233 {234 "type": "input_text",235 "text": text,236 }237 ],238 }239 ],240 }241 ],242 )243```244245```go246// Pass your saved session ID and message to this helper.247func sendMessage(ctx context.Context, client *openai.Client, sessionID, text string) error {248 return client.Beta.Agents.Sessions.Events.New(ctx,249 sessionID,250 openai.BetaAgentSessionEventNewParams{251 Events: []openai.AgentSessionInputParamUnion{252 {253 OfParamAgentSessionInputMessage: &openai.AgentSessionInputParamAgentSessionInputMessage{254 Input: []openai.AgentSessionInputMessageParam{255 {256 Content: []openai.InputContentParamUnion{257 {258 OfParamInputText: &openai.InputContentParamInputText{Text: text},259 },260 },261 },262 },263 },264 },265 },266 })267}268```269270```java271// Pass your saved session ID and message to this helper.272public static void sendMessage(OpenAIClient client, String sessionId, String text) {273 client274 .beta()275 .agents()276 .sessions()277 .events()278 .create(279 EventCreateParams.builder()280 .sessionId(sessionId)281 .addEvent(282 AgentSessionInputParam.AgentSessionInputMessage.builder()283 .addInput(284 AgentSessionInputMessageParam.builder()285 .addInputTextContent(text)286 .build())287 .build())288 .build());289}290```291292```ruby293# Pass your saved session ID and message to this helper.294def send_message(client, session_id, text)295 client.beta.agents.sessions.events.create(296 session_id,297 events: [298 {299 type: "agent.session.input.message",300 input: [301 {302 role: "user",303 content: [304 {305 type: "input_text",306 text: text307 }308 ]309 }310 ]311 }312 ]313 )314end315```316317```bash318curl \319 "https://api.openai.com/v1/agents/sessions/$session_id/events" \320 -H "OpenAI-Beta: agents=v1" \321 -H "Authorization: Bearer $OPENAI_API_KEY" \322 -H "Content-Type: application/json" \323 -d '{324 "events": [325 {326 "type": "agent.session.input.message",327 "input": [328 {329 "role": "user",330 "content": [331 {332 "type": "input_text",333 "text": "List the files in the current directory."334 }335 ]336 }337 ]338 }339 ]340 }'341```342343344For a combined send-and-stream example, see [Events and Items](https://developers.openai.com/api/docs/guides/agents-api/sessions/events#send-and-stream-a-task).345346347348349350351## Retrieve saved work352353Events show live progress. Items are the saved messages and tool calls, including completed responses. Retrieve them to display previous work or inspect results after a turn ends:354355Retrieve session items356357```javascript358// Pass your saved session ID to this helper.359async function listItems(client, sessionId) {360 return client.beta.agents.sessions.items.list(sessionId, {361 order: "asc",362 limit: 100,363 });364}365```366367```python368# Pass your saved session ID to this helper.369def list_items(client: OpenAI, session_id: str):370 return client.beta.agents.sessions.items.list(session_id, order="asc", limit=100)371```372373```go374// Pass your saved session ID to this helper.375func listItems(ctx context.Context, client *openai.Client, sessionID string) (*pagination.CursorPage[openai.AgentSessionItemUnion], error) {376 return client.Beta.Agents.Sessions.Items.List(ctx,377 sessionID,378 openai.BetaAgentSessionItemListParams{379 Order: "asc",380 Limit: openai.Int(100),381 })382}383```384385```java386// Pass your saved session ID to this helper.387public static ItemListPage listItems(OpenAIClient client, String sessionId) {388 return client389 .beta()390 .agents()391 .sessions()392 .items()393 .list(394 ItemListParams.builder()395 .sessionId(sessionId)396 .order(ItemListParams.Order.of("asc"))397 .limit(100L)398 .build());399}400```401402```ruby403# Pass your saved session ID to this helper.404def list_items(client, session_id)405 client.beta.agents.sessions.items.list(406 session_id,407 order: "asc",408 limit: 100409 )410end411```412413```bash414curl \415 "https://api.openai.com/v1/agents/sessions/$session_id/items?order=asc&limit=100" \416 -H "OpenAI-Beta: agents=v1" \417 -H "Authorization: Bearer $OPENAI_API_KEY"418```419420421See [Managing sessions](https://developers.openai.com/api/docs/guides/agents-api/sessions/manage) to inspect session state and turn outcomes. Retrieve files through [Files and artifacts](https://developers.openai.com/api/docs/guides/agents-api/environments/files).422423424425426Streams do not replay missed events. After a disconnect, retrieve the session and its saved items to recover the work. See [Recover a disconnected stream](https://developers.openai.com/api/docs/guides/agents-api/sessions/events#how-to-recover-a-disconnected-stream) for the reconnection procedure.427428## Cancel an active turn429430Cancel the current turn when you want the agent to stop. The session and its previous work remain available:431432Cancel the active turn433434```javascript435// Pass your saved session ID to this helper.436async function cancelTurn(client, sessionId) {437 await client.beta.agents.sessions.events.create(sessionId, {438 events: [{ type: "agent.session.input.cancel" }],439 });440}441```442443```python444# Pass your saved session ID to this helper.445def cancel_turn(client: OpenAI, session_id: str) -> None:446 client.beta.agents.sessions.events.create(447 session_id, events=[{"type": "agent.session.input.cancel"}]448 )449```450451```go452// Pass your saved session ID to this helper.453func cancelTurn(ctx context.Context, client *openai.Client, sessionID string) error {454 return client.Beta.Agents.Sessions.Events.New(ctx,455 sessionID,456 openai.BetaAgentSessionEventNewParams{457 Events: []openai.AgentSessionInputParamUnion{458 {OfParamAgentSessionInputCancel: &openai.AgentSessionInputParamAgentSessionInputCancel{}},459 },460 })461}462```463464```java465// Pass your saved session ID to this helper.466public static void cancelTurn(OpenAIClient client, String sessionId) {467 client468 .beta()469 .agents()470 .sessions()471 .events()472 .create(473 EventCreateParams.builder()474 .sessionId(sessionId)475 .addEventAgentSessionInputCancel()476 .build());477}478```479480```ruby481# Pass your saved session ID to this helper.482def cancel_turn(client, session_id)483 client.beta.agents.sessions.events.create(484 session_id,485 events: [{ type: "agent.session.input.cancel" }]486 )487end488```489490```bash491curl "https://api.openai.com/v1/agents/sessions/$session_id/events" \492 -H "OpenAI-Beta: agents=v1" \493 -H "Authorization: Bearer $OPENAI_API_KEY" \494 -H "Content-Type: application/json" \495 -d '{"events":[{"type":"agent.session.input.cancel"}]}'496```