Update app.py
Browse files21 unmodified lines22232425262728349 unmodified lines3783793803813823833843853863877 unmodified lines39539639739839940040140240340440540640740840941041114 unmodified lines4264274284294304314324339 unmodified lines4434444454464474484494504514524534544555 unmodified lines46146246346446546646746846947047147217 unmodified lines4904914924934944954964974984995006 unmodified lines50750850951051151251351451551651751851952052152252352466 unmodified lines59159259359459559659759859960060160260321 unmodified linesfrom langchain_community.llms import HuggingFaceHubfrom langchain_core.documents import Documentfrom sentence_transformers import SentenceTransformerfrom llama_parse import LlamaParsehuggingface_token = os.environ.get("HUGGINGFACE_TOKEN")llama_cloud_api_key = os.environ.get("LLAMA_CLOUD_API_KEY")349 unmodified linesreturn truncate_text(context, max_tokens)def ask_question(question, temperature, top_p, repetition_penalty, web_search, chatbot, user_instructions):if not question:return "Please enter a question."model = get_model(temperature, top_p, repetition_penalty)# Update the chatbot's model7 unmodified linesdatabase = Nonemax_attempts = 3max_input_tokens = 20000 # Leave room for the model's responsemax_output_tokens = 800if web_search:contextualized_question, topics, entity_tracker, _ = chatbot.process_question(question)print(f"Contextualized question: {contextualized_question}")print(f"User Instructions: {user_instructions}")try:search_results = google_search(contextualized_question, num_results=5) # Increased from 3 to 5except Exception as e:print(f"Error in web search: {e}")return f"I apologize, but I encountered an error while searching for information: {str(e)}"14 unmodified linesdatabase.save_local("faiss_database")# Prepare context using rerankingcontext_str = prepare_context(contextualized_question, web_docs, max_input_tokens // 2) # Use half of max_input_tokens for contextinstruction_prompt = f"User Instructions: {user_instructions}\n" if user_instructions else ""9 unmodified linesProvide a concise and relevant answer to the question."""prompt_val = ChatPromptTemplate.from_template(prompt_template)current_conv_context = truncate_text(chatbot.get_context(), max_input_tokens // 4) # Use quarter of max_input_tokens for conversation contextcurrent_topics = topics[:5] # Limit to top 5 topicscurrent_entities = {k: list(v)[:3] for k, v in entity_tracker.items()} # Limit to top 3 entities per typeformatted_prompt = prompt_val.format(context=context_str,conv_context=current_conv_context,question=question,5 unmodified linesformatted_prompt = truncate_text(formatted_prompt, max_input_tokens)try:full_response = generate_chunked_response(model, formatted_prompt, max_tokens=max_output_tokens)answer = extract_answer(full_response, user_instructions)all_answers.append(answer)breakexcept Exception as e:print(f"Error in generate_chunked_response: {e}")if attempt == max_attempts - 1:all_answers.append(f"I apologize, but I encountered an error while generating the response. Please try again with a simpler question.")17 unmodified linesif database is None:return "No documents available. Please upload PDF documents to answer questions."retriever = database.as_retriever(search_kwargs={"k": 10}) # Retrieve more documents for rerankingrelevant_docs = retriever.get_relevant_documents(question)# Prepare context using rerankingcontext_str = prepare_context(question, relevant_docs, max_input_tokens // 2) # Use half of max_input_tokens for contextinstruction_prompt = f"User Instructions: {user_instructions}\n" if user_instructions else ""6 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)if estimate_tokens(formatted_prompt) > max_input_tokens:formatted_prompt = truncate_text(formatted_prompt, max_input_tokens)try:full_response = generate_chunked_response(model, formatted_prompt, max_tokens=max_output_tokens)answer = extract_answer(full_response, user_instructions)return answerexcept Exception as e:print(f"Error in generate_chunked_response: {e}")if attempt == max_attempts - 1:return f"I apologize, but I encountered an error while generating the response. Please try again with a simpler question."66 unmodified linesenhanced_context_driven_chatbot = EnhancedContextDrivenChatbot()def chat(question, history, temperature, top_p, repetition_penalty, web_search, user_instructions):answer = ask_question(question, temperature, top_p, repetition_penalty, web_search, enhanced_context_driven_chatbot, user_instructions)history.append((question, answer))return "", historysubmit_button.click(chat, inputs=[question_input, chatbot, temperature_slider, top_p_slider, repetition_penalty_slider, web_search_checkbox, instructions_input], outputs=[question_input, chatbot])clear_button = gr.Button("Clear Cache")clear_output = gr.Textbox(label="Cache Status")clear_button.click(clear_cache, inputs=[], outputs=clear_output)21 unmodified lines222324252627282930313233349 unmodified lines3833843853863873883893903913923933943953963973983994004014024034044054064077 unmodified lines41541641741841942042142242342442542642742814 unmodified lines4434444454464474484499 unmodified lines4594604614624634644654664674684695 unmodified lines47547647747847948048148248348448548648748848949049117 unmodified lines5095105115125135145155165175186 unmodified lines52552652752852953053153253353453553653753853954054154254354454554666 unmodified lines61361461561661761861962062162262362462562621 unmodified linesfrom langchain_community.llms import HuggingFaceHubfrom langchain_core.documents import Documentfrom sentence_transformers import SentenceTransformerfrom llama_parse importfrom llama_cpp import Llamafrom llama_cpp_agent.llm_agent import LlamaCppAgentfrom llama_cpp_agent.messages_formatter import MessagesFormatterTypefrom llama_cpp_agent.providers.llama_cpp_endpoint_provider import LlamaCppEndpointSettingshuggingface_token = os.environ.get("HUGGINGFACE_TOKEN")llama_cloud_api_key = os.environ.get("LLAMA_CLOUD_API_KEY")349 unmodified linesreturn truncate_text(context, max_tokens)# Initialize LlamaCppAgentdef initialize_llama_cpp_agent():main_model = LlamaCppEndpointSettings(completions_endpoint_url="http://127.0.0.1:8080/completion")llama_cpp_agent = LlamaCppAgent(main_model,debug_output=False,system_prompt="You are an AI assistant designed to help with RAG tasks.",predefined_messages_formatter_type=MessagesFormatterType.CHATML)return llama_cpp_agent# Modify the ask_question function to use LlamaCppAgentdef ask_question(question, temperature, top_p, repetition_penalty, web_search, chatbot, user_instructions):if not question:return "Please enter a question."llama_cpp_agent = initialize_llama_cpp_agent()model = get_model(temperature, top_p, repetition_penalty)# Update the chatbot's model7 unmodified linesdatabase = Nonemax_attempts = 3max_input_tokens = 20000max_output_tokens = 800if web_search:contextualized_question, topics, entity_tracker, _ = chatbot.process_question(question)try:search_results = google_search(contextualized_question, num_results=5)except Exception as e:print(f"Error in web search: {e}")return f"I apologize, but I encountered an error while searching for information: {str(e)}"14 unmodified linesdatabase.save_local("faiss_database")context_str = prepare_context(contextualized_question, web_docs, max_input_tokens // 2)instruction_prompt = f"User Instructions: {user_instructions}\n" if user_instructions else ""9 unmodified linesProvide a concise and relevant answer to the question."""current_conv_context = truncate_text(chatbot.get_context(), max_input_tokens // 4)current_topics = topics[:5]current_entities = {k: list(v)[:3] for k, v in entity_tracker.items()}formatted_prompt = prompt_template.format(context=context_str,conv_context=current_conv_context,question=question,5 unmodified linesformatted_prompt = truncate_text(formatted_prompt, max_input_tokens)try:# Use LlamaCppAgent for initial response generationinitial_response = llama_cpp_agent.get_chat_response(formatted_prompt, temperature=temperature)# Use generate_chunked_response for further refinement if neededfull_response = generate_chunked_response(model, initial_response, max_tokens=max_output_tokens)answer = extract_answer(full_response, user_instructions)all_answers.append(answer)breakexcept Exception as e:print(f"Error in response generation: {e}")if attempt == max_attempts - 1:all_answers.append(f"I apologize, but I encountered an error while generating the response. Please try again with a simpler question.")17 unmodified linesif database is None:return "No documents available. Please upload PDF documents to answer questions."retriever = database.as_retriever(search_kwargs={"k": 5})relevant_docs = retriever.get_relevant_documents(question)context_str = prepare_context(question, relevant_docs, max_input_tokens // 2)instruction_prompt = f"User Instructions: {user_instructions}\n" if user_instructions else ""6 unmodified linesProvide a summarized and direct answer to the question."""formatted_prompt = prompt_template.format(context=context_str, question=question)if estimate_tokens(formatted_prompt) > max_input_tokens:formatted_prompt = truncate_text(formatted_prompt, max_input_tokens)try:# Use LlamaCppAgent for initial response generationinitial_response = llama_cpp_agent.get_chat_response(formatted_prompt, temperature=temperature)# Use generate_chunked_response for further refinement if neededfull_response = generate_chunked_response(model, initial_response, max_tokens=max_output_tokens)answer = extract_answer(full_response, user_instructions)return answerexcept Exception as e:print(f"Error in response generation: {e}")if attempt == max_attempts - 1:return f"I apologize, but I encountered an error while generating the response. Please try again with a simpler question."66 unmodified linesenhanced_context_driven_chatbot = EnhancedContextDrivenChatbot()# Update the chat function to use the modified ask_question functiondef chat(question, history, temperature, top_p, repetition_penalty, web_search, user_instructions):answer = ask_question(question, temperature, top_p, repetition_penalty, web_search, enhanced_context_driven_chatbot, user_instructions)history.append((question, answer))return "", historysubmit_button.click(chat, inputs=[question_input, chatbot, temperature_slider, top_p_slider, repetition_penalty_slider, web_search_checkbox, instructions_input], outputs=[question_input, chatbot])clear_button = gr.Button("Clear Cache")clear_output = gr.Textbox(label="Cache Status")clear_button.click(clear_cache, inputs=[], outputs=clear_output)
app.py+47-24