| import streamlit as st |
| import os |
| import random, string |
|
|
| from langchain.chains import LLMChain |
| from langchain_core.prompts import ( |
| ChatPromptTemplate, |
| HumanMessagePromptTemplate, |
| MessagesPlaceholder, |
| ) |
| from langchain_core.messages import SystemMessage |
| from langchain.chains.conversation.memory import ConversationBufferWindowMemory |
| from langchain_groq import ChatGroq |
|
|
| if 'chat_list' not in st.session_state: |
| st.session_state.chat_list = [] |
|
|
|
|
| def arr(): |
| for c_list in st.session_state.chat_list: |
| with st.chat_message("user"): |
| st.write("Question : " + c_list["ques"]) |
| with st.chat_message("machine"): |
| st.write("Answer : " + c_list["ans"]) |
|
|
| def main(): |
|
|
| """ |
| This function is the main entry point of the application. It sets up the Groq client, the Streamlit interface, and handles the chat interaction. |
| """ |
|
|
| |
| groq_api_key = st.secrets["Groq_API_key"] |
| model = 'llama3-8b-8192' |
| |
| groq_chat = ChatGroq( |
| groq_api_key=groq_api_key, |
| model_name=model |
| ) |
|
|
| st.title('Langchain Chatbot With llama3-8b-8192 model') |
| |
| |
| st.markdown("Hello! I'm your friendly Groq chatbot, dev by GJ. I can help answer your questions, provide information, or just chat. I'm also super fast! Let's start our conversation!") |
|
|
| system_prompt = 'You are a friendly conversational chatbot' |
| conversational_memory_length = 5 |
|
|
| if 'memory' not in st.session_state: |
| st.session_state.memory = ConversationBufferWindowMemory(k=conversational_memory_length, memory_key="chat_history", return_messages=True) |
| |
|
|
|
|
| |
| user_question = st.chat_input("Ask a question:") |
| if user_question: |
| |
| prompt = ChatPromptTemplate.from_messages( |
| [ |
| SystemMessage( |
| content=system_prompt |
| ), |
|
|
| MessagesPlaceholder( |
| variable_name="chat_history" |
| ), |
|
|
| HumanMessagePromptTemplate.from_template( |
| "{human_input}" |
| ), |
| ] |
| ) |
|
|
| |
| conversation = LLMChain( |
| llm=groq_chat, |
| prompt=prompt, |
| verbose=False, |
| memory=st.session_state.memory, |
| ) |
| |
| response = conversation.predict(human_input=user_question) |
| |
| |
| result = {"ques":user_question, "ans":response} |
| st.session_state.chat_list.append(result) |
| arr() |
| |
|
|
| if __name__ == "__main__": |
| main() |