题意:如何等待 OpenAI 助手的实际回复?(Python OpenAI API)
问题背景:
I am interacting with the openai assistant API (python). so far, it works well. but sometimes the api returns the message i sent to the assistant instead of the assistants reply.
我正在使用 OpenAI 助手 API(Python)进行交互,目前效果不错。但有时 API 返回的是我发送给助手的消息,而不是助手的回复。
from openai import OpenAI
from os import environ
OPEN_API_KEY = environ.get('OPEN_API_KEY')
assistant_id = "xxxxxxx"
client = OpenAI(api_key=OPEN_API_KEY)
assistant = client.beta.assistants.retrieve(assistant_id)
def ask_assistant(message_text):
print(f'received message: {message_text}')
thread = client.beta.threads.create()
message = client.beta.threads.messages.create(
thread_id=thread.id,
role="user",
content=message_text
)
run = client.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant_id
)
run_retrieve = client.beta.threads.runs.retrieve(
thread_id=thread.id,
run_id=run.id
)
as a hot fix, i implemented a sleep function that waits for 3 seconds before retrieving the reply. this works, but i don't expect it to be the best solution (or reliable at all). any ideas how to wait until the assistant REALLY replied?
作为一个临时解决方案,我实现了一个 sleep 函数,在获取回复前等待 3 秒。这种方法有效,但我不认为这是最好的解决方案(或者完全可靠)。有什么办法可以确保等到助手真正回复吗?
thank you very much. 非常感谢
Update:
This works: 下面的方法有效
from openai import OpenAI
from os import environ
OPEN_API_KEY = environ.get('xxxxx')
assistant_id = "xxxxx"
client = OpenAI(api_key=OPEN_API_KEY)
assistant = client.beta.assistants.retrieve(assistant_id)
def get_answer(run, thread):
while not run.status == "completed":
print("Waiting for answer...")
run = client.beta.threads.runs.retrieve(
thread_id=thread.id,
run_id=run.id
)
messages = client.beta.threads.messages.list(thread.id)
answer = messages.data[0].content[0].text.value
try:
answer = messages.data[0].content[0].text.value
except Exception as e:
print(e)
answer = ''
return answer
def ask_assistant(message_text):
print(f'sending to assistant: {message_text}')
thread = client.beta.threads.create()
message = client.beta.threads.messages.create(
thread_id=thread.id,
role="user",
content=message_text
)
run = client.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant_id
)
answer = get_answer(run, thread)
print(f'assistant response: {answer}')
return answer
if __name__ == "__main__":
ask_assistant('Hello')
问题解决:
This should work: 下面的方式应该有效:
run = openai.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant.id
)
print(run)
while run.status !="completed":
run = openai.beta.threads.runs.retrieve(
thread_id=thread.id,
run_id=run.id
)
print(run.status)
messages = openai.beta.threads.messages.list(
thread_id=thread.id
)
print(messages.data[0].content[0].text.value)