Update app.py
Browse files5 unmodified lines67891011121334 unmodified lines48495051525322 unmodified lines76777879808146 unmodified lines12812913013113213313413513613713813929 unmodified lines16917017117217317417517617717817918018118218318415 unmodified lines20020120220320420520620720820914 unmodified lines2242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942954 unmodified lines30030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240323 unmodified lines42742842943043143243315 unmodified lines4494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844855 unmodified linesfrom llama_index.llms.groq import Groqfrom llama_index.embeddings.huggingface import HuggingFaceEmbeddingfrom llama_index.core import Settings, VectorStoreIndex, StorageContext, load_index_from_storagefrom llama_index.core.retrievers import QueryFusionRetrieverfrom llama_index.retrievers.bm25 import BM25Retrieverfrom llama_index.core.llms import ChatMessagefrom llama_index.vector_stores.chroma import ChromaVectorStorefrom llama_index.core.storage.docstore import SimpleDocumentStore34 unmodified lines# Question reformulation promptreformulation_prompt = """Reformulate the following user message to be a short standalone question.If the question is too vague, just state it as it is.This reformulated question will be used to retrieve the documents.22 unmodified lines"""# Global variables to store stateretrieved_nodes_history = []def load_llm(temperature=0.7, max_tokens=1024):46 unmodified linesexcept Exception as e:raise ValueError(f"Error loading index: {e}")def reformulate_query(query, temperature=0.2):"""Reformulate the user query to be more specific and contextual"""llm = load_llm(temperature=temperature, max_tokens=256)# Format the reformulation promptprompt = reformulation_prompt.format(question=query)# Get reformulated query from LLMmessages = [ChatMessage(role="user", content=prompt)]29 unmodified linesreturn formatted_sourcesdef process_query(query, k=12, temperature=0.5, max_tokens=1024):"""Process a query using the RAG pipeline"""global retrieved_nodes_historyllm = load_llm(temperature=temperature, max_tokens=max_tokens)retriever = load_retriever(k=k)reranker = ColbertRerank(top_n=k)# Reformulate the query for better retrievalreformulated_query = reformulate_query(query, temperature=0.2)# Retrieve relevant nodes using the reformulated queryretrieved_nodes = retriever.retrieve(reformulated_query)15 unmodified lines)# Create chat messagesmessages = [ChatMessage(role="system", content=system_prompt),ChatMessage(role="user", content=full_prompt)]# Get response from LLMresponse = llm.chat(messages)14 unmodified lines"reformulated_query": reformulated_query # Store the reformulated query})# Update global variableretrieved_nodes_history = nodes_with_scoresreturn response.message.content, reformulated_querydef answer_question(question, k_value, temperature_value, max_tokens_value):"""Main function to answer a question"""# Process the query and get responseresponse, reformulated_query = process_query(question,k=k_value,temperature=temperature_value,max_tokens=max_tokens_value)# Return both the response and reformulated queryreturn response, format_nodes_for_display(), reformulated_querydef format_nodes_for_display():"""Format nodes for display in the UI"""if not retrieved_nodes_history:return "No documents retrieved yet."html_content = ""for idx, node in enumerate(retrieved_nodes_history):html_content += f"""<div style="margin-bottom: 20px; padding: 15px; border: 1px solid #ddd; border-radius: 5px; background-color: #f0f8ff;"><h4 style="color: #2c78d9; margin-top: 0;">Source {idx+1} (Relevance Score: {node['score']:.4f})</h4><div style="background-color: #ffffff; border: 1px solid #e0e0e0; border-radius: 4px; padding: 10px; margin-bottom: 10px;"><pre style="white-space: pre-wrap; max-height: 200px; overflow-y: auto; padding: 10px; font-size: 12px; margin: 0;">{node['full_content']}</pre></div><div style="margin-top: 10px; background-color: #f7f7f7; border: 1px solid #e0e0e0; border-radius: 4px; padding: 10px;"><strong>Metadata:</strong><pre style="white-space: pre-wrap; font-size: 12px; margin: 5px 0 0 0;">{json.dumps(node['metadata'], indent=2)}</pre></div></div>"""return html_contentdef save_response(response, question, reformulated_query):"""Save the response to a file"""data = {"original_question": question,"reformulated_question": reformulated_query,"response": response,"sources": [{"content": node.get('full_content', ''),"metadata": node.get('metadata', {}),"score": node.get('score', 0.0)}for node in retrieved_nodes_history],"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}json_data = json.dumps(data, indent=2)timestamp = datetime.now().strftime("%Y%m%d%H%M%S")filename = f"response_{timestamp}.json"# Create download linkencoded = base64.b64encode(json_data.encode()).decode()href = f"data:application/json;base64,{encoded}"return href, filenamedef main():# Check for API key4 unmodified lines.gradio-container {font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;}.answer-box {font-size: 14px;padding: 15px;border-radius: 8px;background-color: #e9f5ff; /* Light blue background from second implementation */border: 1px solid #c8e1ff;color: #333333; /* Dark text for better readability */}.query-box {font-size: 14px;padding: 10px;border-radius: 8px;background-color: #f0f2f5; /* User message color from second implementation */border: 1px solid #e0e0e0;margin-bottom: 10px;color: #333333;}#retrieved-nodes-container {max-height: 600px;overflow-y: auto;font-size: 12px;background-color: #ffffff;padding: 10px;border-radius: 8px;border: 1px solid #e0e0e0;}pre {font-size: 12px;}.node-container {margin-bottom: 15px;border: 1px solid #e6e9ef;border-radius: 6px;overflow: hidden;}.node-header {background-color: #f7f9fc;padding: 8px 12px;font-weight: 600;border-bottom: 1px solid #e6e9ef;}.node-content {padding: 12px;font-size: 12px;}.reformulated-query {background-color: #f7f7f7;padding: 10px 15px;border-radius: 8px;margin-bottom: 15px;border: 1px solid #e0e0e0;font-style: italic;}"""# Create the Gradio interfacewith gr.Blocks(css=css, theme=gr.themes.Soft(primary_hue="blue")) as demo:gr.Markdown("# AiDA: Observatory on Information and Democracy AI Assistant")gr.Markdown("Ask questions about information ecosystems, information disorders, social and news media, AI, and other topics related to information and democracy.")with gr.Row():with gr.Column(scale=3):# Question inputquestion_input = gr.Textbox(placeholder="Ask a question... e.g., what is the academic consensus on fact-checking?",label="Your Question",lines=2)# Reformulated query displayreformulated_query_display = gr.Textbox(label="Reformulated Query",lines=1,interactive=False,elem_classes="reformulated-query")# Answer displayanswer_box = gr.Textbox(label="Answer",lines=12,interactive=False,elem_classes="answer-box")with gr.Row():submit_btn = gr.Button("Submit Question", variant="primary")clear_btn = gr.Button("Clear", variant="secondary")download_btn = gr.Button("Save Response", variant="secondary")download_output = gr.File(label="Save Response", visible=False)with gr.Column(scale=2):with gr.Tab("Parameters"):23 unmodified lineswith gr.Tab("Retrieved Sources"):gr.Markdown("### Retrieved Documents")retrieved_nodes_html = gr.HTML(value="No documents retrieved yet.",elem_id="retrieved-nodes-container")15 unmodified lines# Set up event handlerssubmit_btn.click(answer_question,inputs=[question_input, k_value, temperature_value, max_tokens_value],outputs=[answer_box, retrieved_nodes_html, reformulated_query_display])question_input.submit(answer_question,inputs=[question_input, k_value, temperature_value, max_tokens_value],outputs=[answer_box, retrieved_nodes_html, reformulated_query_display])# Clear all fieldsclear_btn.click(lambda: ("", "No documents retrieved yet.", ""),None,[answer_box, retrieved_nodes_html, reformulated_query_display]).then(lambda: "",None,question_input)# Handle downloaddownload_btn.click(save_response,inputs=[answer_box, question_input, reformulated_query_display],outputs=[download_output, download_output])# Launch the appdemo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)), share=True)if __name__ == "__main__":main()5 unmodified lines678910111213141534 unmodified lines5051525354555622 unmodified lines7980818283848546 unmodified lines13213313413513613713813914014114214314414514614714814915015115215315415529 unmodified lines18518618718818919019119219319419519619719815 unmodified lines21421521621721821922022122222322422522622722822923014 unmodified lines2452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263274 unmodified lines33233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540623 unmodified lines43043143243343443543615 unmodified lines4524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005 unmodified linesfrom llama_index.llms.groq import Groqfrom llama_index.embeddings.huggingface import HuggingFaceEmbeddingfrom llama_index.core import Settings, VectorStoreIndex, StorageContext, load_index_from_storagefrom llama_index.core.node_parser import MarkdownNodeParserfrom llama_index.core.retrievers import QueryFusionRetrieverfrom llama_index.retrievers.bm25 import BM25Retrieverfrom llama_index.core.query_engine import RetrieverQueryEnginefrom llama_index.core.llms import ChatMessagefrom llama_index.vector_stores.chroma import ChromaVectorStorefrom llama_index.core.storage.docstore import SimpleDocumentStore34 unmodified lines# Question reformulation promptreformulation_prompt = """Reformulate the following user message to be a short standalone question.Use the conversation summary to add context if relevant.If the question is too vague, just state it as it is.This reformulated question will be used to retrieve the documents.22 unmodified lines"""# Global variables to store statemessages_history = []retrieved_nodes_history = []def load_llm(temperature=0.7, max_tokens=1024):46 unmodified linesexcept Exception as e:raise ValueError(f"Error loading index: {e}")def reformulate_query(query, chat_history, temperature=0.2):"""Reformulate the user query to be more specific and contextual"""llm = load_llm(temperature=temperature, max_tokens=256)# Create a simple summary of the chat history for contexthistory_summary = ""if chat_history:history_summary = "Based on our previous conversation about: "topics = []for user_msg, _ in chat_history[-3:]: # Use last 3 exchanges for contextif user_msg:topics.append(user_msg)history_summary += ", ".join(topics)# Format the reformulation promptprompt = reformulation_prompt.format(question=query)if history_summary:prompt = f"{history_summary}\n\n{prompt}"# Get reformulated query from LLMmessages = [ChatMessage(role="user", content=prompt)]29 unmodified linesreturn formatted_sourcesdef process_query(query, chat_history, system_prompt, k=12, temperature=0.5, max_tokens=1024):"""Process a query using the RAG pipeline"""llm = load_llm(temperature=temperature, max_tokens=max_tokens)retriever = load_retriever(k=k)reranker = ColbertRerank(top_n=k)# Reformulate the query for better retrievalreformulated_query = reformulate_query(query, chat_history, temperature=0.2)# Retrieve relevant nodes using the reformulated queryretrieved_nodes = retriever.retrieve(reformulated_query)15 unmodified lines)# Create chat messagesmessages = [ChatMessage(role="system", content=system_prompt)]# Add chat history - format expected from Gradio is list of [user_msg, assistant_msg] pairsfor user_msg, asst_msg in chat_history:if user_msg: # User messagemessages.append(ChatMessage(role="user", content=user_msg))if asst_msg: # Assistant messagemessages.append(ChatMessage(role="assistant", content=asst_msg))# Add the new query with contextmessages.append(ChatMessage(role="user", content=full_prompt))# Get response from LLMresponse = llm.chat(messages)14 unmodified lines"reformulated_query": reformulated_query # Store the reformulated query})return response.message.content, nodes_with_scoresdef chat_interface(message, history, k_value, temperature_value, max_tokens_value):global retrieved_nodes_history# Process the query and get response and nodesresponse, nodes = process_query(message,history,system_prompt,k=k_value,temperature=temperature_value,max_tokens=max_tokens_value)# Store the retrieved nodes for later displayretrieved_nodes_history = nodeshistory.append([message, response])return historydef clear_chat():global messages_history, retrieved_nodes_historymessages_history = []retrieved_nodes_history = []return None, []def download_chat():chat_export_data = []for user_msg, bot_msg in chatbot.value:if user_msg:chat_export_data.append({"role": "user", "content": user_msg})if bot_msg:chat_export_data.append({"role": "assistant", "content": bot_msg})chat_export = json.dumps(chat_export_data, indent=2)timestamp = datetime.now().strftime("%Y%m%d%H%M%S")filename = f"chat_history_{timestamp}.json"# Create download linkencoded = base64.b64encode(chat_export.encode()).decode()href = f"data:application/json;base64,{encoded}"return href, filenamedef format_nodes_for_display():"""Format nodes for display in the UI"""if not retrieved_nodes_history:return "No nodes retrieved yet."# Get the reformulated query from the first node (they all have the same)reformulated_query = retrieved_nodes_history[0].get('reformulated_query', 'N/A')html_content = f"""<div style="margin-bottom: 20px; padding: 15px; border: 1px solid #ddd; border-radius: 5px; background-color: #f7f7f7;"><strong>Reformulated Query:</strong> {reformulated_query}</div>"""for idx, node in enumerate(retrieved_nodes_history):html_content += f"""<div style="margin-bottom: 20px; padding: 15px; border: 1px solid #ddd; border-radius: 5px;"><h4>Node {idx+1} (Score: {node['score']:.4f})</h4><pre style="white-space: pre-wrap; max-height: 200px; overflow-y: auto; padding: 10px; background-color: #f7f7f7; font-size: 12px;">{node['full_content']}</pre><div style="margin-top: 10px;"><strong>Metadata:</strong><pre style="white-space: pre-wrap; font-size: 12px;">{json.dumps(node['metadata'], indent=2)}</pre></div></div>"""return html_contentdef update_retrieved_nodes():return format_nodes_for_display()def main():# Check for API key4 unmodified lines.gradio-container {font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;}.chat-bot {font-size: 14px !important;}.chat-bot .message {padding: 10px 15px !important;border-radius: 8px !important;margin-bottom: 10px !important;}.chat-bot .user-message {background-color: #f0f2f5 !important;}.chat-bot .assistant-message {background-color: #e9f5ff !important;}#retrieved-nodes-container {max-height: 600px;overflow-y: auto;font-size: 12px;}pre {font-size: 12px !important;}.node-container {margin-bottom: 15px;border: 1px solid #e6e9ef;border-radius: 6px;overflow: hidden;}.node-header {background-color: #f7f9fc;padding: 8px 12px;font-weight: 600;border-bottom: 1px solid #e6e9ef;}.node-content {padding: 12px;font-size: 12px;}"""# Create the Gradio interfacewith gr.Blocks(css=css) as demo:gr.Markdown("# AiDA: Observatory on Information and Democracy AI Assistant")gr.Markdown("Ask questions about information ecosystems, information disorders, social and news media, AI, and other topics related to information and democracy.")with gr.Row():with gr.Column(scale=3):chatbot = gr.Chatbot(height=400,label="Chat with AiDA",show_label=True,elem_classes="chat-bot")with gr.Row():with gr.Column(scale=8):msg = gr.Textbox(placeholder="Ask a question... e.g., what is the academic consensus on fact-checking?",label="Your Question",show_label=False,lines=2)with gr.Column(scale=1):submit_btn = gr.Button("Submit", variant="primary")with gr.Row():clear_btn = gr.Button("Clear Chat", variant="secondary")download_btn = gr.Button("Download Chat", variant="secondary")download_output = gr.File(label="Download Chat History", visible=False)with gr.Column(scale=2):with gr.Tab("Parameters"):23 unmodified lineswith gr.Tab("Retrieved Sources"):gr.Markdown("### Retrieved Documents")retrieved_nodes_html = gr.HTML(value="No nodes retrieved yet.",elem_id="retrieved-nodes-container")15 unmodified lines# Set up event handlerssubmit_btn.click(chat_interface,inputs=[msg, chatbot, k_value, temperature_value, max_tokens_value],outputs=chatbot).then(lambda: "",None,msg).then(update_retrieved_nodes,None,retrieved_nodes_html)msg.submit(chat_interface,inputs=[msg, chatbot, k_value, temperature_value, max_tokens_value],outputs=chatbot).then(lambda: "",None,msg).then(update_retrieved_nodes,None,retrieved_nodes_html)# Clear both the chat and retrieved nodes displayclear_btn.click(clear_chat,None,[chatbot, retrieved_nodes_html])download_btn.click(download_chat,None,[download_output, download_output])# Launch the appdemo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)), share=True)if __name__ == "__main__":main()
app.py+153-138