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?
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)
Hi all, and thanks as I too struggled with this. I did need to change the line by @mrhendersonteach to be: messages.data[0].content[0].text.value
but is seems to sometimes be missing information.
For example, the assistant may ask me if I want an example of what I asked about. I reply yes. Then the new message will start with something like “Above is an example of ‘foo’”, but there is no example. ??
I’m also trying the nested for loops of @dlaytonj2 hoping to solve this. but I noticed that each new printing of the message is cumulative, i.e., including everything in the current thread in addition to any new question and the resulting answer.
Sorry to piggyback but I am struggling to access the content part of the message so I can manipulate it.
messages = client.beta.threads.messages.list(thread_id=thread_id)
article = next((m.content for m in messages.data if m.role == “assistant”), None)
I want the text inside which is like a value key.
I just want the “I can’t get this” part.
MessageContentText(text=Text(annotations=, value=“I can’t get this”…