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. The session ID identifies the conversation. The turn ID identifies one round of work in that conversation.
The Agents API saves messages and tool calls as items. If the agent writes a file under /workspace/outputs in an OpenAI-hosted environment, 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 reply and its files
If you have only the session ID, list its turns and use their timestamps to find the one you need. Retrieve the turn to check its status. If the status is failed, inspect the 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 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. Match both turn_id and path, then download the file by artifact ID. |
You can download artifacts after the environment expires. Save any files you need to keep before deleting the session.
Example: Show a customer the results of its pagination test
Herringbone uses a separate session for each customer. 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 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.
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 as needed. Herringbone downloads the copy from the matching 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}")Set OPENAI_API_KEY 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.
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_cursorvalue back ascursoruntil 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 to see what information the agent used.