import os import gradio as gr from langchain_community.document_loaders import PyPDFLoader from langchain_community.vectorstores import Chroma from langchain_text_splitters import RecursiveCharacterTextSplitter from langchain_ollama import OllamaEmbeddings, OllamaLLM # ------------------------- # 1. LOAD MULTIPLE PDFs # ------------------------- def load_documents(folder_path="documents"): documents = [] for file in os.listdir(folder_path): if file.endswith(".pdf"): loader = PyPDFLoader(os.path.join(folder_path, file)) docs = loader.load() for doc in docs: doc.metadata["source"] = file documents.extend(docs) return documents # ------------------------- # 2. BUILD VECTOR DATABASE # ------------------------- documents = load_documents("documents") text_splitter = RecursiveCharacterTextSplitter( chunk_size=1000, chunk_overlap=200 ) docs = text_splitter.split_documents(documents) embeddings = OllamaEmbeddings(model="mistral") db = Chroma.from_documents(docs, embeddings) llm = OllamaLLM(model="mistral") # ------------------------- # 3. CHAT MEMORY # ------------------------- chat_history = [] # ------------------------- # 4. QUESTION FUNCTION # ------------------------- def ask_pdf(question): global chat_history retrieved_docs = db.similarity_search(question, k=3) context = "\n\n".join( [doc.page_content for doc in retrieved_docs] ) sources = list(set([doc.metadata["source"] for doc in retrieved_docs])) # Guardrail: if no context found if not context.strip(): return "I don't have enough information from the documents to answer this." prompt = f""" You are a helpful assistant. Answer ONLY from the provided context. If the answer is not in the context, say: "I don't have enough information from the documents." Chat history: {chat_history} Context: {context} Question: {question} Answer: """ answer = llm.invoke(prompt) chat_history.append({"question": question, "answer": answer}) citation_text = "\n\nSources: " + ", ".join(sources) return answer + citation_text # ------------------------- # 5. GRADIO UI # ------------------------- interface = gr.Interface( fn=ask_pdf, inputs="text", outputs="text", title="Advanced Ask My PDF Bot", description="Chat with multiple PDFs. Shows sources. Has memory. Guardrails enabled." ) interface.launch()