Subhanzxz/Prodigy-Task4-Chatbot
0
1import gradio as gr2import os3from langchain_community.document_loaders import WikipediaLoader4from langchain_text_splitters import RecursiveCharacterTextSplitter5from langchain_community.embeddings import HuggingFaceEmbeddings6from langchain_community.vectorstores import Chroma7from langchain_google_genai import ChatGoogleGenerativeAI8from langchain.chains import create_retrieval_chain9from langchain.chains.combine_documents import create_stuff_documents_chain10from langchain_core.prompts import ChatPromptTemplate11 12# Global variable to hold our Vector Database13vector_store = None14 15def load_wikipedia(topic):16 global vector_store17 if not topic.strip():18 return "⚠️ Please enter a topic."19 20 try:21 # Fetch data from Wikipedia22 loader = WikipediaLoader(query=topic, load_max_docs=1)23 docs = loader.load()24 if not docs:25 return "❌ Could not find a Wikipedia page for that topic."26 27 # Chunk the text28 text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)29 chunks = text_splitter.split_documents(docs)30 31 # Create Embeddings and Vector Store32 embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")33 vector_store = Chroma.from_documents(chunks, embeddings)34 35 return f"✅ Success! Loaded Knowledge Base for: **{topic}**. You can now start chatting below!"36 except Exception as e:37 return f"❌ Error loading Wikipedia: {str(e)}"38 39def chat_function(message, history):40 global vector_store41 42 # Check if a document is loaded43 if vector_store is None:44 return "⚠️ Please load a Wikipedia topic at the top of the page first!"45 46 try:47 # Connect to Gemini48 llm = ChatGoogleGenerativeAI(model="gemini-1.5-flash", temperature=0.3)49 50 # Setup RAG Prompt51 system_prompt = (52 "You are a helpful assistant. Use the following pieces of retrieved context to answer "53 "the question. If you don't know the answer based on the context, say that you don't know.\n\n"54 "{context}"55 )56 prompt = ChatPromptTemplate.from_messages([57 ("system", system_prompt),58 ("human", "{input}"),59 ])60 61 # Create the RAG Chain62 retriever = vector_store.as_retriever(search_kwargs={"k": 3})63 question_answer_chain = create_stuff_documents_chain(llm, prompt)64 rag_chain = create_retrieval_chain(retriever, question_answer_chain)65 66 # Get Answer67 response = rag_chain.invoke({"input": message})68 return response["answer"]69 except Exception as e:70 return f"❌ Error generating response: {str(e)}"71 72# Build the Gradio Interface73with gr.Blocks(theme=gr.themes.Soft()) as demo:74 gr.Markdown("# 🧠 Context-Aware Wikipedia Chatbot")75 gr.Markdown("Type a topic below to scrape Wikipedia, build a vector database, and chat with the document using Gemini!")76 77 with gr.Row():78 topic_input = gr.Textbox(label="1. Enter Wikipedia Topic", placeholder="e.g., Quantum Mechanics, The Eiffel Tower...", scale=4)79 load_btn = gr.Button("Load Knowledge Base", variant="primary", scale=1)80 81 status_output = gr.Markdown("⏳ Waiting for topic...")82 83 load_btn.click(fn=load_wikipedia, inputs=topic_input, outputs=status_output)84 85 gr.Markdown("---")86 gr.Markdown("### 2. Chat with the Document")87 88 # Gradio's built in Chat Interface handles memory and history automatically89 gr.ChatInterface(fn=chat_function)90 91# Launch the app92if __name__ == "__main__":93 demo.launch()