Update app.py
Browse files239 unmodified lines24024124224324424524624724824925025125225325425525625751 unmodified lines3093103113123133143157 unmodified lines3233243253263273283293303313323333343353363373383393403413423433443453461 unmodified line34834935035135235335435535635710 unmodified lines368369370371372373374375376377378379380381382383384385386387388389390139 unmodified lines530531532533534535536537538539540239 unmodified linesif content is None:return "No content available to summarize."# Approximate the token limit using character count# Assuming an average of 4 characters per tokenmax_chars = 7000 * 4 # Leave some room for the promptif len(content) > max_chars:content = content[:max_chars] + "..."summary_prompt = f"""Summarize the following content concisely:{content}Summary:"""summary = generate_chunked_response(model, summary_prompt, max_tokens=200)return summarydef rank_search_results(titles, summaries, model):51 unmodified linessummary = summarize_content(result["text"], model)processed_results.append({"title": result.get("title", f"Result {index}"),"content": result["text"],"summary": summary,"index": index})7 unmodified linesprint(f"Number of processed results: {len(processed_results)}")# Rank the resultstitles = [r["title"] for r in processed_results]summaries = [r["summary"] for r in processed_results]try:ranks = rank_search_results(titles, summaries, model)except Exception as e:print(f"Error in ranking results: {str(e)}. Using default ranking.")ranks = list(range(1, len(processed_results) + 1))print(f"Number of ranks: {len(ranks)}")# Update Vector DBcurrent_date = datetime.now().strftime("%Y-%m-%d")update_vector_db_with_search_results(processed_results, ranks, current_date)# Prepare context for the questioncontext_str = "\n\n".join([f"Title: {r['title']}\nSummary: {r['summary']}\nRank: {ranks[i]}"for i, r in enumerate(processed_results)])prompt_template = """Answer the question based on the following web search results:1 unmodified line{context}Current Question: {question}If the web search results don't contain relevant information, state that the information is not available in the search results.Provide a concise and direct answer to the question without mentioning the web search or these instructions:"""prompt_val = ChatPromptTemplate.from_template(prompt_template)formatted_prompt = prompt_val.format(context=context_str, question=question)else:if database is None:return "No documents available. Please upload documents or enable web search to answer questions."10 unmodified linesprompt_val = ChatPromptTemplate.from_template(prompt)formatted_prompt = prompt_val.format(history=history_str, context=context_str, question=question)full_response = generate_chunked_response(model, formatted_prompt)# Extract only the part after the last occurrence of a prompt-like sentenceanswer_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:"]for pattern in answer_patterns:match = re.split(pattern, full_response, flags=re.IGNORECASE)if len(match) > 1:answer = match[-1].strip()breakelse:# If no pattern is found, return the full responseanswer = full_response.strip()if not web_search:memory_database[question] = answer139 unmodified linestop_p_slider = gr.Slider(label="Top P", minimum=0.0, maximum=1.0, value=0.9, step=0.1)repetition_penalty_slider = gr.Slider(label="Repetition Penalty", minimum=1.0, maximum=2.0, value=1.0, step=0.1)web_search_checkbox = gr.Checkbox(label="Enable Web Search", value=False)def chat(question, history, temperature, top_p, repetition_penalty, web_search):answer = ask_question(question, temperature, top_p, repetition_penalty, web_search)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])239 unmodified lines24024124224324424524624724824925025125225351 unmodified lines3053063073083093107 unmodified lines3183193203213223233243253263273283293303313323331 unmodified line33533633733833934034134234334434534610 unmodified lines357358359360361362363139 unmodified lines503504505506507508509510511512513514515516517518519520521239 unmodified linesif content is None:return "No content available to summarize."summary_prompt = f"""Summarize the following news article in 10-15 lines. Focus on the key points, main events, and significant details. Ensure the summary is informative and relevant to current news:{content[:3000]} # Limit input to avoid token limitsSummary:"""summary = generate_chunked_response(model, summary_prompt, max_tokens=300) # Adjust max_tokens as neededreturn summarydef rank_search_results(titles, summaries, model):51 unmodified linessummary = summarize_content(result["text"], model)processed_results.append({"title": result.get("title", f"Result {index}"),"summary": summary,"index": index})7 unmodified linesprint(f"Number of processed results: {len(processed_results)}")# For news requests, return the summaries directlyif "news" in question.lower():news_response = "Here are the latest news summaries on this topic:\n\n"for result in processed_results[:5]: # Limit to top 5 resultsnews_response += f"Title: {result['title']}\n\nSummary: {result['summary']}\n\n---\n\n"return news_response.strip()# For other questions, use the summaries as contextcontext_str = "\n\n".join([f"Title: {r['title']}\nSummary: {r['summary']}"for r in processed_results])prompt_template = """Answer the question based on the following web search results:1 unmodified line{context}Current Question: {question}If the web search results don't contain relevant information, state that the information is not available in the search results.Provide a concise and direct answer to the question:"""prompt_val = ChatPromptTemplate.from_template(prompt_template)formatted_prompt = prompt_val.format(context=context_str, question=question)answer = generate_chunked_response(model, formatted_prompt)else:if database is None:return "No documents available. Please upload documents or enable web search to answer questions."10 unmodified linesprompt_val = ChatPromptTemplate.from_template(prompt)formatted_prompt = prompt_val.format(history=history_str, context=context_str, question=question)answer = generate_chunked_response(model, formatted_prompt)if not web_search:memory_database[question] = answer139 unmodified linestop_p_slider = gr.Slider(label="Top P", minimum=0.0, maximum=1.0, value=0.9, step=0.1)repetition_penalty_slider = gr.Slider(label="Repetition Penalty", minimum=1.0, maximum=2.0, value=1.0, step=0.1)web_search_checkbox = gr.Checkbox(label="Enable Web Search", value=False)def chat(question, history, temperature, top_p, repetition_penalty, web_search):answer = ask_question(question, temperature, top_p, repetition_penalty, web_search)if "news" in question.lower():# Split the answer into individual news itemsnews_items = answer.split("---")for item in news_items:if item.strip():history.append((question, item.strip()))else: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])
app.py+29-48