Spaces:
Runtime error
Runtime error
app file is updated
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081import streamlit as stfrom langchain.document_loaders import PyPDFLoader, DirectoryLoaderfrom langchain import PromptTemplatefrom langchain.embeddings import HuggingFaceEmbeddingsfrom langchain.vectorstores import FAISSfrom langchain.llms import CTransformersfrom langchain.chains import RetrievalQAimport chainlit as clDB_FAISS_PATH = 'vectorstore/db_faiss'custom_prompt_template = """Use the following pieces of information to answer the user's question.If you don't know the answer, just say that you don't know, don't try to make up an answer.Context: {context}Question: {question}Only return the helpful answer below and nothing else.Helpful answer:"""def set_custom_prompt():"""Prompt template for QA retrieval for each vectorstore"""prompt = PromptTemplate(template=custom_prompt_template,input_variables=['context', 'question'])return prompt# Retrieval QA Chaindef retrieval_qa_chain(llm, prompt, db):qa_chain = RetrievalQA.from_chain_type(llm=llm,chain_type='stuff',retriever=db.as_retriever(search_kwargs={'k': 2}),return_source_documents=True,chain_type_kwargs={'prompt': prompt})return qa_chain# Loading the modeldef load_llm():# Load the locally downloaded model herellm = CTransformers(model="llama-2-7b-chat.ggmlv3.q8_0.bin",model_type="llama",max_new_tokens=512,temperature=0.5)return llm# QA Model Functiondef qa_bot():embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2",model_kwargs={'device': 'cpu'})db = FAISS.load_local(DB_FAISS_PATH, embeddings)llm = load_llm()qa_prompt = set_custom_prompt()qa = retrieval_qa_chain(llm, qa_prompt, db)return qadef main():st.title("Medical Assistance AI ChatBot")qa_result = qa_bot()user_input = st.text_input("Enter your question:")if st.button("Ask"):response = qa_result({'query': user_input})answer = response["result"]sources = response["source_documents"]st.write("Answer:", answer)if sources:st.write("Sources:", sources)else:st.write("No sources found")if __name__ == "__main__":main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081import streamlit as stfrom streamlit_chat import messageimport tempfilefrom langchain.document_loaders.csv_loader import CSVLoaderfrom langchain.embeddings import HuggingFaceEmbeddingsfrom langchain.vectorstores import FAISSfrom langchain.llms import CTransformersfrom langchain.chains import ConversationalRetrievalChainDB_FAISS_PATH = 'vectorstore/db_faiss'#Loading the modeldef load_llm():# Load the locally downloaded model herellm = CTransformers(model = "llama-2-7b-chat.ggmlv3.q8_0.bin",model_type="llama",max_new_tokens = 512,temperature = 0.5)return llmst.title("Chat with CSV using Llama2 🦙🦜")st.markdown("<h3 style='text-align: center; color: white;'> A Very Good Bot For CSV</h3>", unsafe_allow_html=True)uploaded_file = st.sidebar.file_uploader("Upload your Data", type="csv")if uploaded_file :#use tempfile because CSVLoader only accepts a file_pathwith tempfile.NamedTemporaryFile(delete=False) as tmp_file:tmp_file.write(uploaded_file.getvalue())tmp_file_path = tmp_file.nameloader = CSVLoader(file_path=tmp_file_path, encoding="utf-8", csv_args={'delimiter': ','})data = loader.load()#st.json(data)embeddings = HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L6-v2',model_kwargs={'device': 'cpu'})db = FAISS.from_documents(data, embeddings)db.save_local(DB_FAISS_PATH)llm = load_llm()chain = ConversationalRetrievalChain.from_llm(llm=llm, retriever=db.as_retriever())def conversational_chat(query):result = chain({"question": query, "chat_history": st.session_state['history']})st.session_state['history'].append((query, result["answer"]))return result["answer"]if 'history' not in st.session_state:st.session_state['history'] = []if 'generated' not in st.session_state:st.session_state['generated'] = ["Hello ! Ask me anything about " + uploaded_file.name + " 🤗"]if 'past' not in st.session_state:st.session_state['past'] = ["Hey ! 👋"]#container for the chat historyresponse_container = st.container()#container for the user's text inputcontainer = st.container()with container:with st.form(key='my_form', clear_on_submit=True):user_input = st.text_input("Query:", placeholder="Talk to your csv data here (:", key='input')submit_button = st.form_submit_button(label='Send')if submit_button and user_input:output = conversational_chat(user_input)st.session_state['past'].append(user_input)st.session_state['generated'].append(output)if st.session_state['generated']:with response_container:for i in range(len(st.session_state['generated'])):message(st.session_state["past"][i], is_user=True, key=str(i) + '_user', avatar_style="big-smile")message(st.session_state["generated"][i], key=str(i), avatar_style="thumbs")
app.py+61-61