# Agents API

> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.

## 3. Send tasks and handle tool calls



To give an agent a task, send a message to a [session](https://developers.openai.com/api/training/agents-api/2-create-isolated-sessions.md). If the session is idle, the message starts a [turn](https://developers.openai.com/api/docs/guides/agents-api/sessions#sessions-and-turns), one round of work. If a turn is already running, the agent uses the new message to adjust the work in progress.

The turn runs in the background. Your app can open an [event stream](https://developers.openai.com/api/docs/guides/agents-api/sessions/events#consume-a-stream), a connection over which the API sends updates as work happens. One of those updates can be a request to run a [function tool](https://developers.openai.com/api/docs/guides/agents-api/tools/functions#define-a-function), a function in your app that the agent can call.



### Submit input and complete function calls

1. **Subscribe to session events** (Your app → OpenAI Agents API, `GET /v1/agents/sessions/sess_a/events`)

   **Your app**: Opens an event stream for the authorized session.

   **OpenAI Agents API**: Sends updates over this connection.

   **HTTP request**: `GET /v1/agents/sessions/sess_a/events HTTP/1.1` `Host: api.openai.com` `Authorization: Bearer EXAMPLE_API_KEY` `OpenAI-Beta: agents=v1` `Accept: text/event-stream`

2. **Read the event stream** (OpenAI Agents API → Your app, HTTP response)

   **Your app**: Keeps listening while it sends input in a separate request.

   **OpenAI Agents API**: Keeps the HTTP response open for new events.

   **Stream response headers**: `HTTP/1.1 200 OK` `Content-Type: text/event-stream`

   Learn more: [Streaming events](https://developers.openai.com/api/reference/resources/beta/subresources/agents/streaming-events)

3. **Send a message** (Your app → OpenAI Agents API, `POST /v1/agents/sessions/sess_a/events`)

   **Your app**: Saves the message and its key, then sends the key in the `Idempotency-Key` header.

   **OpenAI Agents API**: Accepts the message for this session.

   **Request JSON**: `Idempotency-Key: 972d7146-51f2-4d84-9c18-6af9cb516fd4` `{"events":[{"type":"agent.session.input.message","input":[{"role":"user","content":[{"type":"input_text","text":"Herringbone now returns payments one page at a time. Review Customer A’s nightly export. What should the customer change to include every payment?"}]}]}]}`

4. **Check that the API accepted the message** (OpenAI Agents API → Your app, HTTP response)

   **Your app**: Watches for the turn’s first events.

   **OpenAI Agents API**: Accepts the input and starts a turn in this idle session.

   **HTTP response**: `HTTP 202 Accepted` `No response body.`

5. **Receive a pending function call** (OpenAI Agents API → Your app, Streamed event)

   **Your app**: Reads the pending call from the event.

   **OpenAI Agents API**: Reports the function call in `session.required_actions`.

   **Event JSON**: `{"type":"agent.session.requires_action","session":{"id":"sess_a","status":"requires_action","required_actions":[{"type":"function_call","turn_id":"turn_plan","call_id":"call_context","name":"get_integration_context","arguments":{}}]}}`

6. **Look up pending calls** (Your app → OpenAI Agents API, `GET /v1/agents/sessions/sess_a`)

   **Your app**: Rechecks the pending calls by session ID before running the function.

   **OpenAI Agents API**: Returns current `required_actions`.

   **Request body**: `No request body.`

   Learn more: [Retrieve a session](https://developers.openai.com/api/reference/resources/beta/subresources/agents/subresources/sessions/methods/retrieve)

7. **Read the call and its IDs** (OpenAI Agents API → Your app, HTTP response)

   **Your app**: Reads the function name, arguments, turn ID, and call ID.

   **OpenAI Agents API**: Lists the calls awaiting results.

   **Response JSON**: `{"id":"sess_a","status":"requires_action","required_actions":[{"type":"function_call","turn_id":"turn_plan","call_id":"call_context","name":"get_integration_context","arguments":{}}]}`

8. **Run the function handler** (Your app → function handler, Application operation)

   **Your app**: Checks the session owner’s permissions and runs the named function with the supplied arguments.

   **Authorized function call**: `{"function":"get_integration_context","arguments":{},"application_context":{"session_id":"sess_a","customer_id":"customer_a"}}`

9. **Save the function result** (function handler → Your app, Application operation)

   **Your app**: Records the result with its session, turn, and call IDs.

   **Saved function result**: `{"session_id":"sess_a","turn_id":"turn_plan","call_id":"call_context","result":{"path":"exports/nightly.http","code":"GET /v1/payments?limit=100","output_columns":["payment_id","amount"],"notes":["The finance team’s export makes this request once each night."]}}`

10. **Return the function result** (Your app → OpenAI Agents API, `POST /v1/agents/sessions/sess_a/events`)

    **Your app**: Posts the result with the matching `turn_id` and `call_id`.

    **OpenAI Agents API**: Matches the result to the pending call.

    **Request JSON**: `{"events":[{"type":"agent.session.input.tool_result","turn_id":"turn_plan","call_id":"call_context","success":true,"output":"{\"path\":\"exports/nightly.http\",\"code\":\"GET /v1/payments?limit=100\",\"output_columns\":[\"payment_id\",\"amount\"],\"notes\":[\"The finance team’s export makes this request once each night.\"]}"}]}`

11. **Follow the rest of the turn** (OpenAI Agents API → Your app, HTTP response)

    **Your app**: Keeps reading events for completion, failure, or cancellation.

    **OpenAI Agents API**: Acknowledges the result. The turn can resume once all required calls have results.

    **HTTP response**: `HTTP 202 Accepted` `No response body.`

12. **Read the turn outcome** (OpenAI Agents API → Your app, Streamed event)

    **Your app**: Reads the turn ID and status from the completion event.

    **OpenAI Agents API**: Completes the turn after receiving the function result.

    **Event JSON**: `{"type":"agent.session.turn.completed","session_id":"sess_a","turn_id":"turn_plan","turn":{"id":"turn_plan","status":"completed"}}`



### Messages, function calls, and results

Your app uses `/v1/agents/sessions/{session_id}/events` in both directions. A `GET` opens the stream. Separate `POST` requests [send messages and tool results](https://developers.openai.com/api/reference/resources/beta/subresources/agents/subresources/sessions/subresources/events/methods/create).

- **A message.** Open the stream before posting `agent.session.input.message` so you receive the first updates. An [idempotency key](https://developers.openai.com/api/docs/guides/agents-api/sessions#continue-or-steer-the-work) is a unique ID that lets the API recognize a retry. Save it with the message and send it in the `Idempotency-Key` header. If you miss the HTTP response, resend the same message and key to the same session.
- **A request for action.** The event `agent.session.requires_action` tells you the agent needs something from your app. For a function call, [`session.required_actions`](https://developers.openai.com/api/docs/guides/agents-api/tools/functions#handle-required-actions) lists the function name and arguments. Your app checks permissions and arguments before running the function.
- **A function result.** [Send the output or error](https://developers.openai.com/api/docs/guides/agents-api/tools/functions#return-the-result) as `agent.session.input.tool_result`. The `turn_id` and `call_id` tell the API which pending call the result answers. Once all required results arrive, the turn can continue.

HTTP `202` confirms that the API accepted your input. The [turn events](https://developers.openai.com/api/docs/guides/agents-api/sessions/events#handle-updates) report the outcome later. The turn’s final status can be `completed`, `failed`, or `cancelled`. If the stream disconnects, [retrieve the saved work and pending actions](https://developers.openai.com/api/docs/guides/agents-api/sessions/events#how-to-recover-a-disconnected-stream). The stream doesn’t replay missed events.

### Example: Find the request behind a finance report



Customer A uses Herringbone, a fictional payments API provider. Every night, a
  job copies payment IDs and amounts into a finance report. Herringbone now
  returns payments one page at a time. If the job reads only the first 100 of
  101 payments, one payment is missing. Herringbone asks Customer A’s [AI
  forward-deployed engineer](https://developers.openai.com/api/training/agents-api.md#use-case-ai-forward-deployed-engineer) to check
  the export and recommend a fix before the next nightly run.



Herringbone’s app sends an `agent.session.input.message` event to Customer A’s session (`sess_a`). In the diagram, the message with `role: "user"` contains the task from Herringbone. The agent requests `get_integration_context` to see how the job fetches payments. The function takes no arguments. Herringbone uses `sess_a` to identify the integration and checks that Customer A has authorized access to its records.

The lookup finds the request to Herringbone’s payments API, `GET /v1/payments?limit=100`, in `exports/nightly.http`. It also returns the column names finance expects, `payment_id` and `amount`. Herringbone saves the result and posts it to `sess_a` with `turn_id` set to `turn_plan` and `call_id` set to `call_context`. These IDs match the pending call in the diagram.

The integration notes show that the job makes just one request each night. In its [reply](https://developers.openai.com/api/training/agents-api/5-inspect-session-results-and-artifacts.md), the agent recommends reading `next_cursor` after processing each page. If it has a value, the job should send it back as the `cursor` parameter on the next request. It should repeat until there’s no next cursor.

Saving the function result lets Herringbone [resend it after a disconnect](https://developers.openai.com/api/docs/guides/agents-api/tools/functions#recover-after-a-disconnect) if the call is still pending. This matters especially for functions that write data. If a write may have succeeded but there’s no saved result, check what changed before running it again.

These Python excerpts follow one turn of the review. **Full program** combines them in one runnable file.



  


Here, `sessions` is `OpenAI().beta.agents.sessions`. Herringbone opens the event stream before sending the message. When the session needs a function result, the loop passes each pending call to `answer_call` and keeps listening until the turn ends.

    Send the review task

```python
def review_export(sessions, session_id, authorized_exports):
    task = """Herringbone now returns payments one page at a time.
Send next_cursor back as cursor to fetch the next page.
Review Customer A's nightly export. What should the customer change?"""
    message = {
        "type": "agent.session.input.message",
        "input": [{"role": "user", "content": [{"type": "input_text", "text": task}]}],
    }
    key = str(uuid4())
    results = {}
    with sessions.events.stream(session_id) as events:
        sessions.events.create(session_id, events=[message], idempotency_key=key)
        for event in events:
            if event.type == "agent.session.requires_action":
                for call in event.session.required_actions:
                    answer_call(sessions, session_id, call, authorized_exports, results)
            elif event.type == "agent.session.turn.completed":
                return event.turn.id
            elif event.type in {
                "agent.session.turn.failed",
                "agent.session.turn.cancelled",
                "agent.session.failed",
                "error",
            }:
                raise RuntimeError(event.type)
    raise RuntimeError("The stream closed before the turn finished.")
```


  

  


`authorized_exports` maps each session ID to the export records Herringbone may read. The agent supplies no customer ID. Herringbone checks the function name, arguments, and access, then returns the result with the IDs from the pending call.

    Return the tool result

```python
def answer_call(sessions, session_id, call, authorized_exports, results):
    if call.type != "function_call":
        raise ValueError("Unexpected action")
    identity = (session_id, call.turn_id, call.call_id)
    result = {
        "type": "agent.session.input.tool_result",
        "turn_id": call.turn_id,
        "call_id": call.call_id,
    }
    if call.name != "get_integration_context" or call.arguments != {}:
        result.update(success=False, error="Unknown function or unexpected arguments.")
    elif session_id not in authorized_exports:
        result.update(success=False, error="No export authorized for this session.")
    else:
        if identity not in results:
            results[identity] = json.dumps(authorized_exports[session_id])
        result.update(success=True, output=results[identity])
    sessions.events.create(session_id, events=[result])
```


  

  


Set [`OPENAI_API_KEY`](https://developers.openai.com/api/docs/guides/agents-api/quickstart#prerequisites) and copy the program into `review-payment-export.py`. With the Python package manager `uv`, run `uv run --with openai==3.57.0 python review-payment-export.py`.

The program creates a temporary session with an [OpenAI-hosted workspace](https://developers.openai.com/api/docs/guides/agents-api/environments/openai-hosted) and disables network access from the workspace. Your Python process handles the lookup using sample records, so you don’t need GitHub credentials. The program prints the agent’s recommendation for `exports/nightly.http` and deletes the session.

The example keeps the message, key, and function results in memory. To recover after a restart, store them in your app’s database and keep the session.

    review-payment-export.py

```python
import json
from uuid import uuid4

from openai import OpenAI


def review_export(sessions, session_id, authorized_exports):
    task = """Herringbone now returns payments one page at a time.
Send next_cursor back as cursor to fetch the next page.
Review Customer A's nightly export. What should the customer change?"""
    message = {
        "type": "agent.session.input.message",
        "input": [{"role": "user", "content": [{"type": "input_text", "text": task}]}],
    }
    key = str(uuid4())
    results = {}
    with sessions.events.stream(session_id) as events:
        sessions.events.create(session_id, events=[message], idempotency_key=key)
        for event in events:
            if event.type == "agent.session.requires_action":
                for call in event.session.required_actions:
                    answer_call(sessions, session_id, call, authorized_exports, results)
            elif event.type == "agent.session.turn.completed":
                return event.turn.id
            elif event.type in {
                "agent.session.turn.failed",
                "agent.session.turn.cancelled",
                "agent.session.failed",
                "error",
            }:
                raise RuntimeError(event.type)
    raise RuntimeError("The stream closed before the turn finished.")




def answer_call(sessions, session_id, call, authorized_exports, results):
    if call.type != "function_call":
        raise ValueError("Unexpected action")
    identity = (session_id, call.turn_id, call.call_id)
    result = {
        "type": "agent.session.input.tool_result",
        "turn_id": call.turn_id,
        "call_id": call.call_id,
    }
    if call.name != "get_integration_context" or call.arguments != {}:
        result.update(success=False, error="Unknown function or unexpected arguments.")
    elif session_id not in authorized_exports:
        result.update(success=False, error="No export authorized for this session.")
    else:
        if identity not in results:
            results[identity] = json.dumps(authorized_exports[session_id])
        result.update(success=True, output=results[identity])
    sessions.events.create(session_id, events=[result])




def main():
    sessions = OpenAI().beta.agents.sessions
    session = sessions.create(
        agent={
            "model": "gpt-6.2-astra",
            "instructions": """You are a forward-deployed engineer for Herringbone.
Call get_integration_context once before reviewing an API change.
Tell the customer which file is affected, why, and what to update.
Propose changes only. If the lookup fails, report the error.""",
            "tools": [
                {
                    "type": "function",
                    "name": "get_integration_context",
                    "description": "Read the integration records for this session.",
                    "parameters": {
                        "type": "object",
                        "properties": {},
                        "additionalProperties": False,
                    },
                }
            ],
        },
        environment={"type": "openai_hosted", "network": {"access": "disabled"}},
    )
    try:
        # Customer A authorized this session to read only its export.
        authorized_exports = {
            session.id: {
                "path": "exports/nightly.http",
                "code": "GET /v1/payments?limit=100",
                "output_columns": ["payment_id", "amount"],
                "notes": [
                    "The finance team's export makes this request once each night."
                ],
            }
        }
        turn_id = review_export(sessions, session.id, authorized_exports)
        items = sessions.turns.items.list(turn_id, session_id=session.id, order="desc")
        for item in items:
            if item.type == "message" and item.role == "assistant":
                if item.phase != "commentary" and item.output_text:
                    print(item.output_text)
                    return
        raise RuntimeError("The turn completed without a text reply.")
    finally:
        sessions.delete(session.id)


if __name__ == "__main__":
    main()

```


  






**Ask your coding agent:**

```text
When Herringbone changes its API, send a review task to each authorized customer’s Agents API session. Ask how the change affects that integration and what the customer should update. Subscribe to events first and save each message and its idempotency key. On a pending get_integration_context call, check which records the customer authorized the review to read. Run the lookup and return the result with the matching turn and call IDs. Save each result by session, turn, and call ID so you can resend it after a disconnect. Report each turn’s outcome.

Read this lesson for context: https://developers.openai.com/api/training/agents-api/3-send-tasks-and-handle-tool-calls.md
```
