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

## 5. Inspect session results and artifacts








If a user leaves while an agent is working, your app can show them the results when they return, even if it [missed the live events](https://developers.openai.com/api/docs/guides/agents-api/sessions/events#how-to-recover-a-disconnected-stream). The session ID identifies the conversation. The turn ID identifies [one round of work](https://developers.openai.com/api/docs/guides/agents-api/sessions#sessions-and-turns) in that conversation.

The Agents API saves messages and tool calls as [items](https://developers.openai.com/api/docs/guides/agents-api/sessions/events#fetch-items-and-turns). If the agent writes a file under `/workspace/outputs` in an [OpenAI-hosted environment](https://developers.openai.com/api/training/agents-api/4-use-environments-and-artifacts.md), OpenAI publishes a copy called an **artifact** when the turn completes. The turn ID lets you match the agent’s reply to the right copy, even if a later turn writes to the same path.



### Retrieve a turn’s reply and artifacts

1. **Retrieve the turn** (Your app → OpenAI Agents API, `GET /v1/agents/sessions/sess_a/turns/turn_export`)

   **Your app**: Requests the turn by session ID and turn ID.

   **OpenAI Agents API**: Looks up the turn in the specified session.

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

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

   **Your app**: Checks the status on the returned turn.

   **OpenAI Agents API**: Returns the saved turn record.

   **Response JSON**: `{"id":"turn_export","object":"agent.session.turn","session_id":"sess_a","agent_id":"agent_abc123","subagent_id":null,"status":"completed","created_at":1789380300,"started_at":1789380300,"completed_at":1789380320,"error":null,"usage":null}`

3. **List the turn’s saved items** (Your app → OpenAI Agents API, `GET /v1/agents/sessions/sess_a/turns/turn_export/items?order=asc`)

   **Your app**: Requests the main agent’s saved items, oldest first.

   **OpenAI Agents API**: Looks up the messages and tool calls for this turn.

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

4. **Read the assistant’s reply** (OpenAI Agents API → Your app, HTTP response)

   **Your app**: Reads the assistant message that names the output path.

   **OpenAI Agents API**: Returns the assistant message as a saved item.

   **Response JSON**: `{"object":"list","first_id":"msg_report","data":[{"id":"msg_report","turn_id":"turn_export","type":"message","role":"assistant","status":"completed","phase":"final_answer","content":[{"type":"output_text","text":"I summarized the nightly export test in /workspace/outputs/result.json."}]}],"has_more":false,"last_id":"msg_report"}`

   Learn more: [Read saved work](https://developers.openai.com/api/docs/guides/agents-api/sessions#retrieve-saved-work)

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

   **Your app**: Looks up the file named in the reply.

   **OpenAI Agents API**: Finds the files published by this session’s hosted turns.

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

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

   **Your app**: Selects the artifact matching the turn ID and path.

   **OpenAI Agents API**: Returns each artifact’s ID, turn ID, and path.

   **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}`

   Learn more: [Retrieve hosted files](https://developers.openai.com/api/docs/guides/agents-api/environments/files#from-an-openai-hosted-environment)

7. **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**: Retrieves the published file.

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

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

   **Your app**: Reads the file returned in the response body.

   **OpenAI Agents API**: Returns the artifact’s contents.

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



### Retrieve a reply and its files

If you have only the session ID, [list its turns](https://developers.openai.com/api/reference/resources/beta/subresources/agents/subresources/sessions/subresources/turns/methods/list) and use their timestamps to find the one you need. [Retrieve the turn](https://developers.openai.com/api/reference/resources/beta/subresources/agents/subresources/sessions/subresources/turns/methods/retrieve) to check its `status`. If the status is `failed`, [inspect the error](https://developers.openai.com/api/docs/guides/agents-api/errors#inspect-an-error). For a completed turn, the reply and files come from different API resources.

| Result        | Where to find it                                                                                                                                                                                                                                                                                                                       |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Agent’s reply | [List the turn’s items](https://developers.openai.com/api/reference/resources/beta/subresources/agents/subresources/sessions/subresources/turns/subresources/items/methods/list) for the main agent. Look for a `message` with `role: "assistant"`. When present, `phase: "final_answer"` marks the final reply. Read the text of its `output_text` parts.          |
| Output file   | [List the session’s artifacts](https://developers.openai.com/api/reference/resources/beta/subresources/agents/subresources/sessions/subresources/artifacts/methods/list). Match both `turn_id` and `path`, then [download the file](https://developers.openai.com/api/reference/resources/beta/subresources/agents/subresources/sessions/subresources/artifacts/methods/content) by artifact ID. |

You can [download artifacts after the environment expires](https://developers.openai.com/api/docs/guides/agents-api/environments/files#file-lifetime). Save any files you need to keep before deleting the session.

### Example: Show a customer the results of its pagination test



Herringbone’s payments API now returns payments one page at a time.
  Herringbone asks each customer’s [AI forward-deployed
  engineer](https://developers.openai.com/api/training/agents-api.md#use-case-ai-forward-deployed-engineer) to review the integration.
  Customer A’s nightly export needs to count each payment exactly once. Customer
  C, a reseller, needs to return a single `payments` array to its
  merchants. Herringbone tests both proposed changes so each agent can include
  the results with its recommendation.



Herringbone uses a [separate session for each customer](https://developers.openai.com/api/training/agents-api/2-create-isolated-sessions.md). In both sessions, the agent writes to `/workspace/outputs/result.json`. Each time a report is ready, Herringbone saves the `session_id` and `turn_id` from the [completion event](https://developers.openai.com/api/docs/guides/agents-api/sessions/events#handle-updates) with the customer’s test run.

For Customer A, Herringbone’s app looks up the session (`sess_a`) and turn (`turn_export`). The saved reply names the report’s path. The app matches that path and turn ID to the artifact `artifact_export`, downloads it, and reads its `summary` field.



  


Here, `sessions` is `OpenAI().beta.agents.sessions`. Herringbone reads the completed turn’s items, newest first, and skips progress messages marked `commentary`. In the Python SDK, `item.output_text` joins the text parts of one message.

    Read the assistant’s final reply

```python
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.")
```


  

  


Herringbone sets `report_path` to `/workspace/outputs/result.json`, the path it asked the agent to use. The SDK fetches more pages of [session artifacts](https://developers.openai.com/api/docs/guides/agents-api/environments/files#openai-hosted-artifacts) as needed. Herringbone downloads the copy from the matching turn.

    Read the summary from the matching artifact

```python
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}")
```


  

  


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()

```


  




The app notifies Customer A’s finance team and checks each user’s access when they open the review. Here’s what the FDE might tell them.

> Herringbone now returns payments one page at a time. Your nightly export makes only one request, so your report will miss any payments after the first page. Update the export to send each `next_cursor` value back as `cursor` until there are no more pages. In a test of this change, all three sample payments appeared exactly once. Your live export hasn’t changed.

The app uses Customer C’s session and turn IDs to retrieve a different report at the same path. The FDE advises the reseller to fetch all pages and combine the payments into one array before responding to merchants. The report shows whether merchants can keep using the API as before.

If a report conflicts with the test log, Herringbone can [inspect the trace for that turn](https://developers.openai.com/api/training/agents-api/7-debug-a-session-with-traces.md) to see what information the agent used.



**Ask your coding agent:**

```text
Check the user’s access to the requested test run, then look up its Agents API session and turn IDs. Check the turn’s status and read all pages of items in order to find the assistant’s final reply. Find the artifact with the same turn ID and expected report path. Download it by artifact ID and display the report alongside the reply.

Read this lesson for context: https://developers.openai.com/api/training/agents-api/5-inspect-session-results-and-artifacts.md
```
