from langchain import HuggingFaceHub from langchain.chains import LLMChain from langchain.prompts import ChatPromptTemplate from dotenv import load_dotenv import streamlit as st import os # Load the Hugging Face API credentials from the environment load_dotenv() # Setup the LLM (Language Model) llm = HuggingFaceHub(repo_id="mistralai/Mistral-7B-Instruct-v0.2", model_kwargs={ "temperature": 0.7, "max_length": 512, }) # Create a refined template for the chatbot template = [ ("system", "You are an intelligent assistant. Provide clear, concise, and accurate explanations to users.Respond only to what the user is asking, and make sure your responses are complete."), ("human", "{message}"), ("ai", "Sure, here is the information you requested:") ] # Create the chat prompt template chat_prompt = ChatPromptTemplate.from_messages(template) # Create the language model chain chain = LLMChain(llm=llm, prompt=chat_prompt, output_key="chat") # Function to initialize session state if it doesn't exist def init_session(): if "flow_messages" not in st.session_state: st.session_state["flow_messages"] = [] # Create a function for getting the response from the chatbot def chatbot(message): response = chain.run({"message": message}) print(response) return response.split("AI:")[-1].strip() # Function to display messages in chat bubble style def display_messages(): st.markdown( """ """, unsafe_allow_html=True ) st.markdown('
', unsafe_allow_html=True) for sender, message in st.session_state["flow_messages"]: if sender == "human": st.markdown(f'
{message}
', unsafe_allow_html=True) elif sender == "ai": st.markdown(f'
{message}
', unsafe_allow_html=True) st.markdown('
', unsafe_allow_html=True) # Streamlit app initialization def main(): init_session() # Initialize session state st.title("Chat with AI Bot") st.write("Welcome to the AI Bot! Type your message below.") display_messages() user_input = st.text_input("You:", "", key="user_input", on_change=handle_input_change) def handle_input_change(): user_input = st.session_state["user_input"] if user_input: # Append the user message to the session state st.session_state["flow_messages"].append(("human", user_input)) # Get the bot response and append to session state bot_response = chatbot(st.session_state["flow_messages"]) st.session_state["flow_messages"].append(("ai", bot_response)) # Clear the input box st.session_state["user_input"] = "" # Run the Streamlit app if __name__ == "__main__": main()