import gradio as gr import os from bs4 import BeautifulSoup import requests from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain_community.embeddings import HuggingFaceEmbeddings from langchain_community.vectorstores import FAISS from langchain.chains import ConversationalRetrievalChain from langchain.memory import ConversationBufferMemory from langchain_community.llms import HuggingFaceEndpoint from langchain.schema import Document # Initialize environment api_token =os.getenv("HF_TOKEN") list_llm = ["meta-llama/Meta-Llama-3-8B-Instruct", "mistralai/Mistral-7B-Instruct-v0.2"] list_llm_simple = [os.path.basename(llm) for llm in list_llm] def scrape_website(url): """Scrape text content from a website""" try: response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') for script in soup(["script", "style"]): script.decompose() text = soup.get_text() lines = (line.strip() for line in text.splitlines()) chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) text = ' '.join(chunk for chunk in chunks if chunk) return text except Exception as e: return f"Error scraping website: {str(e)}" def process_text(text): """Split text into chunks""" text_splitter = RecursiveCharacterTextSplitter( chunk_size=1024, chunk_overlap=64 ) chunks = text_splitter.split_text(text) return chunks def create_db(splits): """Create vector database""" embeddings = HuggingFaceEmbeddings() documents = [Document(page_content=text, metadata={}) for text in splits] vectordb = FAISS.from_documents(documents, embeddings) return vectordb def initialize_database(url, progress=gr.Progress()): """Initialize database from URL""" # Scrape website content text_content = scrape_website(url) if text_content.startswith("Error"): return None, text_content # Create text chunks doc_splits = process_text(text_content) # Create vector database vector_db = create_db(doc_splits) return vector_db, "Database created successfully!" def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db): """Initialize LLM chain""" llm = HuggingFaceEndpoint( repo_id=llm_model, huggingfacehub_api_token=api_token, temperature=temperature, max_new_tokens=max_tokens, top_k=top_k, ) memory = ConversationBufferMemory( memory_key="chat_history", output_key='answer', return_messages=True ) qa_chain = ConversationalRetrievalChain.from_llm( llm, retriever=vector_db.as_retriever(), chain_type="stuff", memory=memory, return_source_documents=True, verbose=False, ) return qa_chain def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()): """Initialize LLM with selected options""" llm_name = list_llm[llm_option] qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db) return qa_chain, "QA chain initialized. Chatbot is ready!" def format_chat_history(message, chat_history): """Format chat history for the model""" formatted_chat_history = [] for user_message, bot_message in chat_history: formatted_chat_history.append(f"User: {user_message}") formatted_chat_history.append(f"Assistant: {bot_message}") return formatted_chat_history def conversation(qa_chain, message, history): """Handle conversation with the model""" formatted_chat_history = format_chat_history(message, history) response = qa_chain.invoke({"question": message, "chat_history": formatted_chat_history}) response_answer = response["answer"] if response_answer.find("Helpful Answer:") != -1: response_answer = response_answer.split("Helpful Answer:")[-1] response_sources = response["source_documents"][:3] sources = [] for i in range(3): if i < len(response_sources): sources.append((response_sources[i].page_content.strip(), 1)) else: sources.append(("", 1)) new_history = history + [(message, response_answer)] return (qa_chain, gr.update(value=""), new_history, sources[0][0], sources[0][1], sources[1][0], sources[1][1], sources[2][0], sources[2][1]) def demo(): with gr.Blocks(theme=gr.themes.Default(primary_hue="red", secondary_hue="pink", neutral_hue="sky")) as demo: vector_db = gr.State() qa_chain = gr.State() gr.HTML("

RAG Website Chatbot

") gr.Markdown("""Query any website content! This AI agent performs retrieval augmented generation (RAG) on website content.""") with gr.Row(): with gr.Column(scale=86): gr.Markdown("Step 1 - Enter Website URL and Initialize RAG pipeline") with gr.Row(): url_input = gr.Textbox(label="Website URL", placeholder="Enter website URL here...") with gr.Row(): db_btn = gr.Button("Create vector database") with gr.Row(): db_progress = gr.Textbox(value="Not initialized", show_label=False) gr.Markdown("Select Large Language Model (LLM) and input parameters") with gr.Row(): llm_btn = gr.Radio(list_llm_simple, label="Available LLMs", value=list_llm_simple[0], type="index") with gr.Row(): with gr.Accordion("LLM input parameters", open=False): slider_temperature = gr.Slider(0.01, 1.0, 0.5, step=0.1, label="Temperature") slider_maxtokens = gr.Slider(128, 9192, 4096, step=128, label="Max New Tokens") slider_topk = gr.Slider(1, 10, 3, step=1, label="top-k") with gr.Row(): qachain_btn = gr.Button("Initialize Question Answering Chatbot") with gr.Row(): llm_progress = gr.Textbox(value="Not initialized", show_label=False) with gr.Column(scale=200): gr.Markdown("Step 2 - Chat about the Website Content") chatbot = gr.Chatbot(height=505) with gr.Accordion("Relevant context from the source", open=False): with gr.Row(): doc_source1 = gr.Textbox(label="Reference 1", lines=2, container=True, scale=20) source1_page = gr.Number(label="Section", scale=1) with gr.Row(): doc_source2 = gr.Textbox(label="Reference 2", lines=2, container=True, scale=20) source2_page = gr.Number(label="Section", scale=1) with gr.Row(): doc_source3 = gr.Textbox(label="Reference 3", lines=2, container=True, scale=20) source3_page = gr.Number(label="Section", scale=1) with gr.Row(): msg = gr.Textbox(placeholder="Ask a question", container=True) with gr.Row(): submit_btn = gr.Button("Submit") clear_btn = gr.ClearButton([msg, chatbot], value="Clear") # Event handlers db_btn.click(initialize_database, inputs=[url_input], outputs=[vector_db, db_progress]) qachain_btn.click(initialize_LLM, inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db], outputs=[qa_chain, llm_progress]) msg.submit(conversation, inputs=[qa_chain, msg, chatbot], outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page]) submit_btn.click(conversation, inputs=[qa_chain, msg, chatbot], outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page]) clear_btn.click(lambda: [None, "", 0, "", 0, "", 0], inputs=None, outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page]) demo.queue().launch(debug=True) if __name__ == "__main__": demo()