Automation of Massive Thread Deletion in OpenAI v1 Assistant API Beta.

Israel Gomez
5 min readMay 1, 2024

In the dynamic world of software development, efficiency and automation are key. When working with the OpenAI v1 Assistant API Beta, specifically with the management of threads created by AI assistants, it can become tedious and impractical to delete each thread individually when they accumulate in large quantities.

This tutorial provides a solution for massively deleting these threads, facilitating management and optimizing time.

Step 1: Retrieve the List of Threads

  • Open your browser’s developer tools (F12) and select the “Network” tab.
  • Reload the page (CTRL + R or F5) to load all network requests.
  • Search for and select the API call containing threads?limit=30.
  • Right-click on this request and select “Copy as cURL (cmd)”.

cURL example (cmd):

curl "https://api.openai.com/v1/threads?limit=30" ^
-H "accept: */*" ^
-H "accept-language: es,es-419;q=0.9,en;q=0.8" ^
-H "authorization: Bearer sess-XXXXXXXXXXXXXXXXXXXXXXXXXXXX" ^
-H "dnt: 1" ^
-H "openai-beta: assistants=v1" ^
-H "openai-organization: org-xxxxxxxxxxxxxxxxxxxx" ^
-H "origin: https://platform.openai.com" ^
-H "priority: u=1, i" ^
-H "referer: https://platform.openai.com/" ^
-H "sec-ch-ua: \"Chromium\";v=\"124\", \"Google Chrome\";v=\"124\", \"Not-A.Brand\";v=\"99\"" ^
-H "sec-ch-ua-mobile: ?0" ^
-H "sec-ch-ua-platform: \"Windows\"" ^
-H "sec-fetch-dest: empty" ^
-H "sec-fetch-mode: cors" ^
-H "sec-fetch-site: same-site" ^
-H "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"

Step 2: Use Postman to Query the Threads

  • Open Postman and create a new GET request.
  • Paste the copied URL (e.g., https://api.openai.com/v1/threads?limit=30) into Postman and configure the authorization header with the token obtained in the previous step.
  • Send the request to get the list of threads. Be sure to adjust the limit to 100 if necessary.

Step 3: Prepare for Thread Deletion with Python

  • Go to the OpenAI API documentation and find the reference for “Delete thread”.
  • Get your API Key from the “API Keys” section in OpenAI and create a new key if necessary.
  • Use the sample code provided in the OpenAI documentation to set up your Python deletion script. Be sure to replace thread_abc123 with the ID of the threads you want to delete.

Example cURL and JSON API Reference response for deleting threads:

curl https://api.openai.com/v1/threads/thread_abc123 \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "OpenAI-Beta: assistants=v2" \
-X DELETE

Response:
{
"id": "thread_abc123",
"object": "thread.deleted",
"deleted": true
}

Python Script for Massive Deletion

To automate the querying and deletion of threads using OpenAI’s APIs in Python 3.11, I will provide a script that uses the requests library. The script will be divided into two main functions: one to fetch the threads and another to delete them. It will also include a main block to execute these functions and handle authorization tokens properly.

import requests

def fetch_threads(session_token):
"""Esta función consulta la lista de threads activos y maneja las respuestas HTTP."""
url = "https://api.openai.com/v1/threads?limit=100"
headers = {
'Authorization': f'Bearer {session_token}',
'Content-Type': 'application/json'
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status() # Esto lanzará una excepción para respuestas 4xx/5xx
return response.json() # Devuelve el JSON con la lista de threads
except requests.RequestException as e:
return {'error': str(e), 'status_code': response.status_code}

def delete_thread(thread_id, api_key):
url = f"https://api.openai.com/v1/threads/{thread_id}"
headers = {
"Content-Type": "text/plain; charset=utf-8",
"OpenAI-Beta": "assistants=v1",
"Authorization": f"Bearer {api_key}",
}
response = requests.delete(url, headers=headers)
if response.status_code == 200:
return response.json()
else:
return {
"error": "Failed to delete",
"status_code": response.status_code,
"response": response.text # Añadir texto de respuesta para más detalles
}

def main():
session_token = 'sess-VTyy3TzgRKzfVUI2A2v7wvFwL2tFaUnbrA4qMRI9'
api_key = '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'

# Obtiene la lista de threads
threads_response = fetch_threads(session_token)
if 'error' not in threads_response:
print("Threads obtenidos exitosamente:")
for thread in threads_response.get('data', []):
print(thread['id']) # Asumiendo que cada thread tiene un 'id'

# Eliminar cada thread
delete_response = delete_thread(thread['id'], api_key)
if 'error' not in delete_response:
print(f"Thread {thread['id']} eliminado exitosamente.")
else:
print(f"Error al eliminar thread {thread['id']}: {delete_response['error']}")
else:
print(f"Error al obtener threads: {threads_response['error']}")

if __name__ == "__main__":
main()

Code Execution in VS Code.

Explanation of the Code:

fetch_threads: This function makes a GET request to fetch threads. It uses exception handling to address request errors and HTTP status codes. delete_thread: Similarly, this function makes a DELETE request to remove a specific thread, handling exceptions appropriately. main: This block runs the functions, handles authorization tokens, and displays the results of the query and deletion operations.

Be sure to replace ‘your_session_token_here’ and ‘your_api_key_here’ with your real credentials to authenticate correctly with OpenAI’s APIs. This script handles HTTP response codes and provides an appropriate control flow for the desired operations.

Python Code Generated by ChatGPT 4

Disclaimer: This tutorial and the provided code are solely for educational and research purposes, presented as a proof of concept to illustrate an alternative method of thread management in OpenAI’s API. This approach aims to simplify the deletion of multiple threads, facilitating the management of large volumes of data and improving development efficiency.

It’s important to note that, while this method may provide a practical solution, its implementation and use should be carried out with caution and responsibility. This tutorial and associated codes are provided “as is,” with no warranties of any kind regarding their functionality, suitability for a particular purpose, or specific results.

The author of this tutorial is not responsible for any inconvenience, interruption, or damage that may arise from the incorrect or improper use of the information and codes presented here. Users are responsible for ensuring that their applications of the procedures and codes in this tutorial comply with applicable policies and regulations, including the terms of use of the OpenAI API.

This document does not imply any affiliation with OpenAI nor is it endorsed by that organization. The implementation of any practices described in this tutorial is at the user’s discretion and should be managed with full knowledge and understanding of the potential implications and risks.

--

--