Update app.py
Browse files324 unmodified lines32532632732832933010 unmodified lines3413423433443453463473483493503513523533543553563573583593603613 unmodified lines36536636736836937037110 unmodified lines38238338438538638738838939039139239339439539639739839940040140240340415 unmodified lines4204214224234244254264274284294304312 unmodified lines434435436437438439440441442443444445446447448449450451324 unmodified linesreturn all_resultsdef ask_question(question, temperature, top_p, repetition_penalty, web_search, chatbot):if not question:return "Please enter a question."10 unmodified lineselse:database = Nonemax_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 ""10 unmodified lines"""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)answer = extract_answer(full_response, instructions)all_answers.append(answer)breakexcept Exception as e:print(f"Error in ask_question (attempt {attempt + 1}): {e}")if attempt == max_attempts - 1:all_answers.append(f"I apologize, but I'm having trouble processing the query due to its length or complexity.")answer = "\n\n".join(all_answers)sources = set(doc.metadata['source'] for doc in web_docs)15 unmodified linesrelevant_docs = retriever.get_relevant_documents(question)context_str = "\n".join([doc.page_content for doc in relevant_docs])if attempt > 0:words = 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:2 unmodified linesProvide a summarized and direct answer to the question."""prompt_val = ChatPromptTemplate.from_template(prompt_template)formatted_prompt = prompt_val.format(context=context_str, question=question)full_response = generate_chunked_response(model, formatted_prompt)answer = extract_answer(full_response)return answerexcept Exception as e:print(f"Error in ask_question (attempt {attempt + 1}): {e}")if attempt == max_attempts - 1:return f"I apologize, but I'm having trouble processing your question. Could you please try rephrasing it more concisely?"return "An unexpected error occurred. Please try again later."324 unmodified lines32532632732832933033133233333410 unmodified lines3453463473483493503513523533543553563573583593603613623633643 unmodified lines36836937037137237310 unmodified lines38438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343415 unmodified lines4504514524534544552 unmodified lines458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492324 unmodified linesreturn all_resultsdef estimate_tokens(text):# Rough estimate: 1 token ~= 4 charactersreturn len(text) // 4def ask_question(question, temperature, top_p, repetition_penalty, web_search, chatbot):if not question:return "Please enter a question."10 unmodified lineselse:database = Nonemax_attempts = 5context_reduction_factor = 0.7max_estimated_tokens = 30000 # Leave some room for the model's responseif 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()}search_results = google_search(contextualized_question, num_results=3)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 ""10 unmodified lines"""prompt_val = ChatPromptTemplate.from_template(prompt_template)# Start with full context and progressively reduce if necessarycurrent_context = context_strcurrent_conv_context = chatbot.get_context()current_topics = topicscurrent_entities = serializable_entity_trackerwhile True:formatted_prompt = prompt_val.format(context=current_context,conv_context=current_conv_context,question=question,topics=", ".join(current_topics),entities=json.dumps(current_entities))# Estimate token countestimated_tokens = estimate_tokens(formatted_prompt)if estimated_tokens <= max_estimated_tokens:break# Reduce context if estimated token count is too highcurrent_context = current_context[:int(len(current_context) * context_reduction_factor)]current_conv_context = current_conv_context[:int(len(current_conv_context) * context_reduction_factor)]current_topics = current_topics[:max(1, int(len(current_topics) * context_reduction_factor))]current_entities = {k: v[:max(1, int(len(v) * context_reduction_factor))] for k, v in current_entities.items()}if len(current_context) + len(current_conv_context) + len(str(current_topics)) + len(str(current_entities)) < 100:raise ValueError("Context reduced too much. Unable to process the query.")full_response = generate_chunked_response(model, formatted_prompt)answer = extract_answer(full_response, instructions)all_answers.append(answer)breakexcept ValueError as ve:print(f"Error in ask_question (attempt {attempt + 1}): {ve}")if attempt == max_attempts - 1:all_answers.append(f"I apologize, but I'm having trouble processing the query due to its length or complexity. Could you please try asking a more specific or shorter question?")except Exception as e:print(f"Error in ask_question (attempt {attempt + 1}): {e}")if attempt == max_attempts - 1:all_answers.append(f"I apologize, but an unexpected error occurred. Please try again with a different question or check your internet connection.")answer = "\n\n".join(all_answers)sources = set(doc.metadata['source'] for doc in web_docs)15 unmodified linesrelevant_docs = retriever.get_relevant_documents(question)context_str = "\n".join([doc.page_content for doc in relevant_docs])prompt_template = """Answer the question based on the following context from the PDF document:Context:2 unmodified linesProvide a summarized and direct answer to the question."""while True:prompt_val = ChatPromptTemplate.from_template(prompt_template)formatted_prompt = prompt_val.format(context=context_str, question=question)estimated_tokens = estimate_tokens(formatted_prompt)if estimated_tokens <= max_estimated_tokens:break# Reduce context if estimated token count is too highcontext_str = context_str[:int(len(context_str) * context_reduction_factor)]if len(context_str) < 100:raise ValueError("Context reduced too much. Unable to process the query.")full_response = generate_chunked_response(model, formatted_prompt)answer = extract_answer(full_response)return answerexcept ValueError as ve:print(f"Error in ask_question (attempt {attempt + 1}): {ve}")if attempt == max_attempts - 1:return f"I apologize, but I'm having trouble processing your question due to the complexity of the document. Could you please try asking a more specific or shorter question?"except Exception as e:print(f"Error in ask_question (attempt {attempt + 1}): {e}")if attempt == max_attempts - 1:return f"I apologize, but an unexpected error occurred. Please try again with a different question."return "An unexpected error occurred. Please try again later."
app.py+64-23