import streamlit as st import time from langchain.schema import HumanMessage, SystemMessage, AIMessage from langchain.chat_models import ChatOpenAI import openai from IPython.display import Audio import base64 def get_chatmodel_response(question): # Retry logic max_retries = 3 retries = 0 while retries < max_retries: try: st.session_state['flowmessages'].append(HumanMessage(content=question)) answer = chat(st.session_state['flowmessages']) st.session_state['flowmessages'].append(AIMessage(content=answer.content)) return answer.content except Exception as e: print(f"Error: {e}") if "Rate limit" in str(e): print(f"Rate limit exceeded. Waiting and retrying...") time.sleep(5) # Adjust the waiting time as needed retries += 1 else: print("Unhandled exception. Please try again later.") break print("Exceeded the maximum number of retries. Please try again later.") return None # Streamlit app setup st.set_page_config(page_title="Sisi Chatbot") st.snow() st.balloons() st.header("Hey, I'm Sisi!") from dotenv import load_dotenv load_dotenv() import os # ChatOpenAI class chat = ChatOpenAI(temperature=0.5) if 'flowmessages' not in st.session_state: st.session_state['flowmessages'] = [ SystemMessage(content="You are an AI Friend, your name is Sisi and you was developed by Sailesh on December 5 2023. First get the name of the user and become his friend. then, You have to be a nice friend and an AI assistant to the users and help them with what information they need. It should be short and sharp") ] # Streamlit UI with st.form(key='my_form',clear_on_submit=True): st.markdown( """ """, unsafe_allow_html=True ) input_question = st.text_input("Type here.", key="input") submit = st.form_submit_button("Submit") # If the "Submit" button is clicked if submit: # Display loading message while processing with st.spinner("Analyzing..."): st.header(":blue[You]", divider=True) st.caption(input_question) st.header("Sisi", divider=True) response = get_chatmodel_response(input_question) if response is not None: st.write(response) # Text-to-speech audio_response = openai.audio.speech.create( model="tts-1", voice="nova", input=response, response_format="mp3", speed=1.0 ) # Embed audio in the webpage without saving it st.header(':blue[Listen] :loud_sound:') st.audio(audio_response.content,format="audio/wav",start_time=0) else: st.subheader("Error: Unable to get response. Please try again later.")