Downloading a file generated by code_interpereter tool

I am experimenting with the code interpreter tool and hoping to download a plot that it generated. The API consistently gives me a file ID, but I have yet to be able to view the PNG. I have tried two things:

  1. Download the file in the same script that generates it (shown in code below), which avoids any issues with the file quickly expiring
  2. Conversely, to check if there is some delay in creating the file, I have tried using the file ID in a separate script a few seconds/minutes later. This had the same error (code not pictured)

Here is my code (it’s very brittle for now since I know exactly what response structure I’m expecting)

from openai import OpenAI

client = OpenAI()

instructions = """
You are a personal math tutor. When asked a math question, 
write and run code using the python tool to answer the question.
"""

resp = client.responses.create(
    model="gpt-4.1",
    tools=[
        {
            "type": "code_interpreter",
            "container": {"type": "auto"}
        }
    ],
    instructions=instructions,
    input="Plot the function sin(x) from -10 to 10 with a little bit of noise",
)

print(resp.output)
file_id = resp.output[1].content[0].annotations[0].file_id

image_data = client.files.content(file_id)
image_data_bytes = image_data.read()

with open("./my-image.png", "wb") as file:
    file.write(image_data_bytes)

but I always get

API/lib/python3.13/site-packages/openai/_base_client.py", line 1037, in request
    raise self._make_status_error_from_response(err.response) from None
openai.NotFoundError: Error code: 404 - {'error': {'message': 'No such File object: cfile_686fe1cfa0488191af3d0d5912a3a95a', 'type': 'invalid_request_error', 'param': 'id', 'code': None}}

Any suggestions would be much appreciated—thank you!

Code interpreter generates its output into their own ephemeral containers.
You use a different endpoint to download them, as they are not store in the files endpoint used for permanent storage.
You must access it within 20 minutes, or they disappear.

Have a look at these:

1 Like

Thank you! That explains why the file id starts with “cfile” and not “file”. Really appreciate it!

Most importantly - you must goad and prompt the AI into making links correctly while it writes to the user that would be returned as annotations, otherwise you get no output files in the sandbox file to present with your own link.

The container rapidly expires, so you’ll likely want to provide better service to your user, by not just serving the downloaded files from your own web host, but immediately downloading and persisting files.