ilhianois's picture
Update app.py
af81ab1 verified
Raw History Blame Contribute Delete
28.8 kB
import gradio as gr
import requests
import uuid
import os
import base64
from PIL import Image
import json # Added for parsing potential JSON errors
import gradio.themes as gr_themes # Import themes
# Default API URL and endpoint
#DEFAULT_BASE_URL = 'https://longevity-research-test-7a9c4333b535.herokuapp.com/'
DEFAULT_BASE_URL = 'https://longevity-zdi5.onrender.com/'
DEFAULT_ENDPOINT = "integrated_chat" # Default endpoint
API_TIMEOUT = 3000 # seconds
# List of available chat service endpoints
# AVAILABLE_ENDPOINTS = [ # Removed as endpoint is now fixed
# "research_chat",
# "lab_chat",
# "integrated_chat",
# "order_chat"
# ]
def create_demo():
# Initialize state as a dictionary to make it mutable
# state = {
# "session_id": str(uuid.uuid4()),
# "messages": [],
# "suggested_questions": [],
# "base_url": DEFAULT_BASE_URL,
# "endpoint": DEFAULT_ENDPOINT,
# "username": "test_user", # Adding default username for testing
# "user_id": 1 # Adding default user_id for testing
# }
def get_api_url(base_url, endpoint):
"""Get the full API URL based on base_url and endpoint"""
# Handle potential trailing slashes in base_url
base = base_url.rstrip('/')
# Handle potential leading slashes in endpoint
ep = endpoint.lstrip('/')
return f"{base}/{ep}"
def get_welcome_message(current_session_id, base_url):
endpoint = DEFAULT_ENDPOINT # Hardcoded endpoint
try:
api_url = get_api_url(base_url, endpoint)
# Use the endpoint-specific welcome endpoint
welcome_response = requests.get(f"{api_url}/welcome", timeout=API_TIMEOUT)
if welcome_response.status_code == 200:
welcome_data = welcome_response.json()
messages = [{"role": "assistant", "content": welcome_data["welcome_message"]}]
suggested_questions = welcome_data.get("suggested_questions", [])
return (
messages,
gr.update(visible=True),
suggested_questions,
current_session_id, # Return current session ID (unchanged on initial load)
gr.update(value="") # Clear session input field
)
else:
fallback_message = f"Welcome to Longevity Assistant! How can I help you today?"
return [{"role": "assistant", "content": fallback_message}], gr.update(visible=False), [], current_session_id, gr.update(value="")
except Exception as e:
print(f"Error connecting to server: {str(e)}")
fallback_message = f"Welcome to Longevity Assistant! How can I help you today?"
return [{"role": "assistant", "content": fallback_message}], gr.update(visible=False), [], current_session_id, gr.update(value="")
# Refactored restart_conversation
def restart_conversation(base_url):
endpoint = DEFAULT_ENDPOINT # Hardcoded endpoint
new_session_id = str(uuid.uuid4())
# Call get_welcome_message with the new session ID and current endpoint/base URL
messages, suggestions_visible, suggested_questions, _, session_input_clear = \
get_welcome_message(new_session_id, base_url)
# Return updates for UI elements and the new session ID state
return messages, suggestions_visible, suggested_questions, new_session_id, session_input_clear, new_session_id
# Refactored load_session
def load_session(new_session_id_input, current_session_id, base_url):
endpoint = DEFAULT_ENDPOINT # Hardcoded endpoint
if not new_session_id_input or not new_session_id_input.strip():
# If input is empty, return empty history and the current session ID (no change)
return [], gr.update(value=current_session_id), current_session_id
new_session_id = new_session_id_input.strip()
try:
api_url = get_api_url(base_url, endpoint)
response = requests.get(
f"{api_url}/history/{new_session_id}",
timeout=API_TIMEOUT
)
if response.status_code == 200:
history_data = response.json()
# Return loaded history, update display with new ID, update session state with new ID
return history_data.get("history", []), gr.update(value=new_session_id), new_session_id
else:
print(f"Error loading session {new_session_id}: Status {response.status_code}")
# Return empty history, update display with current ID, keep current session state
return [], gr.update(value=current_session_id), current_session_id
except Exception as e:
print(f"Error loading session {new_session_id}: {str(e)}")
# Return empty history, update display with current ID, keep current session state
return [], gr.update(value=current_session_id), current_session_id
# Refactored change_endpoint - REMOVED
# def change_endpoint(new_endpoint, refresh_session, current_session_id, base_url):
# if refresh_session:
# # Generate a new session ID and get welcome message for the new endpoint
# new_session_id = str(uuid.uuid4())
# messages, suggestions_visible, suggested_questions, _, session_input_clear = \
# get_welcome_message(new_session_id, base_url, new_endpoint)
# # Return UI updates, the new session ID, and the new endpoint for state updates
# return messages, suggestions_visible, suggested_questions, new_session_id, session_input_clear, new_session_id, new_endpoint
# else:
# # Just update the endpoint state, keep current session ID, clear chat UI
# return (
# [], # Clear chatbot
# gr.update(visible=False), # Hide suggestions
# [], # Clear suggested questions list
# current_session_id, # Keep current session ID in display
# gr.update(value=""), # Clear session input field
# current_session_id, # Keep current session ID in state
# new_endpoint # Update endpoint state
# )
def handle_chat(message, files, history, session_id, base_url):
endpoint = DEFAULT_ENDPOINT # Hardcoded endpoint
# Add user message to history
# Ensure history is a list (it should be, coming from Chatbot)
if history is None:
history = []
history.append({"role": "user", "content": message})
# Process the chat with files if any were uploaded
try:
current_api_url = get_api_url(base_url, endpoint)
# Create form data for the request
form_data = {
"session_id": session_id,
"message": message,
"user_id": 3
}
# Prepare files for multipart form upload
file_objects = None
if files:
file_objects = [
('files', (file.name, open(file.name, 'rb'), 'application/octet-stream'))
for file in files
]
# Add note about uploaded files to history
file_names = [os.path.basename(file.name) for file in files]
file_list = ", ".join(file_names)
history[-1]["content"] += f"\n\n📎 *Attached files: {file_list}*"
# Make the integrated request with both message and files
response = requests.post(
f"{current_api_url}",
data=form_data,
files=file_objects,
timeout=API_TIMEOUT
)
if response.status_code == 200:
response_data = response.json()
history.append({"role": "assistant", "content": response_data["response"]})
# Display links if any are returned
if response_data.get("links") and len(response_data["links"]) > 0:
links_text = "\n\n**Relevant Links:**\n"
for link in response_data["links"]:
links_text += f"- [{link['name']}]({link['url']})\n"
history[-1]["content"] += links_text
else:
try:
error_data = response.json()
error_detail = error_data.get('detail', 'Unknown error occurred')
except:
error_detail = response.text or 'Unknown error occurred'
error_message = f"Sorry, I encountered an error: {error_detail}"
history.append({"role": "assistant", "content": error_message})
except Exception as e:
import traceback
print("\nError during chat request:")
print(traceback.format_exc())
error_message = "Sorry, I'm having trouble connecting to the server."
history.append({"role": "assistant", "content": error_message})
finally:
# Cleanup temporary files associated with the upload
if files:
for file in files:
try:
if os.path.exists(file.name):
os.remove(file.name)
except Exception as e:
print(f"Error removing temporary file {file.name}: {str(e)}")
# Return updates for the text input (clear it), file input (clear it), and chatbot (updated history)
return "", None, history
# Refactored handle_doc_upload
def handle_doc_upload(files, session_id, base_url, username, user_id):
"""Handle document upload to the upload_docs endpoint"""
if not files:
return "Please select files to upload"
try:
# Create form data for the request
file_objects = None
if files:
file_objects = [
('files', (file.name, open(file.name, 'rb'), 'application/octet-stream'))
for file in files
]
# Add note about uploaded files to history
file_names = [os.path.basename(file.name) for file in files]
file_list = ", ".join(file_names)
form_data = {
"session_id": session_id,
"username": username,
"user_id": user_id
}
# Make the request to upload_docs endpoint
response = requests.post(
f"{base_url}/upload_docs",
data=form_data,
files=file_objects,
timeout=3600
)
if response.status_code == 200:
response_data = response.json()
return f"Successfully processed documents:\nUploaded chunks: {response_data['uploaded_chunks']}\nFailed chunks: {response_data['failed_chunks']}"
else:
return f"Error uploading documents: {response.text}"
except Exception as e:
return f"Error: {str(e)}"
finally:
# Cleanup temporary files
if files:
for file in files:
try:
if os.path.exists(file.name):
os.remove(file.name)
except Exception as e:
print(f"Error removing temporary file {file.name}: {str(e)}")
# --- Start: Prompt Management Functions ---
def get_research_prompt_api_url(base_url):
"""Constructs the specific URL for the research prompt API."""
return f"{base_url.rstrip('/')}/prompt/research"
def get_research_prompt(base_url):
"""Fetches the current research prompt from the backend."""
api_url = get_research_prompt_api_url(base_url)
try:
response = requests.get(api_url, timeout=API_TIMEOUT)
if response.status_code == 200:
return response.text # Assuming endpoint returns plain text
else:
print(f"Error fetching prompt: {response.status_code} - {response.text}")
return f"Error: Could not load prompt (Status: {response.status_code}). Using default." # Return error message or default
except Exception as e:
print(f"Error fetching prompt: {str(e)}")
return f"Error: Could not connect to server to load prompt. {str(e)}"
def save_research_prompt(base_url, session_id, prompt_text):
"""Saves the updated research prompt to the backend and returns a *new* session ID."""
api_url = get_research_prompt_api_url(base_url)
try:
payload = {"session_id": session_id, "prompt_text": prompt_text}
response = requests.post(api_url, json=payload, timeout=API_TIMEOUT) # Send as JSON
if response.status_code == 200:
new_session_id = str(uuid.uuid4())
status_message = "Research Agent prompt saved. Starting a new session with updated prompt."
# Return status message and the NEW session ID
return status_message, new_session_id
else:
try: # Try parsing JSON error detail
detail = response.json().get('detail', response.text)
except json.JSONDecodeError:
detail = response.text
return f"Error saving prompt: {response.status_code} - {detail}", None
except Exception as e:
print(f"Error saving prompt: {str(e)}")
return f"Error: Could not connect to server to save prompt. {str(e)}", None
def restore_default_prompt(base_url, session_id):
"""Restores the default research prompt via the backend and returns a *new* session ID."""
api_url = get_research_prompt_api_url(base_url)
try:
payload = {"session_id": session_id}
response = requests.delete(api_url, json=payload, timeout=API_TIMEOUT) # Send as JSON
if response.status_code == 200:
# Fetch the new default prompt to update the UI
new_prompt = get_research_prompt(base_url)
new_session_id = str(uuid.uuid4())
status_message = "Default Research Agent prompt restored. Starting a new session with default prompt."
# Return new prompt text, status message, and the NEW session ID
return new_prompt, status_message, new_session_id
else:
try: # Try parsing JSON error detail
detail = response.json().get('detail', response.text)
except json.JSONDecodeError:
detail = response.text
# Don't fetch new prompt on error, return current prompt state implicitly via Gradio update
return gr.update(), f"Error restoring default prompt: {response.status_code} - {detail}", None
except Exception as e:
print(f"Error restoring default prompt: {str(e)}")
# Don't fetch new prompt on error
return gr.update(), f"Error: Could not connect to server to restore prompt. {str(e)}", None
# --- End: Prompt Management Functions ---
# --- Start: Document Management Functions ---
def list_indexed_documents(base_url):
"""Fetches the list of distinct indexed documents from the backend."""
api_url = f"{base_url.rstrip('/')}/documents"
status_message = ""
choices = []
try:
print(f"API URL: {api_url}")
response = requests.get(api_url, timeout=API_TIMEOUT)
if response.status_code == 200:
data = response.json()
documents = data.get("documents", [])
if not documents:
status_message = "No indexed documents found."
else:
# Create choices for CheckboxGroup: (label, value)
# Label is file_name, Value is source_path
choices = [(doc.get("file_name", "Unknown"), doc.get("source_path"))
for doc in documents if doc.get("source_path")]
status_message = f"Found {len(choices)} indexed documents."
# Filter out any potential entries where source_path might be missing
choices = [choice for choice in choices if choice[1]]
if not choices:
status_message = "No valid indexed documents found after processing."
# Update CheckboxGroup with (label, value) pairs
return gr.update(choices=choices, value=[]), status_message
else:
error_msg = f"Error listing documents: {response.status_code} - {response.text}"
print(error_msg)
status_message = error_msg
return gr.update(choices=[], value=[]), status_message # Return empty choices on error
except Exception as e:
error_msg = f"Error connecting to server for listing documents: {str(e)}"
print(error_msg)
status_message = error_msg
return gr.update(choices=[], value=[]), status_message # Return empty choices on error
def delete_selected_documents(base_url, selected_paths):
"""Sends a request to delete documents based on selected source paths."""
if not selected_paths:
return "Please select at least one document to delete."
api_url = f"{base_url.rstrip('/')}/documents"
try:
payload = {"source_paths": selected_paths}
response = requests.delete(api_url, json=payload, timeout=API_TIMEOUT * 2) # Longer timeout for delete
if response.status_code == 200:
data = response.json()
status = data.get("overall_status", "Deletion request processed.")
# Potentially parse details for a more granular message
# details = data.get("details", {})
# successful_deletes = sum(1 for path, res in details.items() if res.get("successful"))
# failed_deletes = len(details) - successful_deletes
# status += f" Successful: {successful_deletes}, Failed: {failed_deletes}."
return status
else:
error_msg = f"Error deleting documents: {response.status_code} - {response.text}"
print(error_msg)
return error_msg
except Exception as e:
error_msg = f"Error connecting to server for deleting documents: {str(e)}"
print(error_msg)
return error_msg
# --- End: Document Management Functions ---
# Apply the Monochrome theme to Blocks
with gr.Blocks(theme='earneleh/paris', css="#chatbot { height: 500px; } .upload-box { height: 40px; min-height: 40px; }") as demo:
gr.Markdown("# 🧬 Longevity Assistant")
# Define State variables HERE, before UI elements that use them
session_id_state = gr.State(lambda: str(uuid.uuid4()))
base_url_state = gr.State(DEFAULT_BASE_URL)
username_state = gr.State("test_user")
user_id_state = gr.State(1)
question_list = gr.State([]) # Also move question_list state here
with gr.Tabs():
with gr.TabItem("Chat"):
# --- Existing Chat UI ---
with gr.Accordion("Prompt Customization (Research Agent)", open=False):
prompt_status_textbox = gr.Textbox(label="Status", interactive=False, value="")
research_prompt_textbox = gr.Textbox(
label="Current Customizable Prompt (Research Agent)",
lines=15,
interactive=True,
placeholder="Loading prompt..."
)
with gr.Row():
save_prompt_btn = gr.Button("Save and Apply Prompt")
restore_prompt_btn = gr.Button("Restore Default Prompt")
with gr.Row():
session_display = gr.Textbox(
label="Current Session ID",
interactive=False
)
session_input = gr.Textbox(
label="Enter Session ID to Restore",
placeholder="Paste a previous session ID here"
)
load_session_btn = gr.Button("Load Session")
restart_btn = gr.Button("Restart Conversation")
# Chatbot and input area
chatbot = gr.Chatbot(
[],
elem_id="chatbot",
height=500,
type="messages"
)
with gr.Row():
txt = gr.Textbox(
scale=4,
show_label=False,
placeholder="Enter text and press enter",
container=False
)
file_output = gr.File(
file_count="multiple",
label="",
scale=1,
container=False,
elem_classes="upload-box"
)
btn = gr.Button("Send", scale=1)
suggested_questions_container = gr.Column(visible=False)
with suggested_questions_container:
gr.Markdown("Try asking about:")
question_buttons = []
for i in range(4):
with gr.Row():
for j in range(2):
question_btn = gr.Button("", visible=False)
question_btn.click(
handle_chat,
[question_btn, gr.State(None), chatbot, session_id_state, base_url_state],
[txt, file_output, chatbot]
).then(
lambda: gr.update(visible=False),
None,
suggested_questions_container
)
question_buttons.append(question_btn)
# --- End Existing Chat UI ---
with gr.TabItem("Manage Documents"):
gr.Markdown("## Upload New Documents")
with gr.Row():
# Moved from Chat tab
doc_upload = gr.File(
file_count="multiple",
label="Select Documents to Upload",
scale=3
)
upload_docs_btn = gr.Button("Upload and Process Documents", scale=1)
upload_result = gr.Textbox(label="Upload Status", interactive=False)
gr.Markdown("## Manage Indexed Documents")
with gr.Column():
delete_status_textbox = gr.Textbox(label="Deletion Status", interactive=False)
refresh_docs_btn = gr.Button("Refresh Document List")
indexed_docs_checkboxgroup = gr.CheckboxGroup(label="Select indexed documents to delete", info="Note: Deleting a document removes all associated data.")
delete_docs_btn = gr.Button("Delete Selected Documents")
# Event Handlers for Chat Tab (need to be defined after components)
load_session_btn.click(
load_session,
inputs=[session_input, session_id_state, base_url_state],
outputs=[chatbot, session_display, session_id_state]
)
restart_btn.click(
restart_conversation,
inputs=[base_url_state],
outputs=[chatbot, suggested_questions_container, question_list, session_display, session_input, session_id_state]
)
txt.submit(
handle_chat,
inputs=[txt, file_output, chatbot, session_id_state, base_url_state],
outputs=[txt, file_output, chatbot]
)
btn.click(
handle_chat,
inputs=[txt, file_output, chatbot, session_id_state, base_url_state],
outputs=[txt, file_output, chatbot]
)
save_prompt_btn.click(
save_research_prompt,
inputs=[base_url_state, session_id_state, research_prompt_textbox],
outputs=[prompt_status_textbox, session_id_state]
).then(
lambda: ([], gr.update(visible=False), [], gr.update(value="")),
inputs=None,
outputs=[chatbot, suggested_questions_container, question_list, session_input]
).then(
lambda new_id: gr.update(value=new_id),
inputs=[session_id_state],
outputs=[session_display]
).then(
get_welcome_message,
inputs=[session_id_state, base_url_state],
outputs=[chatbot, suggested_questions_container, question_list, session_display, session_input]
)
restore_prompt_btn.click(
restore_default_prompt,
inputs=[base_url_state, session_id_state],
outputs=[research_prompt_textbox, prompt_status_textbox, session_id_state]
).then(
lambda: ([], gr.update(visible=False), [], gr.update(value="")),
inputs=None,
outputs=[chatbot, suggested_questions_container, question_list, session_input]
).then(
lambda new_id: gr.update(value=new_id),
inputs=[session_id_state],
outputs=[session_display]
).then(
get_welcome_message,
inputs=[session_id_state, base_url_state],
outputs=[chatbot, suggested_questions_container, question_list, session_display, session_input]
)
# Event Handlers for Manage Documents Tab
upload_docs_btn.click(
handle_doc_upload,
inputs=[doc_upload, session_id_state, base_url_state, username_state, user_id_state],
outputs=[upload_result]
).then( # Refresh list after upload attempt
list_indexed_documents,
inputs=[base_url_state],
outputs=[indexed_docs_checkboxgroup, delete_status_textbox]
)
refresh_docs_btn.click(
list_indexed_documents,
inputs=[base_url_state],
# Update checkbox choices and clear status message
outputs=[indexed_docs_checkboxgroup, delete_status_textbox]
)
delete_docs_btn.click(
delete_selected_documents,
inputs=[base_url_state, indexed_docs_checkboxgroup],
outputs=[delete_status_textbox]
).then( # Refresh list after delete attempt
list_indexed_documents,
inputs=[base_url_state],
outputs=[indexed_docs_checkboxgroup, delete_status_textbox]
)
# Initialize welcome message, prompt, AND document list on load
demo.load(
get_welcome_message,
inputs=[session_id_state, base_url_state],
outputs=[chatbot, suggested_questions_container, question_list, session_display, session_input]
).then(
get_research_prompt,
inputs=[base_url_state],
outputs=[research_prompt_textbox]
).then( # Also load initial document list
list_indexed_documents,
inputs=[base_url_state],
outputs=[indexed_docs_checkboxgroup, delete_status_textbox]
)
return demo
demo = create_demo()
if __name__ == "__main__":
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=True
)
else:
# For Gradio deployment
app = demo