OpenAIError
openai.OpenAIError: Thread not found or expired
Stack trace
openai.OpenAIError: Thread not found or expired
at openai.client.chat.completions.create (/path/to/your/app.py:45:15)
at main (/path/to/your/app.py:50:5) Why it happens
OpenAI conversation threads have a limited lifespan or can be deleted, causing the API to return a 'Thread not found or expired' error when you try to continue a conversation with an invalid or expired thread ID. This usually happens if the thread ID is stale or incorrectly stored.
Detection
Log and verify the thread ID before making API calls; catch OpenAIError exceptions and check for 404 status or specific error messages indicating expired or missing threads.
Causes & fixes
Using a thread ID that has expired due to inactivity or time limits on the OpenAI server.
Start a new conversation thread instead of reusing the expired thread ID, or refresh the thread ID by creating a new chat completion.
Incorrectly storing or retrieving the thread ID, leading to invalid or malformed IDs being sent to the API.
Implement robust storage and retrieval logic for thread IDs, including validation and expiration checks before reuse.
Attempting to access a thread that was manually deleted or invalidated on the OpenAI platform.
Handle this error by catching the exception and prompting the application to create a new thread rather than retrying the old one.
Code: broken vs fixed
from openai import OpenAI
import os
client = OpenAI(api_key=os.environ['OPENAI_API_KEY'])
thread_id = 'expired-thread-id'
response = client.chat.completions.create(
model='gpt-4o-mini',
thread_id=thread_id, # This causes the error
messages=[{'role': 'user', 'content': 'Hello!'}]
)
print(response.choices[0].message.content) from openai import OpenAI, OpenAIError
import os
client = OpenAI(api_key=os.environ['OPENAI_API_KEY'])
thread_id = 'expired-thread-id'
try:
response = client.chat.completions.create(
model='gpt-4o-mini',
thread_id=thread_id, # May cause thread not found error
messages=[{'role': 'user', 'content': 'Hello!'}]
)
except OpenAIError as e:
if 'Thread not found' in str(e):
# Create a new thread by omitting thread_id
response = client.chat.completions.create(
model='gpt-4o-mini',
messages=[{'role': 'user', 'content': 'Hello!'}]
)
else:
raise
print(response.choices[0].message.content) # Now works with new thread Workaround
Wrap the chat completion call in a try/except block catching OpenAIError; on thread not found errors, retry the request without the thread_id to start a new conversation.
Prevention
Implement thread ID lifecycle management by tracking expiration and refreshing threads proactively; use new thread IDs for long-running or infrequently used conversations.