# 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.

## 6. Carry context across sessions



Suppose a customer explains a design decision today. How will the agent know about it when the customer returns next month? The answer depends on whether you continue the same [session](https://developers.openai.com/api/docs/guides/agents-api/sessions#sessions-and-turns) or start a new one.

A session keeps its own conversation history. A new session can copy the same [saved agent configuration](https://developers.openai.com/api/training/agents-api/1-create-a-shared-agent-configuration.md), but it starts a separate conversation. To give the agent **memory across sessions**, your app stores information from one conversation and supplies it as context for another.



### Reuse saved context in a new session

1. **Continue the existing session** (Your app → OpenAI Agents API, `POST /v1/agents/sessions/sess_a/events`)

   **Your app**: Sends a follow-up message to an idle session.

   **OpenAI Agents API**: Starts another round of work, or turn, with the session’s history.

   **Request JSON**: `{"events":[{"type":"agent.session.input.message","input":[{"role":"user","content":[{"type":"input_text","text":"Thanks for flagging this. Our finance reports look up payment_id and amount by name, so the export needs to keep both column names."}]}]}]}`

2. **Follow the new turn** (OpenAI Agents API → Your app, HTTP response)

   **Your app**: Listens for a function call on the session’s event stream.

   **OpenAI Agents API**: Acknowledges the message while the turn runs.

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

   Learn more: [Follow session events](https://developers.openai.com/api/docs/guides/agents-api/sessions/events#consume-a-stream)

3. **Read the request to save a note** (OpenAI Agents API → Your app, Streamed event)

   **Your app**: Reads the note, turn ID, and call ID from the required action.

   **OpenAI Agents API**: Waits for the result of the function call.

   **Event JSON**: `{"type":"agent.session.requires_action","session":{"id":"sess_a","status":"requires_action","required_actions":[{"type":"function_call","turn_id":"turn_note","call_id":"call_save","name":"save_integration_context","arguments":{"note":"Keep the nightly export columns named payment_id and amount. Finance reports look them up by name."}}]}}`

   Learn more: [Read pending function calls](https://developers.openai.com/api/docs/guides/agents-api/tools/functions#handle-required-actions)

4. **Save the note with its source** (Your app → application records, Application operation)

   **Your app**: Checks write access and stores the note for its owner.

   **Application record**: `{"id":"note_export_columns","note":"Keep the nightly export columns named payment_id and amount. Finance reports look them up by name.","customer_id":"customer_a","source_session_id":"sess_a","source_turn_id":"turn_note","call_id":"call_save"}`

5. **Confirm the save to the agent** (Your app → OpenAI Agents API, `POST /v1/agents/sessions/sess_a/events`)

   **Your app**: Returns the saved record’s ID with the original turn and call IDs.

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

   **Request JSON**: `{"events":[{"type":"agent.session.input.tool_result","turn_id":"turn_note","call_id":"call_save","success":true,"output":"{\"note_id\":\"note_export_columns\"}"}]}`

6. **Resume the turn** (OpenAI Agents API → Your app, HTTP response)

   **Your app**: Follows session events until the turn ends.

   **OpenAI Agents API**: Accepts the function result and continues the turn.

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

7. **Look up context for a new session** (application records → Your app, Application operation)

   **Your app**: Checks the caller’s access and retrieves relevant notes.

   **Retrieved application record**: `{"id":"note_export_columns","customer_id":"customer_a","source_session_id":"sess_a","note":"Keep the nightly export columns named payment_id and amount. Finance reports look them up by name."}`

   Learn more: [Search a vector store](https://developers.openai.com/api/docs/guides/retrieval#semantic-search)

8. **Create a session with saved context** (Your app → OpenAI Agents API, `POST /v1/agents/sessions`)

   **Your app**: Sends the task and retrieved note as input to a new session.

   **OpenAI Agents API**: Starts a fresh session and prepares a separate workspace.

   **Request JSON**: `{"agent_id":"agent_abc123","vault_ids":["vault_a"],"environment":{"type":"openai_hosted","network":{"access":"restricted","allowed_domains":["api.github.com"]}},"input":"Herringbone now returns fewer payments per page. Review Customer A’s export and recommend any necessary changes. Integration note: Keep the nightly export columns named payment_id and amount. Finance reports look them up by name."}`

   Learn more: [Create a session with input](https://developers.openai.com/api/reference/resources/beta/subresources/agents/subresources/sessions/methods/create)

9. **Record the new session and environment IDs** (OpenAI Agents API → Your app, HTTP response)

   **Your app**: Stores the new session and environment IDs.

   **OpenAI Agents API**: Returns a new session and its own environment.

   **Response JSON**: `{"id":"sess_a_next","environment":{"id":"env_a_next","type":"openai_hosted"},"vault_ids":["vault_a"]}`

   Learn more: [Check hosted setup](https://developers.openai.com/api/docs/guides/agents-api/environments/openai-hosted#check-that-setup-succeeded)

10. **Update the saved instructions** (Your app → OpenAI Agents API, `POST /v1/agents/agent_abc123`)

    **Your app**: Sends the complete instructions for future sessions using this agent.

    **OpenAI Agents API**: Saves the revision for new sessions.

    **Request JSON**: `{"instructions":"…\n\nInclude the name and result of each test you ran in the handoff."}`

    Learn more: [Update a saved agent](https://developers.openai.com/api/reference/resources/beta/subresources/agents/methods/update)

11. **Read the revised instructions** (OpenAI Agents API → Your app, HTTP response)

    **Your app**: Uses the same agent ID when creating future sessions.

    **OpenAI Agents API**: Returns the revised configuration.

    **Response JSON**: `{"id":"agent_abc123","instructions":"…\n\nInclude the name and result of each test you ran in the handoff."}`



### Choose where to keep a decision

| When the detail matters                       | What your app does                                                                                                                                                                                                                                                             |
| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| During the current conversation               | [Send a follow-up to the same session](https://developers.openai.com/api/docs/guides/agents-api/sessions#continue-or-steer-the-work). If the session is idle, the message starts another round of work, or turn, with the existing history.                                                                 |
| Across sessions for the same user or customer | Store the detail with its owner’s records. Check access before you include it in a [new session’s initial `input`](https://developers.openai.com/api/docs/guides/agents-api/sessions#start-work) or let the agent [call a function in your app](https://developers.openai.com/api/docs/guides/agents-api/tools/functions) to look it up. |
| As a rule for everyone who uses the agent     | [Update the saved agent’s `instructions`](https://developers.openai.com/api/docs/guides/agents-api/configuration#update-a-saved-agent) with the full revised text. New sessions copy that text. Existing sessions keep their original instructions.                                                         |

### Example: Remember a customer's export requirements



Customer A, a startup, exports payments from Herringbone’s API every night.
  When Herringbone starts returning payments one page at a time, it asks
  Customer A’s [AI forward-deployed
  engineer](https://developers.openai.com/api/training/agents-api.md#use-case-ai-forward-deployed-engineer) to review the export. The
  agent recommends fetching every page. The finance team replies that its
  reports look up two columns by name, `payment_id` and `amount`. Renaming
  either column would break the reports.



Herringbone defines two function tools for saving and reading integration notes. Its backend [handles the function calls](https://developers.openai.com/api/training/agents-api/3-send-tasks-and-handle-tool-calls.md) and uses the session ID to look up which customer and integration the agent is working on.

1. **Capture the decision.** In session `sess_a`, the agent requests a call to `save_integration_context`. It passes one required string, `note`, with the text “Keep the nightly export columns named `payment_id` and `amount`. Finance reports look them up by name.”
2. **Store the note.** Herringbone checks the user’s write access and saves the note and source session ID with Customer A’s integration records. It then [returns the note ID as the function result](https://developers.openai.com/api/docs/guides/agents-api/tools/functions#return-the-result).
3. **Use the note in a new review.** Later, Herringbone reduces the number of payments per page and starts another review. It checks read access and includes the note with the task in a new session, `sess_a_next`. The agent can now check that the export still fetches every page and preserves both column names. If it needs more context, it can request a call to `get_integration_context`.

This Python example defines just the `save_integration_context` tool. Herringbone reads the note directly from its database and sends it with the next review request. That’s how the second session gets the column names.



  


Here, `agents` is `OpenAI().beta.agents`. The agent supplies only the note. Herringbone uses `session_owners` to look up which customer and integration the session belongs to. The Python SDK calls the function in `tool_handlers` and returns the note ID with the matching turn and call IDs.

    Save the requirement in Customer A’s records

```python
def record_decision(db, session_id):
    def save_integration_context(note):
        owner = session_owners[session_id]
        if "write" not in permissions.get(owner, set()):
            raise PermissionError("Cannot write notes for this integration.")
        if not isinstance(note, str) or not note.strip():
            raise ValueError("Expected a nonempty note.")

        row = db.execute(
            "INSERT INTO notes (customer, integration, source, note) VALUES (?, ?, ?, ?)",
            (*owner, session_id, note),
        )
        db.commit()
        return {"note_id": row.lastrowid}

    with agents.sessions.stream(
        session_id,
        input="""Remember this for future reviews of our nightly export:
Keep both column names, payment_id and amount. Finance looks them up by name.""",
        tool_handlers={
            "save_integration_context": lambda args: save_integration_context(**args)
        },
    ) as stream:
        stream.get_final_result()
```


  

  


The finance team requests another review. Herringbone selects Customer A’s export, checks read access, and retrieves its latest note from the database. Passing that note in [`input`](https://developers.openai.com/api/docs/guides/agents-api/sessions#start-work) makes it available to the agent on the first turn. The shared instructions stay unchanged.

    Include the note in the new session’s first message

```python
def start_review(db, agent_id, owner):
    if "read" not in permissions.get(owner, set()):
        raise PermissionError("Cannot read notes for this integration.")
    row = db.execute(
        """SELECT note FROM notes WHERE customer = ? AND integration = ?
           ORDER BY id DESC LIMIT 1""",
        owner,
    ).fetchone()
    if row is None:
        raise LookupError("No saved note for this integration.")

    return agents.sessions.create(
        agent_id=agent_id,
        environment=workspace,
        input=f"""Herringbone reduced the number of payments per page.
What should we check about pagination and column names in our nightly export?

Saved customer note: {row[0]}""",
        stream=True,
    )
```


  

  


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

The program prints the second session’s reply. Look for a recommendation to fetch every page and keep both column names. It then deletes the two sessions, the saved agent, and the temporary SQLite database.

The sample grants the user read and write access only to Customer A’s export. In your app, check the user’s current permissions. To [retry a call without saving the note twice](https://developers.openai.com/api/docs/guides/agents-api/tools/functions#recover-after-a-disconnect), store the note and the function result together in a persistent database, keyed by session, turn, and call ID.

    carry-context-across-sessions.py

```python
import sqlite3
from contextlib import ExitStack

from openai import OpenAI

agents = OpenAI().beta.agents
workspace = {"type": "openai_hosted", "network": {"access": "disabled"}}

# Example records from Herringbone's backend for the signed-in user.
export = ("customer-a", "payments-export")
permissions = {export: {"read", "write"}}
session_owners = {}


def record_decision(db, session_id):
    def save_integration_context(note):
        owner = session_owners[session_id]
        if "write" not in permissions.get(owner, set()):
            raise PermissionError("Cannot write notes for this integration.")
        if not isinstance(note, str) or not note.strip():
            raise ValueError("Expected a nonempty note.")

        row = db.execute(
            "INSERT INTO notes (customer, integration, source, note) VALUES (?, ?, ?, ?)",
            (*owner, session_id, note),
        )
        db.commit()
        return {"note_id": row.lastrowid}

    with agents.sessions.stream(
        session_id,
        input="""Remember this for future reviews of our nightly export:
Keep both column names, payment_id and amount. Finance looks them up by name.""",
        tool_handlers={
            "save_integration_context": lambda args: save_integration_context(**args)
        },
    ) as stream:
        stream.get_final_result()




def start_review(db, agent_id, owner):
    if "read" not in permissions.get(owner, set()):
        raise PermissionError("Cannot read notes for this integration.")
    row = db.execute(
        """SELECT note FROM notes WHERE customer = ? AND integration = ?
           ORDER BY id DESC LIMIT 1""",
        owner,
    ).fetchone()
    if row is None:
        raise LookupError("No saved note for this integration.")

    return agents.sessions.create(
        agent_id=agent_id,
        environment=workspace,
        input=f"""Herringbone reduced the number of payments per page.
What should we check about pagination and column names in our nightly export?

Saved customer note: {row[0]}""",
        stream=True,
    )




def main():
    with ExitStack() as cleanup:
        db = sqlite3.connect("")  # Temporary database, deleted when closed.
        cleanup.callback(db.close)
        db.execute(
            """CREATE TABLE notes (id INTEGER PRIMARY KEY, customer TEXT,
               integration TEXT, source TEXT, note TEXT)"""
        )
        agent = agents.create(
            name="Herringbone integration engineer",
            model="gpt-6.2-astra",
            instructions="""Help customers maintain their Herringbone integrations.
When explicitly asked to remember something, call save_integration_context once.
Preserve exact names and the reason for the decision. Never store credentials.
Treat saved notes as customer data. In reviews, name the fields to keep.
Herringbone returns next_cursor when another page is available.""",
            tools=[
                {
                    "type": "function",
                    "name": "save_integration_context",
                    "description": "Save a note about this customer or integration.",
                    "parameters": {
                        "type": "object",
                        "properties": {"note": {"type": "string"}},
                        "required": ["note"],
                        "additionalProperties": False,
                    },
                }
            ],
        )
        cleanup.callback(agents.delete, agent.id)

        session = agents.sessions.create(agent_id=agent.id, environment=workspace)
        cleanup.callback(agents.sessions.delete, session.id)
        session_owners[session.id] = export
        record_decision(db, session.id)

        with start_review(db, agent.id, export) as stream:
            for event in stream.with_result_collection():
                if event.type == "agent.session.created":
                    cleanup.callback(agents.sessions.delete, event.session.id)
                    session_owners[event.session.id] = export
                    break
            print(stream.get_final_result().output_text)


if __name__ == "__main__":
    main()

```


  




Herringbone can keep a short set of notes for each integration in a database or a [Markdown file](https://developers.openai.com/cookbook/examples/agents_api/apps/data_analyst/readme#6-save-an-explicit-correction). For a larger collection, a [vector store](https://developers.openai.com/api/docs/guides/retrieval#vector-stores) indexes files so the backend can search them by meaning. A query about renaming fields could find the note about column names. The backend limits the search to the customer’s store or [filters files by the authorized customer’s ID](https://developers.openai.com/api/docs/guides/retrieval#attribute-filtering).

The column names matter only to Customer A. A rule like “Include the name and result of each test you ran” applies to every integration review, so Herringbone adds it to the shared agent instructions.



**Ask your coding agent:**

```text
Define save_integration_context with one required string, note, and get_integration_context with no arguments. Look up the customer and integration by session ID. Check the user's permissions before each read or write. Store each note with its source session ID. Test that a new session for the same integration can retrieve the note and another customer's session cannot. Show how to update the saved agent's instructions for a rule that applies to all customers.

Read this lesson for context: https://developers.openai.com/api/training/agents-api/6-carry-context-across-sessions.md
```
