Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657import gradio as grfrom langchain.vectorstores import Chromafrom langchain.embeddings import HuggingFaceEmbeddingsfrom langchain.llms import HuggingFaceHubfrom langchain.chains import ConversationalRetrievalChainfrom langchain.document_loaders import SimpleDocumentLoaderfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain.memory import ConversationBufferMemory
# Initialize the Hugging Face embedding modelembedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
# Initialize the LLaMA 2 model from Hugging Face Hubllm = HuggingFaceHub(repo_id="meta-llama/Llama-2-7b-hf", model_kwargs={"temperature": 0.7, "max_length": 512})
# Initialize ChromaDB for storing and retrieving document embeddingsvectorstore = Chroma(embedding_function=embedding_model, persist_directory="chroma_db")
# Create a conversational chain with retrieval capabilitiesmemory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)qa_chain = ConversationalRetrievalChain.from_llm(llm, retriever=vectorstore.as_retriever(), memory=memory)
def upload_docs(docs): # Load and process the uploaded documents loader = SimpleDocumentLoader(docs) documents = loader.load() # Split documents into manageable chunks text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200) texts = text_splitter.split_documents(documents) # Add documents to the vector store and persist them vectorstore.add_documents(texts) vectorstore.persist() return "Documents uploaded and processed successfully!"
def chat(query): # Process the query with the conversational chain and return the result response = qa_chain({"query": query}) return response["result"]
# Gradio Interfacewith gr.Blocks() as demo: with gr.Row(): with gr.Column(): doc_upload = gr.File(label="Upload your documents", file_types=[".txt", ".pdf", ".docx"], multiple=True) upload_button = gr.Button("Upload") upload_button.click(upload_docs, inputs=doc_upload, outputs=gr.Textbox())
with gr.Column(): chat_input = gr.Textbox(label="Ask a question:") chat_output = gr.Textbox(label="Answer:") chat_button = gr.Button("Send") chat_button.click(chat, inputs=chat_input, outputs=chat_output)
demo.launch()app.pyAdded+57