Update app.py
Browse files11 unmodified lines12131415161718192021223 unmodified lines2627282930313236 unmodified lines697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201215 unmodified lines12712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823911 unmodified linesfrom langchain_community.embeddings import HuggingFaceEmbeddingsfrom llama_parse import LlamaParsefrom langchain_core.documents import Document# Environment variables and configurationshuggingface_token = os.environ.get("HUGGINGFACE_TOKEN")llama_cloud_api_key = os.environ.get("LLAMA_CLOUD_API_KEY")# Initialize LlamaParsellama_parser = LlamaParse(api_key=llama_cloud_api_key,3 unmodified lineslanguage="en",)def load_document(file: NamedTemporaryFile, parser: str = "pypdf") -> List[Document]:"""Loads and splits the document into pages."""if parser == "pypdf":loader = PyPDFLoader(file.name)36 unmodified linesreturn f"Vector store updated successfully. Processed {total_chunks} chunks from {len(files)} files using {parser}."def generate_chunked_response(prompt, max_tokens=1000, max_chunks=5, temperature=0.7, repetition_penalty=1.1):API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3"headers = {"Authorization": f"Bearer {huggingface_token}"}payload = {"inputs": prompt,"parameters": {"max_new_tokens": max_tokens,"temperature": temperature,"top_p": 0.4,"top_k": 40,"repetition_penalty": repetition_penalty,"stop": ["</s>", "[/INST]"]}}full_response = ""for _ in range(max_chunks):response = requests.post(API_URL, headers=headers, json=payload)if response.status_code == 200:result = response.json()if isinstance(result, list) and len(result) > 0:chunk = result[0].get('generated_text', '')# Remove any part of the chunk that's already in full_responsenew_content = chunk[len(full_response):].strip()if not new_content:break # No new content, so we're donefull_response += new_contentif chunk.endswith((".", "!", "?", "</s>", "[/INST]")):break# Update the prompt for the next iterationpayload["inputs"] = full_responseelse:breakelse:break# Clean up the responseclean_response = re.sub(r'<s>\[INST\].*?\[/INST\]\s*', '', full_response, flags=re.DOTALL)clean_response = clean_response.replace("Using the following context:", "").strip()clean_response = clean_response.replace("Using the following context from the PDF documents:", "").strip()return clean_responsedef duckduckgo_search(query):with DDGS() as ddgs:5 unmodified lines...,description="List of sources to cite. Should be an URL of the source.")def get_response_from_pdf(query, temperature=0.7, repetition_penalty=1.1):embed = get_embeddings()if os.path.exists("faiss_database"):database = FAISS.load_local("faiss_database", embed, allow_dangerous_deserialization=True)else:return "No documents available. Please upload PDF documents to answer questions."retriever = database.as_retriever()relevant_docs = retriever.get_relevant_documents(query)context_str = "\n".join([doc.page_content for doc in relevant_docs])prompt = f"""<s>[INST] Using the following context from the PDF documents:{context_str}Write a detailed and complete response that answers the following user question: '{query}'Do not include a list of sources in your response. [/INST]"""generated_text = generate_chunked_response(prompt, temperature=temperature, repetition_penalty=repetition_penalty)# Clean the responseclean_text = re.sub(r'<s>\[INST\].*?\[/INST\]\s*', '', generated_text, flags=re.DOTALL)clean_text = clean_text.replace("Using the following context from the PDF documents:", "").strip()return clean_textdef get_response_with_search(query, temperature=0.7, repetition_penalty=1.1):search_results = duckduckgo_search(query)context = "\n".join(f"{result['title']}\n{result['body']}\nSource: {result['href']}\n"for result in search_results if 'body' in result)prompt = f"""<s>[INST] Using the following context:{context}Write a detailed and complete research document that fulfills the following user request: '{query}'After writing the document, please provide a list of sources used in your response. [/INST]"""generated_text = generate_chunked_response(prompt, temperature=temperature, repetition_penalty=repetition_penalty)# Clean the responseclean_text = re.sub(r'<s>\[INST\].*?\[/INST\]\s*', '', generated_text, flags=re.DOTALL)clean_text = clean_text.replace("Using the following context:", "").strip()# Split the content and sourcesparts = clean_text.split("Sources:", 1)main_content = parts[0].strip()sources = parts[1].strip() if len(parts) > 1 else ""return main_content, sourcesdef chatbot_interface(message, history, use_web_search, temperature, repetition_penalty):if use_web_search:main_content, sources = get_response_with_search(message, temperature, repetition_penalty)formatted_response = f"{main_content}\n\nSources:\n{sources}"else:response = get_response_from_pdf(message, temperature, repetition_penalty)formatted_response = responsehistory.append((message, formatted_response))return history# Gradio interfacewith gr.Blocks() as demo:gr.Markdown("# AI-powered Web Search and PDF Chat Assistant")with gr.Row():file_input = gr.Files(label="Upload your PDF documents", file_types=[".pdf"])parser_dropdown = gr.Dropdown(choices=["pypdf", "llamaparse"], label="Select PDF Parser", value="pypdf")update_button = gr.Button("Upload Document")update_output = gr.Textbox(label="Update Status")update_button.click(update_vectors, inputs=[file_input, parser_dropdown], outputs=update_output)chatbot = gr.Chatbot(label="Conversation")msg = gr.Textbox(label="Ask a question")use_web_search = gr.Checkbox(label="Use Web Search", value=False)with gr.Row():temperature_slider = gr.Slider(minimum=0.1, maximum=1.0, value=0.7, step=0.1, label="Temperature")repetition_penalty_slider = gr.Slider(minimum=1.0, maximum=2.0, value=1.1, step=0.1, label="Repetition Penalty")submit = gr.Button("Submit")gr.Examples(examples=[["What are the latest developments in AI?"],["Tell me about recent updates on GitHub"],["What are the best hotels in Galapagos, Ecuador?"],["Summarize recent advancements in Python programming"],],inputs=msg,)submit.click(chatbot_interface,inputs=[msg, chatbot, use_web_search, temperature_slider, repetition_penalty_slider],outputs=[chatbot])msg.submit(chatbot_interface,inputs=[msg, chatbot, use_web_search, temperature_slider, repetition_penalty_slider],outputs=[chatbot])gr.Markdown("""## How to use1. Upload PDF documents using the file input at the top.2. Select the PDF parser (pypdf or llamaparse) and click "Upload Document" to update the vector store.3. Ask questions in the textbox.4. Toggle "Use Web Search" to switch between PDF chat and web search.5. Adjust Temperature and Repetition Penalty sliders to fine-tune the response generation.6. Click "Submit" or press Enter to get a response.""")11 unmodified lines121314151617181920212223242526272829303 unmodified lines3435363738394036 unmodified lines77787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301315 unmodified lines13713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630711 unmodified linesfrom langchain_community.embeddings import HuggingFaceEmbeddingsfrom llama_parse import LlamaParsefrom langchain_core.documents import Documentfrom huggingface_hub import InferenceClientimport inspect# Environment variables and configurationshuggingface_token = os.environ.get("HUGGINGFACE_TOKEN")llama_cloud_api_key = os.environ.get("LLAMA_CLOUD_API_KEY")MODELS = ["mistralai/Mistral-7B-Instruct-v0.3","mistralai/Mixtral-8x7B-Instruct-v0.1","microsoft/Phi-3-mini-4k-instruct"]# Initialize LlamaParsellama_parser = LlamaParse(api_key=llama_cloud_api_key,3 unmodified lineslanguage="en",)def load_document(file: NamedTemporaryFile, parser: str = "llamaparse") -> List[Document]:"""Loads and splits the document into pages."""if parser == "pypdf":loader = PyPDFLoader(file.name)36 unmodified linesreturn f"Vector store updated successfully. Processed {total_chunks} chunks from {len(files)} files using {parser}."def generate_chunked_response(prompt, model, max_tokens=1000, num_calls=3, temperature=0.2, should_stop=False):print(f"Starting generate_chunked_response with {num_calls} calls")client = InferenceClient(model, token=huggingface_token)full_response = ""messages = [{"role": "user", "content": prompt}]for i in range(num_calls):print(f"Starting API call {i+1}")if should_stop:print("Stop clicked, breaking loop")breaktry:for message in client.chat_completion(messages=messages,max_tokens=max_tokens,temperature=temperature,stream=True,):if should_stop:print("Stop clicked during streaming, breaking")breakif message.choices and message.choices[0].delta and message.choices[0].delta.content:chunk = message.choices[0].delta.contentfull_response += chunkprint(f"API call {i+1} completed")except Exception as e:print(f"Error in generating response: {str(e)}")# Clean up the responseclean_response = re.sub(r'<s>\[INST\].*?\[/INST\]\s*', '', full_response, flags=re.DOTALL)clean_response = clean_response.replace("Using the following context:", "").strip()clean_response = clean_response.replace("Using the following context from the PDF documents:", "").strip()# Remove duplicate paragraphs and sentencesparagraphs = clean_response.split('\n\n')unique_paragraphs = []for paragraph in paragraphs:if paragraph not in unique_paragraphs:sentences = paragraph.split('. ')unique_sentences = []for sentence in sentences:if sentence not in unique_sentences:unique_sentences.append(sentence)unique_paragraphs.append('. '.join(unique_sentences))final_response = '\n\n'.join(unique_paragraphs)print(f"Final clean response: {final_response[:100]}...")return final_responsedef duckduckgo_search(query):with DDGS() as ddgs:5 unmodified lines...,description="List of sources to cite. Should be an URL of the source.")def chatbot_interface(message, history, use_web_search, model, temperature, num_calls):if not message.strip():return "", historyhistory = history + [(message, "")]try:if use_web_search:for main_content, sources in get_response_with_search(message, model, num_calls=num_calls, temperature=temperature):history[-1] = (message, f"{main_content}\n\n{sources}")yield historyelse:for partial_response in get_response_from_pdf(message, model, num_calls=num_calls, temperature=temperature):history[-1] = (message, partial_response)yield historyexcept gr.CancelledError:yield historydef retry_last_response(history, use_web_search, model, temperature, num_calls):if not history:return historylast_user_msg = history[-1][0]history = history[:-1] # Remove the last responsereturn chatbot_interface(last_user_msg, history, use_web_search, model, temperature, num_calls)def respond(message, history, model, temperature, num_calls, use_web_search):if use_web_search:for main_content, sources in get_response_with_search(message, model, num_calls=num_calls, temperature=temperature):yield f"{main_content}\n\n{sources}"else:for partial_response in get_response_from_pdf(message, model, num_calls=num_calls, temperature=temperature):yield partial_responsedef get_response_with_search(query, model, num_calls=3, temperature=0.2):search_results = duckduckgo_search(query)context = "\n".join(f"{result['title']}\n{result['body']}\nSource: {result['href']}\n"for result in search_results if 'body' in result)prompt = f"""Using the following context:{context}Write a detailed and complete research document that fulfills the following user request: '{query}'After writing the document, please provide a list of sources used in your response."""client = InferenceClient(model, token=huggingface_token)main_content = ""for i in range(num_calls):for message in client.chat_completion(messages=[{"role": "user", "content": prompt}],max_tokens=1000,temperature=temperature,stream=True,):if message.choices and message.choices[0].delta and message.choices[0].delta.content:chunk = message.choices[0].delta.contentmain_content += chunkyield main_content, "" # Yield partial main content without sourcesdef get_response_from_pdf(query, model, num_calls=3, temperature=0.2):embed = get_embeddings()if os.path.exists("faiss_database"):database = FAISS.load_local("faiss_database", embed, allow_dangerous_deserialization=True)else:yield "No documents available. Please upload PDF documents to answer questions."returnretriever = database.as_retriever()relevant_docs = retriever.get_relevant_documents(query)context_str = "\n".join([doc.page_content for doc in relevant_docs])prompt = f"""Using the following context from the PDF documents:{context_str}Write a detailed and complete response that answers the following user question: '{query}'"""client = InferenceClient(model, token=huggingface_token)response = ""for i in range(num_calls):for message in client.chat_completion(messages=[{"role": "user", "content": prompt}],max_tokens=1000,temperature=temperature,stream=True,):if message.choices and message.choices[0].delta and message.choices[0].delta.content:chunk = message.choices[0].delta.contentresponse += chunkyield response # Yield partial responsedef vote(data: gr.LikeData):if data.liked:print(f"You upvoted this response: {data.value}")else:print(f"You downvoted this response: {data.value}")css = """/* Add your custom CSS here */"""# Define the checkbox outside the demo blockuse_web_search = gr.Checkbox(label="Use Web Search", value=False)demo = gr.ChatInterface(respond,additional_inputs=[gr.Dropdown(choices=MODELS, label="Select Model", value=MODELS[0]),gr.Slider(minimum=0.1, maximum=1.0, value=0.2, step=0.1, label="Temperature"),gr.Slider(minimum=1, maximum=5, value=1, step=1, label="Number of API Calls"),use_web_search # Add this line to include the checkbox],title="AI-powered Web Search and PDF Chat Assistant",description="Chat with your PDFs or use web search to answer questions.",theme=gr.themes.Soft(primary_hue="orange",secondary_hue="amber",neutral_hue="gray",font=[gr.themes.GoogleFont("Exo"), "ui-sans-serif", "system-ui", "sans-serif"]).set(body_background_fill_dark="#0c0505",block_background_fill_dark="#0c0505",block_border_width="1px",block_title_background_fill_dark="#1b0f0f",input_background_fill_dark="#140b0b",button_secondary_background_fill_dark="#140b0b",border_color_accent_dark="#1b0f0f",border_color_primary_dark="#1b0f0f",background_fill_secondary_dark="#0c0505",color_accent_soft_dark="transparent",code_background_fill_dark="#140b0b"),css=css,examples=[["Tell me about the contents of the uploaded PDFs."],["What are the main topics discussed in the documents?"],["Can you summarize the key points from the PDFs?"]],cache_examples=False,analytics_enabled=False,)# Add file upload functionalitywith demo:gr.Markdown("## Upload PDF Documents")with gr.Row():file_input = gr.Files(label="Upload your PDF documents", file_types=[".pdf"])parser_dropdown = gr.Dropdown(choices=["pypdf", "llamaparse"], label="Select PDF Parser", value="llamaparse")update_button = gr.Button("Upload Document")update_output = gr.Textbox(label="Update Status")update_button.click(update_vectors, inputs=[file_input, parser_dropdown], outputs=update_output)gr.Markdown("""## How to use1. Upload PDF documents using the file input at the top.2. Select the PDF parser (pypdf or llamaparse) and click "Upload Document" to update the vector store.3. Ask questions in the chat interface.4. Toggle "Use Web Search" to switch between PDF chat and web search.5. Adjust Temperature and Number of API Calls to fine-tune the response generation.6. Use the provided examples or ask your own questions.""")
app.py+183-115