Cannot Delete Messages from Thread in Assistants API

Hello

I have the following code:

def trim_messages(thread_id, num_messages_to_keep=10):
    # Fetch list of message info objects
    try:
        messages = client.beta.threads.messages.list(thread_id=thread_id, order='desc').data
    except Exception as e:
        print(f"Error: could not fetch messages from thread: {e}")

    # No need for any bulk-delete functionality - normally will only delete 2 messages
    try:
        for message in messages[num_messages_to_keep:]:
            message_id = message.id
            deleted_message = client.beta.threads.messages.delete(
                message_id=message_id,
                thread_id=thread_id
            )
            print()
            print(deleted_message)
    except Exception as e:
        print(f"Error: could not delete messages: {e}")

print(len(client.beta.threads.messages.list(thread_id='<thread_id>', order='desc').data))
trim_messages('<thread_id>')
print(len(client.beta.threads.messages.list(thread_id=thread_id, order='desc').data))

I am trying to delete all messages before the last 10 messages that were sent in order to keep costs down for a chatbot. However, when I run the code, the outputs for the number of messages are the same, which seems to indicate that the messages are not actually being deleted. However, the returned object from the delete call says deleted=True and no errors are being thrown.

Why is this not working as I want it to? Is there anything I can change to make it work as I want it to? Will it maybe work if I set the number of messages to keep to a higher number?

It seemed to work when I did it on a thread with 12 messages, but it never worked when I did it on a thread with 20 messages