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

## 2. Create isolated sessions



A common agent configuration allows you to encode the behavior and functionality all instances of the agent will share. Customer- and task-specific data lives at the [session](https://developers.openai.com/api/docs/guides/agents-api/sessions#sessions-and-turns) level. Two sessions can use the [same saved agent](https://developers.openai.com/api/training/agents-api/1-create-a-shared-agent-configuration.md) and still have separate messages, tool results, files, and credentials.

To run code, the agent needs an [environment](https://developers.openai.com/api/docs/guides/agents-api/configuration#environment-settings). An OpenAI-hosted environment provides an isolated workspace, or **sandbox**, for files and commands. To let the agent access systems that require authentication, attach a [**vault**](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults) that holds credentials such as API tokens. Your app decides which resources to attach and which application users can interact with a session.



### Isolate session history, files, and credentials

1. **Create a vault** (Your app → OpenAI Agents API, `POST /v1/vaults`)

   **Your app**: Checks the caller’s permissions and requests a vault.

   **OpenAI Agents API**: Creates a vault that can hold credentials.

   **Request JSON**: `{"name":"Customer A repository access"}`

   Learn more: [Create a vault](https://developers.openai.com/api/reference/resources/beta/subresources/agents/subresources/vaults/methods/create)

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

   **Your app**: Uses the returned ID to add a credential to the vault.

   **OpenAI Agents API**: Returns the new vault.

   **Response JSON**: `{"id":"vault_a","object":"vault","name":"Customer A repository access","metadata":{},"created_at":1789380020}`

3. **Limit where the token can be used** (Your app → OpenAI Agents API, `POST /v1/vaults/vault_a/credentials`)

   **Your app**: Supplies the token in `secret_value` and specifies which hosts may receive it.

   **OpenAI Agents API**: Stores the token and its allowed hosts.

   **Request JSON**: `{"name":"Read Customer A’s repository","auth":{"type":"environment_variable","secret_name":"GITHUB_TOKEN","networking":{"type":"limited","allowed_hosts":["api.github.com"]},"secret_value":"example-token-for-training-only"}}`

   Learn more: [Use a vault secret from a sandbox](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults#use-vault-secrets-for-api-requests-from-a-sandbox)

4. **Read the credential settings** (OpenAI Agents API → Your app, HTTP response)

   **Your app**: Includes the vault ID in the session’s `vault_ids` list.

   **OpenAI Agents API**: Returns the credential settings and keeps the token secret.

   **Response JSON**: `{"id":"cred_repo_a","object":"vault.credential","vault_id":"vault_a","name":"Read Customer A’s repository","auth":{"type":"environment_variable","secret_name":"GITHUB_TOKEN","networking":{"type":"limited","allowed_hosts":["api.github.com"]}},"metadata":{},"created_at":1789380030,"updated_at":1789380030}`

   Learn more: [Attach a vault to a hosted session](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults#attach-the-vault-to-a-hosted-session)

5. **Create a hosted session** (Your app → OpenAI Agents API, `POST /v1/agents/sessions`)

   **Your app**: Sends the saved agent ID and vault ID and restricts sandbox network access to the required host.

   **OpenAI Agents API**: Creates a session from the shared configuration and starts preparing its hosted sandbox.

   **Request JSON**: `{"agent_id":"agent_abc123","vault_ids":["vault_a"],"environment":{"type":"openai_hosted","network":{"access":"restricted","allowed_domains":["api.github.com"]}}}`

6. **Read the session and environment IDs** (OpenAI Agents API → Your app, HTTP response)

   **Your app**: Uses the session ID for messages and the environment ID for files.

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

   **Response JSON**: `{"id":"sess_a","status":"idle","environment":{"id":"env_a","type":"openai_hosted"},"vault_ids":["vault_a"]}`

7. **Record who owns the session** (Your app → application records, Application operation)

   **Your app**: Stores the session, environment, and vault IDs with the session owner’s record.

   **Application record**: `{"customer_id":"customer_a","session_id":"sess_a","environment_id":"env_a","vault_id":"vault_a"}`

   Learn more: [Application responsibilities](https://developers.openai.com/api/docs/guides/agents-api/architecture#the-pieces)

8. **Check access to the session** (application records → Your app, Application operation)

   **Your app**: Checks the signed-in user’s access to the session owner’s record before looking up the resource IDs.

   **Application lookup result**: `{"customer_id":"customer_a","session_id":"sess_a","environment_id":"env_a","vault_id":"vault_a"}`

   Learn more: [Inspect a session](https://developers.openai.com/api/docs/guides/agents-api/sessions/manage#inspect-a-session)

9. **Check whether the workspace is ready** (Your app → OpenAI Agents API, `GET /v1/agents/environments/env_a`)

   **Your app**: Requests the environment by ID before uploading files.

   **OpenAI Agents API**: Looks up the environment’s connection status.

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

   Learn more: [Retrieve an environment](https://developers.openai.com/api/reference/resources/beta/subresources/agents/subresources/environments/methods/retrieve)

10. **Read the environment status** (OpenAI Agents API → Your app, HTTP response)

    **Your app**: Can upload files now that the environment reports `connected`.

    **OpenAI Agents API**: Returns the current environment status.

    **Response JSON**: `{"id":"env_a","object":"agent.environment","type":"openai_hosted","status":"connected","files":[],"skills":[],"plugins":[]}`



### Assign resources to a session

Here are the key components of a session you can specify [when you create it](https://developers.openai.com/api/reference/resources/beta/subresources/agents/subresources/sessions/methods/create).

| Field         | What it selects                                                                                                                                                                                                                                 |
| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `agent_id`    | The saved agent whose model, instructions, and tools the session copies.                                                                                                                                                                        |
| `environment` | Set `type` to `openai_hosted` for a new workspace. Choose its [initial files](https://developers.openai.com/api/docs/guides/agents-api/environments/files#upload-files) and [network access](https://developers.openai.com/api/docs/guides/agents-api/environments/openai-hosted#control-network-access). |
| `vault_ids`   | The [vaults](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults) that supply credentials. Attach only the vaults this session needs.                                                                                                                      |

In your app, associate the returned session `id` and `environment.id` with the user or customer who owns the session. Use the session ID to [send a task](https://developers.openai.com/api/training/agents-api/3-send-tasks-and-handle-tool-calls.md). Use the environment ID to [work with files](https://developers.openai.com/api/training/agents-api/4-use-environments-and-artifacts.md) once the workspace [reports `connected`](https://developers.openai.com/api/docs/guides/agents-api/environments/openai-hosted#check-that-setup-succeeded).

### Example: Isolate each customer's integration review



Herringbone, a fictional payments API provider, now returns payments one
    page at a time. When more payments are available, the response includes a
    cursor, a value the caller sends back to fetch the next page. Herringbone
    asks its [AI forward-deployed
    engineers](https://developers.openai.com/api/training/agents-api.md#use-case-ai-forward-deployed-engineer) to check each customer’s
    code before notifying them about the change.
  

  

    Customer A is a startup whose nightly export copies payment IDs and amounts
    into a finance report. To check whether the export reads every page, its
    agent needs the code in Customer A’s private GitHub repository,
    `customer-a/payments-export`.
  

  

    Customer B is an enterprise whose internal apps use a proxy, a service that
    forwards their requests to Herringbone. To check whether the proxy forwards
    the cursor when an app requests page two, its agent needs access to Customer
    B’s private GitHub repository, `customer-b/payments-proxy`.



Each customer has already authorized these reviews and supplied a GitHub token with read-only access to its own repository. Herringbone [stores each token in a dedicated vault](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults#store-the-api-token).

When the API changes, Herringbone creates both sessions using the same shared agent configuration. Each call to `agents.sessions.create` attaches the customer’s vault and copies its test data into a new workspace. The examples omit `input`, so both sessions start `idle`, with no work in progress.

To start each review, Herringbone’s app [sends a message to the session](https://developers.openai.com/api/training/agents-api/3-send-tasks-and-handle-tool-calls.md) describing the change and asking the agent to propose any necessary updates. It could also [include that task at creation](https://developers.openai.com/api/docs/guides/agents-api/sessions#start-work).

In the Python examples, `agents` is `OpenAI().beta.agents` and `db` is a SQLite database. The customer tabs show which vault and test data Herringbone selects for each session. **Shared backend** shows the access checks. **Full program** sets up both reviews and tests those checks.



  

    

      Herringbone gives the agent two pages of sample payments so it can check
      whether the export includes every payment exactly once. The app saves
      the session and workspace IDs in its review database.
      When a finance user opens the review, the app checks their access and lists its files.
    

    Customer A: open the nightly export review

```python
export_token = os.environ["CUSTOMER_A_GITHUB_TOKEN"]
export_vault = create_repository_vault(
    agents, cleanup, "customer-a/payments-export", export_token
)
export_session = agents.sessions.create(
    agent_id=shared_agent_id,
    vault_ids=[export_vault],
    environment={
        "type": "openai_hosted",
        "network": {
            "access": "restricted",
            "allowed_domains": ["api.github.com"],
        },
        "files": [inline_file("/workspace/export-pages.json", export_pages)],
    },
)

save_session(db, "customer-a", "payments-export", export_session)

export_review = inspect_customer_session(
    agents, db, "finance-user", "customer-a", "payments-export"
)
```

  

  

    

      For the proxy review, the agent needs to compare the URL the app sends
      with the URL the proxy should forward. Herringbone supplies a sample of both
      and saves this session and workspace under Customer B’s integration.
      A member of the proxy team can then open the review.
    

    Customer B: open the proxy review

```python
proxy_token = os.environ["CUSTOMER_B_GITHUB_TOKEN"]
proxy_vault = create_repository_vault(
    agents, cleanup, "customer-b/payments-proxy", proxy_token
)
proxy_session = agents.sessions.create(
    agent_id=shared_agent_id,
    vault_ids=[proxy_vault],
    environment={
        "type": "openai_hosted",
        "network": {
            "access": "restricted",
            "allowed_domains": ["api.github.com"],
        },
        "files": [inline_file("/workspace/proxy-request.json", proxy_request)],
    },
)

save_session(db, "customer-b", "payments-proxy", proxy_session)

proxy_review = inspect_customer_session(
    agents, db, "proxy-user", "customer-b", "payments-proxy"
)
```

  

  

    

      Both workspaces need to reach `api.github.com` to read code.
      The environment’s `allowed_domains` permits that connection.
      Inside the workspace, `GITHUB_TOKEN` contains a placeholder.
      On HTTPS requests to a host in the credential’s `allowed_hosts`,
      OpenAI’s network proxy [replaces the placeholder with the token](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults#call-the-api-from-the-sandbox).
      GitHub enforces the token’s repository permissions.
    

    Store a repository token and prepare a workspace file

```python
def create_repository_vault(agents, cleanup, repository, token):
    vault = agents.vaults.create(name=repository)
    cleanup.callback(agents.vaults.delete, vault.id)
    agents.vaults.credentials.create(
        vault.id,
        name="GitHub repository token",
        auth={
            "type": "environment_variable",
            "secret_name": "GITHUB_TOKEN",
            "secret_value": token,
            "networking": {"type": "limited", "allowed_hosts": ["api.github.com"]},
        },
    )
    return vault.id


def inline_file(path, test_data):
    encoded = base64.b64encode(json.dumps(test_data).encode()).decode()
    return {"type": "inline", "path": path, "data": encoded}
```

    

      Herringbone’s backend reads its own membership database using the user ID
      from its sign-in system. The query returns the session and environment IDs
      only for an integration the user can access. The backend then waits for
      the environment to report `connected` before listing files.
    

    Save the review and look it up after sign-in

```python
def save_session(db, customer, integration, session):
    with db:
        db.execute(
            """INSERT INTO reviews (customer, integration, session_id, environment_id)
               VALUES (?, ?, ?, ?)""",
            (customer, integration, session.id, session.environment.id),
        )


def inspect_customer_session(agents, db, signed_in_user, customer, integration):
    row = db.execute(
        """SELECT session_id, environment_id FROM reviews
           JOIN memberships USING (customer, integration)
           WHERE user_id = ? AND customer = ? AND integration = ?""",
        (signed_in_user, customer, integration),
    ).fetchone()
    if row is None:
        raise PermissionError("No access to this review")

    session_id, environment_id = row
    session = agents.sessions.retrieve(session_id)
    deadline = time.monotonic() + 120
    while time.monotonic() < deadline:
        status = agents.environments.retrieve(environment_id).status
        if status == "connected":
            files = agents.environments.files.list(environment_id, path="/workspace")
            return session.id, environment_id, [file.path for file in files]
        if status in {"failed", "expired", "disconnected", "suspended"}:
            raise RuntimeError(f"Workspace is {status}")
        time.sleep(2)
    raise TimeoutError("Workspace did not connect in time")
```

  

  


Copy the program into `isolate-customer-sessions.py`. Set `shared_agent_id` to the ID of a [saved agent in your project](https://developers.openai.com/api/docs/guides/agents-api/configuration#reuse-an-agent-across-sessions). Set `OPENAI_API_KEY` to a project key with [vault permissions](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults#permissions). Set `CUSTOMER_A_GITHUB_TOKEN` and `CUSTOMER_B_GITHUB_TOKEN` to read-only tokens for two repositories you control.

With `uv`, a Python package manager, run `uv run --with openai==3.42.0 python isolate-customer-sessions.py`. Expect `Cross-customer access denied` when the finance user tries to open the proxy review, then the IDs and files for each authorized review. The program tests Herringbone’s access checks without sending a task or calling GitHub. It deletes the sessions and vaults it created when it exits.

    isolate-customer-sessions.py

```python
"""Set up isolated export and proxy reviews with one saved Herringbone agent."""

import base64
import json
import os
import sqlite3
import time
from contextlib import ExitStack, closing
from pathlib import Path
from tempfile import TemporaryDirectory

from openai import ConflictError, OpenAI


def create_repository_vault(agents, cleanup, repository, token):
    vault = agents.vaults.create(name=repository)
    cleanup.callback(agents.vaults.delete, vault.id)
    agents.vaults.credentials.create(
        vault.id,
        name="GitHub repository token",
        auth={
            "type": "environment_variable",
            "secret_name": "GITHUB_TOKEN",
            "secret_value": token,
            "networking": {"type": "limited", "allowed_hosts": ["api.github.com"]},
        },
    )
    return vault.id


def inline_file(path, test_data):
    encoded = base64.b64encode(json.dumps(test_data).encode()).decode()
    return {"type": "inline", "path": path, "data": encoded}




def delete_session(agents, session_id):
    for attempt in range(10):
        try:
            agents.sessions.delete(session_id)
            return
        except ConflictError:
            if attempt == 9:
                raise
            time.sleep(2)


def initialize_store(db):
    db.executescript("""
        CREATE TABLE reviews (
            customer TEXT, integration TEXT, session_id TEXT UNIQUE,
            environment_id TEXT UNIQUE, PRIMARY KEY (customer, integration)
        );
        CREATE TABLE memberships (
            user_id TEXT, customer TEXT, integration TEXT,
            PRIMARY KEY (user_id, customer, integration)
        );
        INSERT INTO memberships VALUES
            ('finance-user', 'customer-a', 'payments-export'),
            ('proxy-user', 'customer-b', 'payments-proxy');
    """)


def save_session(db, customer, integration, session):
    with db:
        db.execute(
            """INSERT INTO reviews (customer, integration, session_id, environment_id)
               VALUES (?, ?, ?, ?)""",
            (customer, integration, session.id, session.environment.id),
        )


def inspect_customer_session(agents, db, signed_in_user, customer, integration):
    row = db.execute(
        """SELECT session_id, environment_id FROM reviews
           JOIN memberships USING (customer, integration)
           WHERE user_id = ? AND customer = ? AND integration = ?""",
        (signed_in_user, customer, integration),
    ).fetchone()
    if row is None:
        raise PermissionError("No access to this review")

    session_id, environment_id = row
    session = agents.sessions.retrieve(session_id)
    deadline = time.monotonic() + 120
    while time.monotonic() < deadline:
        status = agents.environments.retrieve(environment_id).status
        if status == "connected":
            files = agents.environments.files.list(environment_id, path="/workspace")
            return session.id, environment_id, [file.path for file in files]
        if status in {"failed", "expired", "disconnected", "suspended"}:
            raise RuntimeError(f"Workspace is {status}")
        time.sleep(2)
    raise TimeoutError("Workspace did not connect in time")




def print_review(customer, integration, review):
    session_id, environment_id, files = review
    print(
        json.dumps(
            dict(
                customer=customer,
                integration=integration,
                session_id=session_id,
                environment_id=environment_id,
                files=files,
            )
        )
    )


def main():
    with ExitStack() as cleanup:
        agents = cleanup.enter_context(OpenAI()).beta.agents
        directory = cleanup.enter_context(TemporaryDirectory())
        db = cleanup.enter_context(
            closing(sqlite3.connect(Path(directory) / "reviews.db"))
        )
        initialize_store(db)
        shared_agent_id = "agent_abc123"  # Use the id returned by POST /v1/agents for your saved agent.

        export_pages = [
            {
                "payments": [
                    {"payment_id": "p1", "amount": 10},
                    {"payment_id": "p2", "amount": 20},
                ],
                "next_cursor": "c2",
            },
            {"payments": [{"payment_id": "p3", "amount": 30}], "next_cursor": None},
        ]
        export_token = os.environ["CUSTOMER_A_GITHUB_TOKEN"]
        export_vault = create_repository_vault(
            agents, cleanup, "customer-a/payments-export", export_token
        )
        export_session = agents.sessions.create(
            agent_id=shared_agent_id,
            vault_ids=[export_vault],
            environment={
                "type": "openai_hosted",
                "network": {
                    "access": "restricted",
                    "allowed_domains": ["api.github.com"],
                },
                "files": [inline_file("/workspace/export-pages.json", export_pages)],
            },
        )
        cleanup.callback(delete_session, agents, export_session.id)
        save_session(db, "customer-a", "payments-export", export_session)

        proxy_request = {
            "incoming": "/proxy/payments?cursor=c2",
            "outgoing": "/v1/payments?cursor=c2",
        }
        proxy_token = os.environ["CUSTOMER_B_GITHUB_TOKEN"]
        proxy_vault = create_repository_vault(
            agents, cleanup, "customer-b/payments-proxy", proxy_token
        )
        proxy_session = agents.sessions.create(
            agent_id=shared_agent_id,
            vault_ids=[proxy_vault],
            environment={
                "type": "openai_hosted",
                "network": {
                    "access": "restricted",
                    "allowed_domains": ["api.github.com"],
                },
                "files": [inline_file("/workspace/proxy-request.json", proxy_request)],
            },
        )
        cleanup.callback(delete_session, agents, proxy_session.id)
        save_session(db, "customer-b", "payments-proxy", proxy_session)

        try:
            inspect_customer_session(
                agents, db, "finance-user", "customer-b", "payments-proxy"
            )
        except PermissionError:
            print("Cross-customer access denied")
        else:
            raise AssertionError("Finance user could access the proxy review")

        export_review = inspect_customer_session(
            agents, db, "finance-user", "customer-a", "payments-export"
        )
        print_review("customer-a", "payments-export", export_review)

        proxy_review = inspect_customer_session(
            agents, db, "proxy-user", "customer-b", "payments-proxy"
        )
        print_review("customer-b", "payments-proxy", proxy_review)


if __name__ == "__main__":
    main()

```


  






**Ask your coding agent:**

```text
Create a hosted session per integration using the shared agent ID. Attach the customer's vault and restrict network access to the repository API. Save the session and environment IDs with the customer and integration. Check access before using either ID and wait for the environment to report connected before uploading files.

Read this lesson for context: https://developers.openai.com/api/training/agents-api/2-create-isolated-sessions.md
```
