“I’m working on an app that uses the ChatGPT API and I want to display a custom spinner. The spinner shows up when the process starts, but the issue is that it keeps displaying even after the process has finished. How can I sync it with ChatGPT’s operations so that the spinner clears once the processing is done?
Here’s the relevant code snippet created by ChatGPT:”
def communicate(user_input, bot_response_placeholder, model, temperature, top_p):
spinner_placeholder=st.empty()
show_custom_spinner(spinner_placeholder)
try:
messages = st.session_state["messages"]
user_message = {"role": "user", "content": user_input}
messages.append(user_message)
complete_response = ""
# Get the response from ChatCompletion
response = client.chat.completions.create(
model=model,
messages=messages,
temperature=temperature,
max_tokens=2000,
top_p=top_p,
)
response_message = response.choices[0].message.content
if response_message is not None:
# Accumulate content and update the bot's response in real time
complete_response += response_message
formatted_response = complete_response.replace("\n", "<br>")
indented_response = "".join([f"<div style='margin-left: 20px; white-space: pre-wrap;'>{line}</div>" for line in complete_response.split('\n')])
bot_response_placeholder.markdown(indented_response, unsafe_allow_html=True)
# After all chunks are received, add the complete response to the chat history
if complete_response:
bot_message = {"role": "assistant", "content": complete_response}
messages.append(bot_message)
# Reset the messages after the chat
messages = [{"role": "system", "content": "You are the best AI assistant in the world."}]
return complete_response
spinner_placeholder.empty()
except Exception as e:
spinner_placeholder.empty()
raise e