Hi all. I’m following this tutorial by @ joyasree78 and have tried to make a few changes of my own. When I run the code and ask the first question, I’m getting this error:
raise self._make_status_error_from_response(err.response) from None openai.BadRequestError: Error code: 400 - {'error': {'message': "Can't add messages to thread_Xhtc7rjp5KYTKxWdfnDuLD6U while a run run_rF3R9B6ZqrJmGUhjYNoNb93E is active.", 'type': 'invalid_request_error', 'param': None, 'code': None}}
Thanks
Here’s my code:
import os
from openai import OpenAI, AsyncOpenAI
from dotenv import load_dotenv
import asyncio
# env variables
load_dotenv()
my_key = os.getenv('OPENAI_API_KEY')
# OpenAI API
client = AsyncOpenAI(api_key=my_key)
async def deploy_assistant():
# Create the assistant
assistant = await client.beta.assistants.create(
name="Coding Buddy",
instructions="You are a programming support chatbot. Use your knowledge of programming languages to best respond to user queries.",
model="gpt-4-1106-preview",
tools=[{"type": "code_interpreter"}],
#file_ids=[file.id]
)
return assistant
async def run_assistant(assistant_id,thread):
run = await client.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant_id
)
runInfo = await client.beta.threads.runs.retrieve(
thread_id=thread.id,
run_id=run.id
)
return run, runInfo
async def get_answer(run, runInfo, thread, user_question):
print("Looking for an answer to your question...")
# add a message to a thread
message = await client.beta.threads.messages.create(
thread_id=thread.id,
role="user",
content= user_question
)
while runInfo.status != "completed":
runInfo = await client.beta.threads.runs.retrieve(
thread_id=thread.id,
run_id=run.id
)
print("All done...")
# Get the messages from the thread
messages = await client.beta.threads.messages.list(message.thread_id)
message_content = await messages.data[0].content[0].text.value
return message_content
if __name__ == "__main__":
async def main():
# assistant = await deploy_assistant()
# print(assistant)
thread = await client.beta.threads.create()
print("Thread created is: ", thread.id)
while True:
question = input("How may I help you today? \n")
if "exit" in question.lower():
break
run,runInfo = await run_assistant("asst_3GtOWcJBMrBs4EiUjP9ZXY9P",thread)
message_content = await get_answer(run, runInfo, thread, question)
print("FYI, your thread is: ", thread.id)
print(message_content)
print("Thanks and happy to serve you")
asyncio.run(main())