I’m having trouble retrieving messages I saved into a thread. What am I doing wrong?
import time
from openai import OpenAI
# Initialize the client with your API key
client = OpenAI(api_key='sk-proj-XXX')
# Define the initial message content
initial_message_content = "Hello, I'd like to start a new conversation about AI."
try:
# Step 1: Create a new thread
new_thread = client.beta.threads.create(
messages=[{"role": "user", "content": initial_message_content}]
)
# Output the new thread ID
print(f"New Thread ID: {new_thread.id}")
print(f"Created At: {new_thread.created_at}")
# Step 2: Add a new message to the created thread
thread_message = client.beta.threads.messages.create(
new_thread.id,
role="user",
content="How does AI work? Explain it in simple terms."
)
# Output the details of the added message
print(f"Message ID: {thread_message.id}")
print(f"Created At: {thread_message.created_at}")
print(f"Role: {thread_message.role}")
print(f"Content: {thread_message.content}")
# Add a delay before retrieving the thread to ensure data is processed
time.sleep(2)
# Retrieve the thread again to check for messages
retrieved_thread = client.beta.threads.retrieve(new_thread.id)
print(f"Thread ID: {retrieved_thread.id}")
print(f"Created At: {retrieved_thread.created_at}")
print(f"Metadata: {retrieved_thread.metadata}")
print(f"Object: {retrieved_thread.object}")
print(f"Tool Resources: {retrieved_thread.tool_resources}")
# Attempt to access messages if available
if hasattr(retrieved_thread, 'messages') and retrieved_thread.messages:
for message in retrieved_thread.messages:
print(f"Role: {message['role']}, Content: {message['content']}")
else:
print("No messages found in this thread.")
except Exception as e:
print(f"An error occurred: {str(e)}")
This returns:
New Thread ID: thread_Irhdu5YrzkAoz5AokviMHF2s
Created At: 1722504758
Message ID: msg_fAVkDrh4wC4IIXJOckPMWo8v
Created At: 1722504758
Role: user
Content: [TextContentBlock(text=Text(annotations=, value=‘How does AI work? Explain it in simple terms.’), type=‘text’)]
Thread ID: thread_Irhdu5YrzkAoz5AokviMHF2s
Created At: 1722504758
Metadata: {}
Object: thread
Tool Resources: ToolResources(code_interpreter=ToolResourcesCodeInterpreter(file_ids=), file_search=None)
No messages found in this thread.