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

## 4. Use environments and artifacts



To give an agent a file to work on, [create a session](https://developers.openai.com/api/training/agents-api/2-create-isolated-sessions.md) with an [OpenAI-hosted environment](https://developers.openai.com/api/docs/guides/agents-api/environments/openai-hosted#configure-the-sandbox). The environment gives the agent a workspace where it can read and edit files and run commands.

To get a file back, ask the agent to write it under `/workspace/outputs`. When the [turn](https://developers.openai.com/api/docs/guides/agents-api/sessions#sessions-and-turns) (one round of work) completes, OpenAI publishes a downloadable copy called an [artifact](https://developers.openai.com/api/docs/guides/agents-api/environments/files#files-and-published-artifacts). That copy stays the same even if the agent edits the working file later.



### Upload input files and download artifacts

1. **Upload an input file** (Your app → OpenAI Agents API, `POST /v1/agents/environments/env_a/files`)

   **Your app**: Uploads the file by environment ID once the environment is connected.

   **OpenAI Agents API**: Writes the decoded file to the connected environment.

   **Request JSON**: `{"type":"inline","path":"/workspace/test-results.txt","data":"RXhwb3J0IHRlc3Q6IGFsbCAzIHBheW1lbnQgSURzIGFwcGVhcmVkIGV4YWN0bHkgb25jZS4K"}`

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

   **Your app**: Uses the returned path in the next message.

   **OpenAI Agents API**: Returns the workspace path and file size.

   **Response JSON**: `{"environment_id":"env_a","object":"agent.environment.file","path":"/workspace/test-results.txt","size_bytes":54}`

3. **Send a task that uses the file** (Your app → OpenAI Agents API, `POST /v1/agents/sessions/sess_a/events`)

   **Your app**: Sends the input path and asks the agent to write a file under `/workspace/outputs`.

   **OpenAI Agents API**: Starts a turn in the idle session.

   **Request JSON**: `{"events":[{"type":"agent.session.input.message","input":[{"role":"user","content":[{"type":"input_text","text":"Summarize /workspace/test-results.txt. Write the finding in the summary field of /workspace/outputs/result.json."}]}]}]}`

4. **Confirm task submission** (OpenAI Agents API → Your app, HTTP response)

   **Your app**: Listens for updates on the session stream.

   **OpenAI Agents API**: Accepts the message and returns HTTP 202.

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

   Learn more: [Session events](https://developers.openai.com/api/docs/guides/agents-api/sessions/events)

5. **Read and write workspace files** (OpenAI Agents API → hosted workspace, Hosted execution)

   **Your app**: Follows the turn on the session stream.

   **OpenAI Agents API**: Runs commands in the hosted environment to read the input and write the output.

   **File operations**: `Read /workspace/test-results.txt` `Write /workspace/outputs/result.json`

   Learn more: [Run commands in a hosted environment](https://developers.openai.com/api/docs/guides/agents-api/architecture#add-an-openai-hosted-environment)

6. **Read the completed turn ID** (OpenAI Agents API → Your app, Streamed event)

   **Your app**: Reads `turn_id` to identify this turn’s files.

   **OpenAI Agents API**: Publishes a fixed copy of each output file as an artifact.

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

   Learn more: [Handle updates](https://developers.openai.com/api/docs/guides/agents-api/sessions/events#handle-updates)

7. **List session artifacts** (Your app → OpenAI Agents API, `GET /v1/agents/sessions/sess_a/artifacts`)

   **Your app**: Requests the list of published files for this session.

   **OpenAI Agents API**: Finds the session’s published artifacts.

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

   Learn more: [List session artifacts](https://developers.openai.com/api/reference/resources/beta/subresources/agents/subresources/sessions/subresources/artifacts/methods/list)

8. **Find the artifact by turn and path** (OpenAI Agents API → Your app, HTTP response)

   **Your app**: Matches the turn ID and path, then reads the artifact ID.

   **OpenAI Agents API**: Returns artifact records and whether more pages follow.

   **Response JSON**: `{"object":"list","data":[{"id":"artifact_export","object":"agent.session.artifact","session_id":"sess_a","environment_id":"env_a","turn_id":"turn_export","path":"/workspace/outputs/result.json","size_bytes":66,"created_at":1789380318}],"first_id":"artifact_export","last_id":"artifact_export","has_more":false}`

9. **Download the artifact** (Your app → OpenAI Agents API, `GET /v1/agents/sessions/sess_a/artifacts/artifact_export/content`)

   **Your app**: Requests the selected artifact’s content by ID.

   **OpenAI Agents API**: Looks up the copy published by the selected turn.

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

   Learn more: [Download content](https://developers.openai.com/api/reference/resources/beta/subresources/agents/subresources/sessions/subresources/artifacts/methods/content)

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

    **Your app**: Reads the file contents and saves a copy if needed.

    **OpenAI Agents API**: Returns the published file’s bytes.

    **Artifact content**: `{"summary":"All three payments appeared once in the export."}`

    Learn more: [Artifact lifetime](https://developers.openai.com/api/docs/guides/agents-api/environments/files#file-lifetime)



### Workspace files and published copies

Use the **environment ID** for files in the live workspace. You can [supply initial files](https://developers.openai.com/api/docs/guides/agents-api/environments/files#upload-files) in `environment.files` when you create the session. To [upload a file later](https://developers.openai.com/api/reference/resources/beta/subresources/agents/subresources/environments/subresources/files/methods/create), wait until the environment [reports `connected`](https://developers.openai.com/api/docs/guides/agents-api/environments/openai-hosted#check-that-setup-succeeded). If the supplied files are all the agent needs, you can [disable network access](https://developers.openai.com/api/docs/guides/agents-api/environments/openai-hosted#control-network-access).

Use the **session ID** to [tell the agent what to do with the files](https://developers.openai.com/api/training/agents-api/3-send-tasks-and-handle-tool-calls.md) and to [find the artifacts it publishes](https://developers.openai.com/api/docs/guides/agents-api/environments/files#openai-hosted-artifacts). A later turn can overwrite a workspace file. Each published copy has its own artifact ID and identifies the turn that produced it.

### Example: Report whether a payment export passed its test



Herringbone, a fictional payments API provider, now returns payments one page
  at a time. Customer A, a startup, exports those payments each night for its
  finance team. At Herringbone’s request, Customer A’s [AI forward-deployed
  engineer](https://developers.openai.com/api/training/agents-api.md#use-case-ai-forward-deployed-engineer) proposes updating the export
  to fetch every page. Herringbone tests the proposed change with three sample
  payments split across two pages. It asks the agent to read the test log and
  report whether the export missed any payments or counted any twice.



Herringbone uses two IDs from the [session creation response](https://developers.openai.com/api/reference/resources/beta/subresources/agents/subresources/sessions/methods/create) to get the log to the agent.

- With `environment.id` (`env_a`), Herringbone uploads the log to `/workspace/test-results.txt` once the workspace is ready.
- With the session `id` (`sess_a`), Herringbone asks the agent to read that path and write a summary to `/workspace/outputs/result.json`.

The agent reads the log and writes “All three payments appeared once in the export” in the report’s `summary` field. Once the turn completes, Herringbone can [retrieve the agent’s reply and the published report](https://developers.openai.com/api/training/agents-api/5-inspect-session-results-and-artifacts.md), even after the workspace expires.



  


The log lists the payment IDs on each page and the IDs the job exported. Here, `environments` is `OpenAI().beta.agents.environments`. Once the environment reports `connected`, Herringbone encodes the log as a base64 string and uploads it to `/workspace/test-results.txt`.

    Write the test log to the workspace

```python
def upload_log(environments, environment_id, log):
    deadline = time.monotonic() + 120
    while True:
        status = environments.retrieve(environment_id).status
        if status == "connected":
            break
        if status not in {"pending", "ready"}:
            raise RuntimeError(f"Workspace is {status}")
        if time.monotonic() >= deadline:
            raise TimeoutError("Workspace did not connect in time.")
        time.sleep(2)

    return environments.files.create(
        environment_id,
        path="/workspace/test-results.txt",
        type="inline",
        data=base64.b64encode(log).decode("ascii"),
    )
```


  

  


Here, `sessions` is `OpenAI().beta.agents.sessions`. Herringbone sends the uploaded file’s path and the destination for the report in a [session message](https://developers.openai.com/api/docs/guides/agents-api/sessions#continue-or-steer-the-work). The completion event supplies the turn ID for retrieving the published copy.

    Ask the agent to write the report

```python
def request_report(sessions, session_id, log_path, report_path):
    task = f"""Read Customer A's nightly export test log at {log_path}.
Write a JSON object to {report_path}. In its summary string, state
how many test payments appeared exactly once and whether any were
missing or duplicated. Include the full report path in your reply."""
    message = {
        "type": "agent.session.input.message",
        "input": [{"role": "user", "content": [{"type": "input_text", "text": task}]}],
    }
    with sessions.events.stream(session_id) as events:
        sessions.events.create(
            session_id, events=[message], idempotency_key=str(uuid4())
        )
        for event in events:
            if event.type == "agent.session.turn.completed":
                return event.turn.id
            if 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.")
```


  

  


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

The program creates a temporary session with an OpenAI-hosted workspace and uploads a sample test log. It prints the assistant’s reply and the report’s summary, then deletes the session and its artifacts.

    publish-and-retrieve-report.py

```python
import base64
import json
import time
from uuid import uuid4

from openai import OpenAI


def upload_log(environments, environment_id, log):
    deadline = time.monotonic() + 120
    while True:
        status = environments.retrieve(environment_id).status
        if status == "connected":
            break
        if status not in {"pending", "ready"}:
            raise RuntimeError(f"Workspace is {status}")
        if time.monotonic() >= deadline:
            raise TimeoutError("Workspace did not connect in time.")
        time.sleep(2)

    return environments.files.create(
        environment_id,
        path="/workspace/test-results.txt",
        type="inline",
        data=base64.b64encode(log).decode("ascii"),
    )




def request_report(sessions, session_id, log_path, report_path):
    task = f"""Read Customer A's nightly export test log at {log_path}.
Write a JSON object to {report_path}. In its summary string, state
how many test payments appeared exactly once and whether any were
missing or duplicated. Include the full report path in your reply."""
    message = {
        "type": "agent.session.input.message",
        "input": [{"role": "user", "content": [{"type": "input_text", "text": task}]}],
    }
    with sessions.events.stream(session_id) as events:
        sessions.events.create(
            session_id, events=[message], idempotency_key=str(uuid4())
        )
        for event in events:
            if event.type == "agent.session.turn.completed":
                return event.turn.id
            if 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 read_reply(sessions, session_id, turn_id):
    turn = sessions.turns.retrieve(turn_id, session_id=session_id)
    if turn.status != "completed":
        raise RuntimeError(f"Turn is {turn.status}")

    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:
                return item.output_text
    raise ValueError("No final reply in this turn.")




def read_report(sessions, session_id, turn_id, report_path):
    for artifact in sessions.artifacts.list(session_id):
        if artifact.path == report_path and artifact.turn_id == turn_id:
            file = sessions.artifacts.content(artifact.id, session_id=session_id)
            return json.loads(file.read())["summary"]
    raise FileNotFoundError(f"No {report_path} for turn {turn_id}")




def main():
    agents = OpenAI().beta.agents
    session = agents.sessions.create(
        agent={
            "model": "gpt-6.2-astra",
            "instructions": """You are a forward-deployed engineer for Herringbone.
Base each finding on the customer's test log. Never claim a fix is live
on the strength of a test alone.""",
        },
        environment={"type": "openai_hosted", "network": {"access": "disabled"}},
    )
    try:
        # Sample log from a test of the change proposed for Customer A.
        log = b"""Expected on page 1: pay_1 pay_2
Expected on page 2: pay_3
Exported: pay_1 pay_2 pay_3"""
        uploaded = upload_log(agents.environments, session.environment.id, log)
        path = "/workspace/outputs/result.json"
        turn_id = request_report(agents.sessions, session.id, uploaded.path, path)
        print(read_reply(agents.sessions, session.id, turn_id))
        print(read_report(agents.sessions, session.id, turn_id, path))
    finally:
        agents.sessions.delete(session.id)


if __name__ == "__main__":
    main()

```


  






**Ask your coding agent:**

```text
Create an Agents API session with an OpenAI-hosted environment. Check that the customer authorized access to the test log. Once the environment reports connected, use its ID to upload the log to /workspace/test-results.txt. Use the session ID to ask the agent to summarize that log in /workspace/outputs/result.json. When the turn completes, find the artifact by turn ID and path, then download it by artifact ID.

Read this lesson for context: https://developers.openai.com/api/training/agents-api/4-use-environments-and-artifacts.md
```
