Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345672 unmodified lines101112131415161718192021222324252611 unmodified lines3839404142434445464748497 unmodified lines5758596061626364653 unmodified lines697071727374757677787980818214 unmodified lines979899100from langchain import PromptTemplatefrom langchain.embeddings import HuggingFaceEmbeddingsfrom langchain_community.vectorstores import FAISSfrom langchain_community.llms import CTransformersfrom langchain.chains import RetrievalQAimport gradio as grfrom huggingface_hub import hf_hub_download2 unmodified linesdef load_llm():"""Load the LLaMA model for the language model."""model_name = 'TheBloke/Llama-2-7B-Chat-GGML'model_path = hf_hub_download(repo_id=model_name, filename='llama-2-7b-chat.ggmlv3.q8_0.bin', cache_dir='./models')llm = CTransformers(model=model_path,model_type="llama",max_new_tokens=512,temperature=0.5)return llmdef set_custom_prompt():"""11 unmodified linesprompt = PromptTemplate(template=custom_prompt_template, input_variables=['context', 'question'])return promptdef retrieval_QA_chain(llm, prompt, db):"""Create a RetrievalQA chain with the specified LLM, prompt, and vector store."""qachain = RetrievalQA.from_chain_type(llm=llm,chain_type="stuff",retriever=db.as_retriever(search_kwargs={'k': 2}),return_source_documents=True,7 unmodified lines"""embeddings = HuggingFaceEmbeddings(model_name='sentence-transformers/all-miniLM-L6-V2', model_kwargs={'device': 'cpu'})db = FAISS.load_local(DB_FAISS_PATH, embeddings, allow_dangerous_deserialization=True)llm = load_llm()qa_prompt = set_custom_prompt()qa = retrieval_QA_chain(llm, qa_prompt, db)return qabot = qa_bot()3 unmodified linesGenerate a response from the chatbot based on the user input and conversation history."""try:response = bot({'query': message})answer = response["result"]sources = response["source_documents"]if sources:answer += f"\nSources: {sources}"else:answer += "\nNo sources found"history.append((message, answer))except Exception as e:history.append((message, f"An error occurred: {str(e)}"))return history, history14 unmodified lines)if __name__ == "__main__":demo.launch()123456782 unmodified lines11121314151617181920212223242526272811 unmodified lines404142434445464748495051525354555657587 unmodified lines6667686970717273747576773 unmodified lines818283848586878889909192939495969714 unmodified lines112113114115from transformers import GPT2LMHeadModel, GPT2Tokenizerfrom langchain import PromptTemplatefrom langchain.embeddings import HuggingFaceEmbeddingsfrom langchain_community.vectorstores import FAISSfrom langchain_community.llms import CTransformers # You might need to change this if GPT-2 isn't directly supportedfrom langchain.chains import RetrievalQAimport gradio as grfrom huggingface_hub import hf_hub_download2 unmodified linesdef load_llm():"""Load the GPT-2 model for the language model."""try:print("Downloading or loading the GPT-2 model and tokenizer...")model_name = 'gpt2'model = GPT2LMHeadModel.from_pretrained(model_name)tokenizer = GPT2Tokenizer.from_pretrained(model_name)print("Model and tokenizer successfully loaded!")return model, tokenizerexcept Exception as e:print(f"An error occurred while loading the model: {e}")return None, Nonedef set_custom_prompt():"""11 unmodified linesprompt = PromptTemplate(template=custom_prompt_template, input_variables=['context', 'question'])return promptdef retrieval_QA_chain(llm, tokenizer, prompt, db):"""Create a RetrievalQA chain with the specified LLM, prompt, and vector store."""def generate_answer(query):# Tokenize the input queryinputs = tokenizer.encode(query, return_tensors='pt')# Generate responseoutputs = llm.generate(inputs, max_length=512, temperature=0.5)return tokenizer.decode(outputs[0], skip_special_tokens=True)qachain = RetrievalQA.from_chain_type(llm=generate_answer,chain_type="stuff",retriever=db.as_retriever(search_kwargs={'k': 2}),return_source_documents=True,7 unmodified lines"""embeddings = HuggingFaceEmbeddings(model_name='sentence-transformers/all-miniLM-L6-V2', model_kwargs={'device': 'cpu'})db = FAISS.load_local(DB_FAISS_PATH, embeddings, allow_dangerous_deserialization=True)model, tokenizer = load_llm()qa_prompt = set_custom_prompt()if model and tokenizer:qa = retrieval_QA_chain(model, tokenizer, qa_prompt, db)else:qa = Nonereturn qabot = qa_bot()3 unmodified linesGenerate a response from the chatbot based on the user input and conversation history."""try:if bot:response = bot({'query': message})answer = response["result"]sources = response.get("source_documents", [])if sources:answer += f"\nSources: {sources}"else:answer += "\nNo sources found"history.append((message, answer))else:history.append((message, "Model is not loaded properly."))except Exception as e:history.append((message, f"An error occurred: {str(e)}"))return history, history14 unmodified lines)if __name__ == "__main__":demo.launch()
app.py+38-23