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:
f.write(content)
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:
3 Likes
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.
2 Likes
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:
f.write(content)
print('File downloaded successfully.')
opened 02:14AM - 07 Nov 23 UTC
When I try to download/retrieve a binary file (eg. PNG image) created by an assi… stant, it get automatically [cast to a string](https://github.com/openai/openai-python/blob/e0aafc6c1a45334ac889fe3e54957d309c3af93f/src/openai/resources/files.py#L229), so it can't be correctly parsed/displayed.
Eg:
``` py
ret_file = client.files.retrieve_content('file-XXX')
ret_file[:10]
# '�PNG\r\n\x1a\n\x00\x00'
```
There doesn't seem to be a clean way in the API to retrieve a file as raw bytes from what I can see.
This is important for code interpreter scenarios where the agent returns binary files that need to be rendered, like Images.
For others having this issue, you can just request the files directly using `requests` like:
``` py
import requests
from io import BytesIO
file_id = 'file-XXXX'
headers = {
'Authorization': f"Bearer {os.environ['OPENAI_API_KEY']}"
}
response = requests.get(f'https://api.openai.com/v1/files/{file_id}/content', headers=headers)
Image.open(BytesIO(response.content))
```
2 Likes
WiFo
November 10, 2023, 1:07am
4
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(
"https://api.openai.com/v1/files/{file-id}/content",
{
headers: {
Authorization:
"Bearer {Your OpenAI key}",
},
}
).then((res) => res.blob());
response.arrayBuffer().then((buffer) => {
writeStream.write(Buffer.from(buffer));
});
};
main();
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:
f.write(image_file.content)
1 Like
I used firebase or supabase, upload the image, get the downloadable url and then delete the image once passed to code interpreter