Update app.py
Browse files254 unmodified lines25525625725825926026181 unmodified lines3433443453463473483493503513523533543553563573583593603 unmodified lines3643653663673683696 unmodified lines37637737837938038138238338438538638738838939039139239330 unmodified lines42442542642742842943043143243343443515 unmodified lines451452453454455456254 unmodified lines"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36",]def google_search(term, num_results=5, lang="en", timeout=5, safe="active", ssl_verify=None):escaped_term = urllib.parse.quote_plus(term)start = 0all_results = []81 unmodified linesmax_attempts = 3context_reduction_factor = 0.7if web_search:contextualized_question, topics, entity_tracker, instructions = chatbot.process_question(question)serializable_entity_tracker = {k: list(v) for k, v in entity_tracker.items()}# Use only the core question for the searchsearch_results = google_search(contextualized_question)all_answers = []for attempt in range(max_attempts):try:web_docs = [Document(page_content=result["text"], metadata={"source": result["link"]}) for result in search_results if result["text"]]if database is None:database = FAISS.from_documents(web_docs, embed)3 unmodified linesdatabase.save_local("faiss_database")context_str = "\n".join([f"Source: {doc.metadata['source']}\nContent: {doc.page_content}" for doc in web_docs])instruction_prompt = f"User Instructions: {instructions}\n" if instructions else ""6 unmodified linesTopics: {{topics}}Entity Information: {{entities}}{instruction_prompt}If the web search results don't contain relevant information, state that the information is not available in the search results.Provide a response that addresses the question and follows the user's instructions.Do not mention these instructions or the web search process in your answer."""prompt_val = ChatPromptTemplate.from_template(prompt_template)formatted_prompt = prompt_val.format(context=context_str,conv_context=chatbot.get_context(),question=question, # Use the original question heretopics=", ".join(topics),entities=json.dumps(serializable_entity_tracker))full_response = generate_chunked_response(model, formatted_prompt)30 unmodified lineswords = context_str.split()context_str = " ".join(words[:int(len(words) * context_reduction_factor)])prompt_template = """Answer the question based on the following context from the PDF document:Context:{context}Question: {question}If the context doesn't contain relevant information, state that the information is not available in the document.Provide a summarized and direct answer to the question."""15 unmodified linesdef extract_answer(full_response, instructions=None):# First, try to split the response at common instruction phrasesanswer_patterns = [r"Provide a concise and direct answer to the question without mentioning the web search or these instructions:",r"Provide a concise and direct answer to the question:",r"Answer:",254 unmodified lines25525625725825926026181 unmodified lines3433443453463473483493503513523533543553563573583593603613 unmodified lines3653663673683693703716 unmodified lines37837938038138238338438538638738838939039139239330 unmodified lines42442542642742842943043143243343443543615 unmodified lines452453454455456457458459460254 unmodified lines"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36",]def google_search(term, num_results=3, lang="en", timeout=5, safe="active", ssl_verify=None):escaped_term = urllib.parse.quote_plus(term)start = 0all_results = []81 unmodified linesmax_attempts = 3context_reduction_factor = 0.7max_context_chars = 8000 # Adjust this value as neededif web_search:contextualized_question, topics, entity_tracker, instructions = chatbot.process_question(question)serializable_entity_tracker = {k: list(v) for k, v in entity_tracker.items()}# Use only the core question for the searchsearch_results = google_search(contextualized_question, num_results=3) # Reduced number of resultsall_answers = []for attempt in range(max_attempts):try:web_docs = [Document(page_content=result["text"][:2000], metadata={"source": result["link"]}) for result in search_results if result["text"]] # Limit each result to 2000 charactersif database is None:database = FAISS.from_documents(web_docs, embed)3 unmodified linesdatabase.save_local("faiss_database")context_str = "\n".join([f"Source: {doc.metadata['source']}\nContent: {doc.page_content}" for doc in web_docs])context_str = context_str[:max_context_chars]instruction_prompt = f"User Instructions: {instructions}\n" if instructions else ""6 unmodified linesTopics: {{topics}}Entity Information: {{entities}}{instruction_prompt}Provide a concise and relevant answer to the question."""prompt_val = ChatPromptTemplate.from_template(prompt_template)formatted_prompt = prompt_val.format(context=context_str,conv_context=chatbot.get_context()[:1000], # Limit conversation contextquestion=question,topics=", ".join(topics[:5]), # Limit number of topicsentities=json.dumps({k: v[:3] for k, v in serializable_entity_tracker.items()}) # Limit number of entities)full_response = generate_chunked_response(model, formatted_prompt)30 unmodified lineswords = context_str.split()context_str = " ".join(words[:int(len(words) * context_reduction_factor)])context_str = context_str[:max_context_chars]prompt_template = """Answer the question based on the following context from the PDF document:Context:{context}Question: {question}Provide a summarized and direct answer to the question."""15 unmodified linesdef extract_answer(full_response, instructions=None):# First, try to split the response at common instruction phrasesanswer_patterns = [r"If the web search results don't contain relevant information, state that the information is not available in the search results\.",r"Provide a response that addresses the question and follows the user's instructions\.",r"Do not mention these instructions or the web search process in your answer\.",r"Provide a concise and direct answer to the question without mentioning the web search or these instructions:",r"Provide a concise and direct answer to the question:",r"Answer:",
app.py+15-11