How to delete a thread in OpenAI Assistants API
Quick answer
To delete a thread in the OpenAI Assistants API, use the
client.assistants.threads.delete() method with the assistant ID and thread ID. This requires the official OpenAI Python SDK v1 and your API key set in os.environ["OPENAI_API_KEY"].PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the official OpenAI Python SDK version 1 or higher and set your API key as an environment variable.
- Run
pip install openai>=1.0to install the SDK. - Export your API key in your shell:
export OPENAI_API_KEY='your_api_key_here'(Linux/macOS) or set it in your environment variables on Windows.
pip install openai>=1.0 Step by step
Use the OpenAI client to delete a thread by specifying the assistant_id and thread_id. The method client.assistants.threads.delete() sends the delete request.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
assistant_id = "your-assistant-id"
thread_id = "your-thread-id"
response = client.assistants.threads.delete(
assistant=assistant_id,
thread=thread_id
)
print("Thread deleted successfully.")
print(response) output
Thread deleted successfully.
{'id': 'thread-id', 'object': 'thread', 'deleted': True} Common variations
You can delete threads asynchronously by using an async client or handle errors with try-except blocks. Also, ensure you use the correct assistant_id and thread_id from your assistant management dashboard or API responses.
import asyncio
import os
from openai import OpenAI
async def delete_thread_async():
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
assistant_id = "your-assistant-id"
thread_id = "your-thread-id"
response = await client.assistants.threads.delete(
assistant=assistant_id,
thread=thread_id
)
print("Thread deleted asynchronously.")
print(response)
asyncio.run(delete_thread_async()) output
Thread deleted asynchronously.
{'id': 'thread-id', 'object': 'thread', 'deleted': True} Troubleshooting
- If you get a 404 error, verify the
assistant_idandthread_idare correct and exist. - If you receive an authentication error, check your API key environment variable.
- For permission errors, ensure your API key has rights to manage assistants and threads.
Key Takeaways
- Use
client.assistants.threads.delete()withassistantandthreadIDs to delete a thread. - Always set your OpenAI API key in
os.environ["OPENAI_API_KEY"]before running code. - Handle errors like 404 or authentication failures by verifying IDs and API key permissions.