Cleanup all the files attached to a thread

Hi,

I am writing a Jupiter notebook to test the capabilities of Assistant API. I create an assistant, a thread, some messages, run them.
At the end, I want to cleanup all the entities I created including assistant, thread and the files. If the files are at the assistant level, there is no issue. I can cleanup everything (including the files) with the following code:

assistant_files = client.beta.assistants.files.list(assistant_id=assistant.id)
for file in assistant_files:
    client.files.delete(file_id=file.id)
client.beta.assistants.delete(assistant_id=assistant.id)
client.beta.threads.delete(thread_id=thread.id)

But, if the file is attached to an individual message or it is generated by the assistant response, I could not find a way to list them all, and delete.

How can I do that?

Here is the notebook if you are interested.

Your files would be attached to your organization (I believe) and can be listed with a simple GET:

[GET]: https://api.openai.com/v1/files

https://platform.openai.com/docs/api-reference/files

Otherwise they’d have to be retrieved from the messages:

[GET]: https://api.openai.com/v1/threads/{thread_id}/messages/{message_id}/files

https://platform.openai.com/docs/api-reference/messages/listMessageFiles

Thank you @RonaldGRuckus , it works.

Here is the full cleanup code for future reference:

assistant_files = client.beta.assistants.files.list(assistant_id=assistant.id)
for file in assistant_files:
    client.files.delete(file_id=file.id)

messages = client.beta.threads.messages.list(
  thread_id=thread.id
)

for message in messages: 
  message_files = client.beta.threads.messages.files.list(
    thread_id=thread.id,
    message_id=message.id
  )
  for file in message_files:
    client.files.delete(file_id=file.id)

client.beta.assistants.delete(assistant_id=assistant.id)
client.beta.threads.delete(thread_id=thread.id)
2 Likes