from openai import OpenAI
import os
import time
global client
global messages
os.environ["OPENAI_API_KEY"] = "{key}"
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
assistant = client.beta.assistants.retrieve("{assistant id}")
print("Assistant Located")
thread = client.beta.threads.create()
print("Thread Created")
message = client.beta.threads.messages.create(
thread_id=thread.id,
role="user",
content="I need to solve the equation `3x + 11 = 14`. Can you help me?"
)
print("Thread Ready")
run = client.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant.id
)
print("Assistant Loaded")
print("Run Started - Please Wait")
while True:
time.sleep(10)
run_status = client.beta.threads.runs.retrieve(
thread_id=thread.id,
run_id=run.id
)
if run_status.status == "completed":
print("Run is Completed")
messages = client.beta.threads.messages.list(
thread_id=thread.id
)
print(messages)
break
else:
print("Run is in progress - Please Wait")
continue
When I run the line, “print(messages)” it outputs the full unformatted output of the thread. Is there any way I can have it print just the messages with the Assistant role? I’ve tried, (used google lol) but I could not figure out how to output it. Does anyone have any ideas how?
I have a similar script, and get the assistant’s message by using:
messages.data[1].content[0].text.value
I hope this helps!
Struggling with the same thing. The first thing I learned is that each of these objects is a Pydantic object. Knowing that I was able to create the following code (with a little help from ChatGPT).
messages = client.beta.threads.messages.list(
thread_id=thread.id
)
for thread_message in messages.data:
# Iterate over the 'content' attribute of the ThreadMessage, which is a list
for content_item in thread_message.content:
# Assuming content_item is a MessageContentText object with a 'text' attribute
# and that 'text' has a 'value' attribute, print it
print(content_item.text.value)