Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345678921 unmodified lines3132333435361 unmodified line3839404142434445464714 unmodified lines6263646566676869707118 unmodified lines909192939495969716 unmodified lines1141151161171181191204 unmodified lines125126127128129130131132133134135136137138139140141142143144145146147148149150import streamlit as stfrom langchain_openai import ChatOpenAI, OpenAIEmbeddingsimport osimport dotenvfrom langchain_text_splitters import RecursiveCharacterTextSplitterfrom langchain_chroma import Chromafrom langchain.chains.combine_documents import create_stuff_documents_chainfrom langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholderfrom langchain_core.messages import HumanMessage, AIMessage21 unmodified linesdotenv.load_dotenv()chat = ChatOpenAI(model="gpt-3.5-turbo-1106", temperature=0.2)loader1 = PyPDFLoader("Tbank resources.pdf")loader2 = PyPDFLoader("International Banking Services.pdf")data1 = loader1.load()1 unmodified linedata = data1 + data2text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)all_splits = text_splitter.split_documents(data)embeddings = OpenAIEmbeddings(model="text-embedding-ada-002")vectorstore = Chroma.from_documents(documents=all_splits, embedding=embeddings)retriever = vectorstore.as_retriever(search_kwargs={"k": 6, "score_threshold": 0.5})SYSTEM_TEMPLATE = """You are Tbank's AI assistant, a chatbot whose knowledge comes exclusively from Tbank's website content and provided PDF documents. Follow these guidelines:14 unmodified lines12. Regularly refer to the provided PDFs for accurate, up-to-date information about Tbank's products and services.13. Check for the basic Grammar and Spellings and understand if the spellings or grammar is slightly incorrect.14. Understand the user query with different angle, analyze properly, check through the possible answers and then give the answer.15. Be forgiving of minor spelling mistakes and grammatical errors in user queries. Try to understand the intent behind the question.16. Maintain context from previous messages in the conversation. If a user asks about a person or topic mentioned earlier, refer back to that information.17. If a user asks about a person using only a name or title, try to identify who they're referring to based on previous context or your knowledge base.18. When answering questions about specific people, provide their full name and title if available.Your primary goal is to assist users with information directly related to Tbank, using only the website content and provided PDF documents. Avoid speculation and stick strictly to the provided information.18 unmodified linesdocument_chain = create_stuff_documents_chain(chat, question_answering_prompt)return retriever, document_chain# Load components16 unmodified lineswith st.chat_message(message["role"]):st.markdown(message["content"])# React to user inputif prompt := st.chat_input("What would you like to know about Tbank?"):# Display user message in chat message container4 unmodified lineswith st.chat_message("assistant"):message_placeholder = st.empty()# # Fuzzy match important terms# matched_term = fuzzy_match(prompt.lower(), important_terms)# if matched_term:# prompt = f"{prompt} (Matched term: {matched_term})"# Retrieve relevant documentsdocs = retriever.get_relevant_documents(prompt)# Include previous messages for contextprevious_messages = st.session_state.messages[-5:] # Last 5 messages# Generate responseresponse = document_chain.invoke({"context": docs,"chat_history": st.session_state.memory.load_memory_variables({})["chat_history"],"messages": [HumanMessage(content=msg["content"]) for msg in previous_messages] + [HumanMessage(content=prompt)],})full_response = responsemessage_placeholder.markdown(full_response)123456789101121 unmodified lines333435363738391 unmodified line41424344454647484914 unmodified lines64656667686918 unmodified lines88899091929316 unmodified lines1101111121131141154 unmodified lines120121122123124125126127128129130131132133134135136137138139140import streamlit as stfrom langchain_openai import ChatOpenAIimport osimport dotenvfrom langchain_community.document_loaders import WebBaseLoaderfrom langchain_text_splitters import RecursiveCharacterTextSplitterfrom langchain_chroma import Chromafrom langchain_openai import OpenAIEmbeddingsfrom langchain.chains.combine_documents import create_stuff_documents_chainfrom langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholderfrom langchain_core.messages import HumanMessage, AIMessage21 unmodified linesdotenv.load_dotenv()chat = ChatOpenAI(model="gpt-3.5-turbo-1106", temperature=0.2)#loader1 = WebBaseLoader("https://www.tbankltd.com/")loader1 = PyPDFLoader("Tbank resources.pdf")loader2 = PyPDFLoader("International Banking Services.pdf")data1 = loader1.load()1 unmodified linedata = data1 + data2text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)all_splits = text_splitter.split_documents(data)embeddings = OpenAIEmbeddings(model="text-embedding-ada-002")vectorstore = Chroma.from_documents(documents=all_splits, embedding=embeddings)retriever = vectorstore.as_retriever(k=4)SYSTEM_TEMPLATE = """You are Tbank's AI assistant, a chatbot whose knowledge comes exclusively from Tbank's website content and provided PDF documents. Follow these guidelines:14 unmodified lines12. Regularly refer to the provided PDFs for accurate, up-to-date information about Tbank's products and services.13. Check for the basic Grammar and Spellings and understand if the spellings or grammar is slightly incorrect.14. Understand the user query with different angle, analyze properly, check through the possible answers and then give the answer.Your primary goal is to assist users with information directly related to Tbank, using only the website content and provided PDF documents. Avoid speculation and stick strictly to the provided information.18 unmodified linesdocument_chain = create_stuff_documents_chain(chat, question_answering_prompt)return retriever, document_chain# Load components16 unmodified lineswith st.chat_message(message["role"]):st.markdown(message["content"])# React to user inputif prompt := st.chat_input("What would you like to know about Tbank?"):# Display user message in chat message container4 unmodified lineswith st.chat_message("assistant"):message_placeholder = st.empty()# Retrieve relevant documentsdocs = retriever.get_relevant_documents(prompt)# Generate responseresponse = document_chain.invoke({"context": docs,"chat_history": st.session_state.memory.load_memory_variables({})["chat_history"],"messages": [HumanMessage(content=prompt)],})# The response is already a string, so we can use it directlyfull_response = responsemessage_placeholder.markdown(full_response)
app.py+9-19