Update app.py
Browse files351 unmodified lines3523533543553563573589 unmodified lines36836937037137237337437537637737837938038138238319 unmodified lines4034044054064074084099 unmodified lines4194204214224234244258 unmodified lines4344354364374384394404414424434444454463 unmodified lines45045145245345445545612 unmodified lines4694704714724734744754764774784794803 unmodified lines4844854864874884894904914924934943 unmodified lines4984995005015025035045055065075085095105115125135149 unmodified lines52452552652752852945 unmodified lines5755765775785795803 unmodified lines584585586587588589590591592593594595351 unmodified lines# 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."9 unmodified lineselse:database = Nonemax_attempts = 3 # Define the maximum number of attemptscontext_reduction_factor = 0.7max_tokens = 32000 # Maximum tokens allowed by the modelif web_search:contextualized_question, topics, entity_tracker, instructions = chatbot.process_question(question)# Log the contextualized question and instructions separately for debuggingprint(f"Contextualized question: {contextualized_question}")print(f"Instructions: {instructions}")try:search_results = google_search(contextualized_question, num_results=3)19 unmodified linescontext_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 ""prompt_template = f"""Answer the question based on the following web search results, conversation context, entity information, and user instructions:9 unmodified linesprompt_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 = topics8 unmodified linesentities=json.dumps(current_entities))# Estimate token count (rough estimate)estimated_tokens = len(formatted_prompt) // 4if estimated_tokens <= max_tokens - 1000: # Leave 1000 tokens for the model's responsebreak# 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))]3 unmodified linesraise ValueError("Context reduced too much. Unable to process the query.")full_response = generate_chunked_response(model, formatted_prompt, max_tokens=1000)answer = extract_answer(full_response, instructions)all_answers.append(answer)break12 unmodified linessources_section = "\n\nSources:\n" + "\n".join(f"- {source}" for source in sources)answer += sources_section# Update chatbot context with the answerchatbot.add_to_history(answer)return answerelse: # PDF document chatfor attempt in range(max_attempts):try:if database is None:3 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:{context}Question: {question}Provide a summarized and direct answer to the question."""3 unmodified linesestimated_tokens = estimate_tokens(formatted_prompt)if estimated_tokens <= max_tokens - 1000: # Leave 1000 tokens for the model's responsebreak# 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, max_tokens=1000)answer = extract_answer(full_response)return answer9 unmodified linesreturn "An unexpected error occurred. Please try again later."def extract_answer(full_response, instructions=None):answer_patterns = [r"Provide a concise and direct answer to the question without mentioning the web search or these instructions:",45 unmodified lineswith gr.Column(scale=2):chatbot = gr.Chatbot(label="Conversation")question_input = gr.Textbox(label="Ask a question")submit_button = gr.Button("Submit")with gr.Column(scale=1):temperature_slider = gr.Slider(label="Temperature", minimum=0.0, maximum=1.0, value=0.5, step=0.1)3 unmodified linesenhanced_context_driven_chatbot = EnhancedContextDrivenChatbot()def chat(question, history, temperature, top_p, repetition_penalty, web_search):answer = ask_question(question, temperature, top_p, repetition_penalty, web_search, enhanced_context_driven_chatbot)history.append((question, answer))return "", historysubmit_button.click(chat, inputs=[question_input, chatbot, temperature_slider, top_p_slider, repetition_penalty_slider, web_search_checkbox], outputs=[question_input, chatbot])clear_button = gr.Button("Clear Cache")clear_output = gr.Textbox(label="Cache Status")351 unmodified lines3523533543553563573589 unmodified lines36836937037137237337437537637737837938038138219 unmodified lines4024034044054064074089 unmodified lines4184194204214224238 unmodified lines4324334344354364374384394404414423 unmodified lines44644744844945045145212 unmodified lines4654664674684694704714724734744753 unmodified lines4794804814824834844854864874884894904914923 unmodified lines4964974984995005015025035045055065075085095105119 unmodified lines52152252352452552652745 unmodified lines5735745755765775785793 unmodified lines583584585586587588589590591592593594351 unmodified lines# Rough estimate: 1 token ~= 4 charactersreturn len(text) // 4def ask_question(question, temperature, top_p, repetition_penalty, web_search, chatbot, user_instructions):if not question:return "Please enter a question."9 unmodified lineselse:database = Nonemax_attempts = 3context_reduction_factor = 0.7max_tokens = 32000if 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=3)19 unmodified linescontext_str = "\n".join([f"Source: {doc.metadata['source']}\nContent: {doc.page_content}" for doc in web_docs])instruction_prompt = f"User Instructions: {user_instructions}\n" if user_instructions else ""prompt_template = f"""Answer the question based on the following web search results, conversation context, entity information, and user instructions:9 unmodified linesprompt_val = ChatPromptTemplate.from_template(prompt_template)current_context = context_strcurrent_conv_context = chatbot.get_context()current_topics = topics8 unmodified linesentities=json.dumps(current_entities))estimated_tokens = len(formatted_prompt) // 4if estimated_tokens <= max_tokens - 1000:breakcurrent_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))]3 unmodified linesraise ValueError("Context reduced too much. Unable to process the query.")full_response = generate_chunked_response(model, formatted_prompt, max_tokens=1000)answer = extract_answer(full_response, user_instructions)all_answers.append(answer)break12 unmodified linessources_section = "\n\nSources:\n" + "\n".join(f"- {source}" for source in sources)answer += sources_sectionchatbot.add_to_history(answer)return answerelse: # PDF document chatfor attempt in range(max_attempts):try:if database is None:3 unmodified linesrelevant_docs = retriever.get_relevant_documents(question)context_str = "\n".join([doc.page_content for doc in relevant_docs])instruction_prompt = f"User Instructions: {user_instructions}\n" if user_instructions else ""prompt_template = f"""Answer the question based on the following context from the PDF document:Context:{{context}}Question: {{question}}{instruction_prompt}Provide a summarized and direct answer to the question."""3 unmodified linesestimated_tokens = estimate_tokens(formatted_prompt)if estimated_tokens <= max_tokens - 1000:breakcontext_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, max_tokens=1000)answer = extract_answer(full_response, user_instructions)return answer9 unmodified linesreturn "An unexpected error occurred. Please try again later."def extract_answer(full_response, instructions=None):answer_patterns = [r"Provide a concise and direct answer to the question without mentioning the web search or these instructions:",45 unmodified lineswith gr.Column(scale=2):chatbot = gr.Chatbot(label="Conversation")question_input = gr.Textbox(label="Ask a question")instructions_input = gr.Textbox(label="Instructions for response (optional)", placeholder="Enter any specific instructions for the response here")submit_button = gr.Button("Submit")with gr.Column(scale=1):temperature_slider = gr.Slider(label="Temperature", minimum=0.0, maximum=1.0, value=0.5, step=0.1)3 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")
app.py+22-23