I’m having an issue with the OpenAI Assistants API where the input() function is skipped after the first user input. My goal is to create an ongoing chat with the assistant where the user can repeatedly send messages and receive responses.
Here’s a snippet of my code:
import os
from dotenv import load_dotenv
from openai import OpenAI, AssistantEventHandler
from rich.console import Console
# Load environment variables from .env
load_dotenv()
api_key = os.getenv("OPENAI_API_KEY")
client = OpenAI(api_key=api_key)
console = Console()
assistant_id = "asst_xxxxxxxxxxxxxxxxxxxxxxxxx"
class MyEventHandler(AssistantEventHandler):
def on_text_delta(self, delta, snapshot):
console.print(delta.value, end="", style="black on white")
def on_error(self, error):
print(error)
my_thread = client.beta.threads.create()
while True:
user_input = input("nnUser:n")
if user_input.lower() == "quit":
console.print("nAssistant:nHave a nice day! :wave:nn", style="black on white")
break
client.beta.threads.messages.create(
thread_id=my_thread.id,
role="user",
content="Provide a response for the following query: " + user_input,
)
with client.beta.threads.runs.stream(
thread_id=my_thread.id,
assistant_id=assistant_id,
instructions="Respond to the user input based on the description provided.",
event_handler=MyEventHandler(),
) as stream:
console.print("nAssistant:", style="black on white")
stream.until_done()
The problem is, after the first user input, the program never stops for another user input, and it skips over the input(“nnUser:n”) line, running the code below it immediately.
Has anyone encountered this issue before or knows why this might be happening? Any suggestions for resolving it would be greatly appreciated!
Thanks in advance! :pray:
MegaMonster is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.