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("