How to save image file returned from the code interpreter tool?

I am trying the new Assistants API, while it runs successfully, I am unable to save the image file returned by the API.

I get the image file id from the messages, then retrieve the contents like this:
content = client.files.retrieve_content(file_id)

with open(‘testoutput.png’, ‘wb’) as f:

However, when I save this in a binary file, the resulting file is not a valid image file.

The content is f type str and looks like this when printed on console:


I am having the same issue. When retrieving the file contents (files.retrieve_content) it seems to be cast to a string. I, and others believe that this is the issue.


Okay, so @ andreas over on Discord was able to chime in and help us figure this out : Discord

Here is the solution:

# handle image file
api_response = client.files.with_raw_response.retrieve_content(r.image_file.file_id)

if api_response.status_code == 200:
  content = api_response.content
  with open('image.png', 'wb') as f:
  print('File downloaded successfully.')

Just in case, I was struggling with the way to achieve this in nodeJs there is no with_raw_response implementation for the OpenAI client.

const main = async () => {
  const writeStream = createWriteStream(__dirname + "/myImage.png");

  const response = await fetch(
      headers: {
          "Bearer {Your OpenAI key}",
  ).then((res) => res.blob());

  response.arrayBuffer().then((buffer) => {

1 Like

This appears to be fixed in the latest python SDK version. You can now download PNG files like so:

image_file_id = "file-abc-123"
image_file = openai.files.content(image_file_id)
with open("plot.png", "wb") as f:
1 Like

I used firebase or supabase, upload the image, get the downloadable url and then delete the image once passed to code interpreter