Spaces:
Runtime error
Runtime error
Update client_demo_ui.py to reflect client-scoped knowledge base changes
Browse files123456789101112131415161718192021222324252627282930317 unmodified lines3940414243444546474849505152535455565758596061626364656667681 unmodified line707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167import streamlit as stimport requestsimport uuidfrom dotenv import load_dotenv# Load environment variablesload_dotenv()# --- Configuration ---# This will be the public URL of your deployed FastAPI serviceAPI_URL = "http://127.0.0.1:8000"st.set_page_config(page_title="Nutritionist Panel", layout="wide")# --- Session State Initialization ---if 'api_key' not in st.session_state:st.session_state.api_key = ""if 'api_key_valid' not in st.session_state:st.session_state.api_key_valid = Falseif 'chat_session_id' not in st.session_state:st.session_state.chat_session_id = str(uuid.uuid4())if 'messages' not in st.session_state:st.session_state.messages = []if 'current_patient_id' not in st.session_state:st.session_state.current_patient_id = ""# --- Sidebar for API Key (Login) ---st.sidebar.title("B2B Client Panel")if not st.session_state.api_key_valid:st.sidebar.header("Login")7 unmodified linesif not api_key_input:st.sidebar.error("Please enter an API key.")else:# --- Test the API Key by calling the root endpoint ---try:headers = {'X-API-Key': api_key_input}# We test the key against a protected endpoint like /chat/get_response# We'll send a dummy requestresponse = requests.post(f"{API_URL}/chat/get_response",headers=headers,json={"client_user_id": "test_login","question": "test","session_id": "test_login"},stream=True)# If we get 401, the key is bad.# If we get 200 (a streaming response), the key is good.if response.status_code == 401:st.sidebar.error("Invalid API Key.")elif response.status_code == 200:st.session_state.api_key = api_key_inputst.session_state.api_key_valid = Truest.rerun()else:st.sidebar.error(f"API Error ({response.status_code}). Please check server.")1 unmodified linest.error(f"Could not connect to the API: {e}. Is the backend running at {API_URL}?")else:# --- Main Application View (after login) ---st.sidebar.success("API Key Validated")if st.sidebar.button("Logout"):st.session_state.api_key = ""st.session_state.api_key_valid = Falsest.session_state.messages = []st.rerun()st.title("Patient Management Dashboard")# --- Patient ID Input ---st.info("Enter a unique ID for the patient you want to manage. This can be any string (e.G., 'patient_001', 'jane_doe_45').")patient_id = st.text_input("Current Patient ID:", key="patient_id_input")if patient_id:# Check if we switched patients, if so, clear chatif patient_id != st.session_state.current_patient_id:st.session_state.messages = []st.session_state.current_patient_id = patient_idst.session_state.chat_session_id = str(uuid.uuid4())st.success(f"Loaded patient: {patient_id}")tab1, tab2 = st.tabs(["π¬ Chat with Patient", "π§ Manage Patient Knowledge"])# --- Tab 1: Chat with Patient ---with tab1:st.header(f"Chatting as Patient: {patient_id}")for message in st.session_state.messages:with st.chat_message(message["role"]):st.markdown(message["content"])if prompt := st.chat_input("Ask the bot a question..."):st.session_state.messages.append({"role": "user", "content": prompt})with st.chat_message("user"):st.markdown(prompt)with st.chat_message("assistant"):with st.spinner("Getting response..."):try:headers = {'X-API-Key': st.session_state.api_key}payload = {"client_user_id": patient_id,"question": prompt,"session_id": st.session_state.chat_session_id}response = requests.post(f"{API_URL}/chat/get_response",headers=headers,json=payload,stream=True)if response.status_code == 200:st.write_stream(response.iter_content())else:st.error(f"Failed to get response ({response.status_code}): {response.text}")except requests.exceptions.RequestException as e:st.error(f"Could not connect to the API: {e}")# --- Tab 2: Manage Patient Knowledge ---with tab2:st.header(f"Upload Documents for: {patient_id}")st.info("Upload .pdf or .docx files. This knowledge will be *permanently* added for this patient only.")uploaded_file = st.file_uploader("Upload a document",type=['pdf', 'docx'],key="patient_doc_uploader",accept_multiple_files=False)if uploaded_file is not None:if st.button(f"Process '{uploaded_file.name}'"):with st.spinner(f"Processing {uploaded_file.name}..."):try:headers = {'X-API-Key': st.session_state.api_key}files = {'file': (uploaded_file.name, uploaded_file, uploaded_file.type)}payload = {'client_user_id': patient_id}response = requests.post(f"{API_URL}/upload_document/",headers=headers,files=files,data=payload)if response.status_code == 200:st.success(f"β Successfully added '{uploaded_file.name}' to {patient_id}'s knowledge base!")else:st.error(f"Error processing file ({response.status_code}): {response.text}")except Exception as e:st.error(f"An error occurred: {e}")if not st.session_state.api_key_valid:st.title("Welcome to the Nutrition Bot B2B Demo")st.header("Please log in with your provided API key using the sidebar.")1234567891011121314151617181920212223242526272829303132337 unmodified lines414243444546474849505152535455565758591 unmodified line616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218import streamlit as stimport requestsimport uuidimport pandas as pdfrom dotenv import load_dotenvimport os# Load environment variablesload_dotenv()# --- Configuration ---# This will be the public URL of your deployed FastAPI serviceAPI_URL = os.getenv("API_URL", "http://127.0.0.1:8000")st.set_page_config(page_title="Client Knowledge Portal", layout="wide", page_icon="π’")# --- Session State Initialization ---if 'api_key' not in st.session_state:st.session_state.api_key = ""if 'api_key_valid' not in st.session_state:st.session_state.api_key_valid = Falseif 'client_name' not in st.session_state:st.session_state.client_name = ""if 'chat_session_id' not in st.session_state:st.session_state.chat_session_id = str(uuid.uuid4())if 'messages' not in st.session_state:st.session_state.messages = []# --- Sidebar for API Key (Login) ---st.sidebar.title("π’ Client Portal")if not st.session_state.api_key_valid:st.sidebar.header("Login")7 unmodified linesif not api_key_input:st.sidebar.error("Please enter an API key.")else:# --- Test the API Key by calling the documents endpoint ---try:headers = {'X-API-Key': api_key_input}response = requests.get(f"{API_URL}/documents/", headers=headers)if response.status_code == 200:data = response.json()st.session_state.api_key = api_key_inputst.session_state.api_key_valid = Truest.session_state.client_name = data.get("client_name", "Client")st.rerun()elif response.status_code == 401:st.sidebar.error("Invalid API Key.")else:st.sidebar.error(f"API Error ({response.status_code}). Please check server.")1 unmodified linest.error(f"Could not connect to the API: {e}. Is the backend running at {API_URL}?")else:# --- Main Application View (after login) ---st.sidebar.success(f"Logged in as: {st.session_state.client_name}")if st.sidebar.button("Logout"):st.session_state.api_key = ""st.session_state.api_key_valid = Falsest.session_state.messages = []st.rerun()st.title(f"π Welcome, {st.session_state.client_name}")st.markdown("Manage your specialized knowledge base and test your bot.")tab1, tab2, tab3 = st.tabs(["π€ Upload Documents", "π Manage Documents", "π¬ Test Chat"])# --- Tab 1: Upload Documents ---with tab1:st.header("Upload Knowledge")st.info("Upload PDF or DOCX files to train your bot. These documents will be added to your private knowledge base.")uploaded_files = st.file_uploader("Choose files",type=['pdf', 'docx', 'doc'],accept_multiple_files=True)if uploaded_files:if st.button(f"Upload {len(uploaded_files)} Files"):with st.spinner("Uploading and processing..."):try:headers = {'X-API-Key': st.session_state.api_key}files = [('files', (f.name, f, f.type)) for f in uploaded_files]response = requests.post(f"{API_URL}/upload_documents/",headers=headers,files=files)if response.status_code == 200:result = response.json()st.success(f"Processed {result['total_files']} files!")# Show results detailresults_df = pd.DataFrame(result['results'])st.dataframe(results_df)else:st.error(f"Upload failed ({response.status_code}): {response.text}")except Exception as e:st.error(f"Error: {e}")# --- Tab 2: Manage Documents ---with tab2:st.header("Your Documents")if st.button("Refresh List"):st.rerun()try:headers = {'X-API-Key': st.session_state.api_key}response = requests.get(f"{API_URL}/documents/", headers=headers)if response.status_code == 200:data = response.json()docs = data.get("documents", [])if not docs:st.info("No documents found. Go to the Upload tab to add some!")else:# Display as a table with delete buttonsfor doc in docs:col1, col2, col3, col4, col5 = st.columns([3, 2, 1, 1, 1])with col1:st.write(f"**{doc['filename']}**")with col2:st.write(f"{doc['upload_date'][:10]}")with col3:st.write(f"{doc['chunk_count']} chunks")with col4:status_color = "green" if doc['status'] == "completed" else "orange"st.markdown(f":{status_color}[{doc['status']}]")with col5:if st.button("ποΈ", key=f"del_{doc['id']}", help="Delete document"):with st.spinner("Deleting..."):del_res = requests.delete(f"{API_URL}/documents/{doc['id']}",headers=headers)if del_res.status_code == 200:st.success("Deleted!")st.rerun()else:st.error("Failed")else:st.error("Failed to fetch documents.")except Exception as e:st.error(f"Error fetching documents: {e}")# --- Tab 3: Test Chat ---with tab3:st.header("Test Your Bot")st.markdown("Test how the bot answers questions using your uploaded knowledge.")# Chat interfacefor message in st.session_state.messages:with st.chat_message(message["role"]):st.markdown(message["content"])if prompt := st.chat_input("Ask a question..."):st.session_state.messages.append({"role": "user", "content": prompt})with st.chat_message("user"):st.markdown(prompt)with st.chat_message("assistant"):message_placeholder = st.empty()full_response = ""try:headers = {'X-API-Key': st.session_state.api_key}payload = {"question": prompt,"session_id": st.session_state.chat_session_id}with st.spinner("Thinking..."):response = requests.post(f"{API_URL}/chat/get_response",headers=headers,json=payload,stream=True)if response.status_code == 200:for chunk in response.iter_content(chunk_size=None):if chunk:content = chunk.decode('utf-8')full_response += contentmessage_placeholder.markdown(full_response + "β")message_placeholder.markdown(full_response)st.session_state.messages.append({"role": "assistant", "content": full_response})else:st.error(f"Error ({response.status_code}): {response.text}")except Exception as e:st.error(f"Connection error: {e}")if not st.session_state.api_key_valid:st.title("Welcome to the Client Portal")st.markdown("""This portal allows B2B clients to:- **Upload** specialized medical/nutritional documents- **Manage** their private knowledge base- **Test** their specialized chatbotPlease log in with your API Key to continue.""")
client_demo_ui.py+152-101