import streamlit as st import sqlite3 import pandas as pd # Initialize Session States for Conversational History if not present if "chats" not in st.session_state: st.session_state.chats = { "Chat 1": [{"role": "assistant", "content": "Hello! How can I help you today?"}], "Chat 2": [{"role": "assistant", "content": "Welcome to NewPhamaGPT. Ask me anything."}] } if "active_chat" not in st.session_state: st.session_state.active_chat = "Chat 1" # Database helper function (Modify with your actual DB path/type) DB_PATH = "pharma_data.db" def add_sql_record(med_name, dosage, stock): conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() # Create table if it doesn't exist for testing purposes cursor.execute('''CREATE TABLE IF NOT EXISTS inventory (id INTEGER PRIMARY KEY, medicine_name TEXT, dosage TEXT, stock INTEGER)''') cursor.execute("INSERT INTO inventory (medicine_name, dosage, stock) VALUES (?, ?, ?)", (med_name, dosage, stock)) conn.commit() conn.close() # ========================================== # FEATURE 1 & 2: LEFT SIDEBAR CHAT LIST & RENAME # ========================================== st.sidebar.title("💬 Conversational Chats") # New Chat Button if st.sidebar.button("➕ New Chat", use_container_width=True): new_chat_title = f"Chat {len(st.session_state.chats) + 1}" st.session_state.chats[new_chat_title] = [{"role": "assistant", "content": "Hello! New chat started."}] st.session_state.active_chat = new_chat_title st.rerun() st.sidebar.markdown("---") # Render Chats as a clickable list instead of a dropdown for chat_title in list(st.session_state.chats.keys()): # Highlight the currently active chat is_active = (chat_title == st.session_state.active_chat) button_label = f"📝 {chat_title}" if is_active else f"📄 {chat_title}" if st.sidebar.button(button_label, key=f"select_{chat_title}", use_container_width=True): st.session_state.active_chat = chat_title st.rerun() st.sidebar.markdown("---") # Feature 2: Rename Option for the currently active chat st.sidebar.subheader("✏️ Rename Active Chat") current_name = st.session_state.active_chat new_name = st.sidebar.text_input("New Title", value=current_name, key="rename_input") if st.sidebar.button("Save Title", use_container_width=True): if new_name and new_name != current_name: if new_name in st.session_state.chats: st.sidebar.error("A chat with this name already exists!") else: # Re-map the key in the dictionary to keep history intact st.session_state.chats[new_name] = st.session_state.chats.pop(current_name) st.session_state.active_chat = new_name st.rerun() # ========================================== # FEATURE 3: ADD RECORD TO SQL DATABASE # ========================================== st.title("🗄️ Database Management") with st.expander("➕ Add New Record to SQL Database", expanded=False): with st.form("sql_add_form", clear_on_submit=True): st.write("Enter the details below to add a record directly to the database:") med_name = st.text_input("Medicine Name") dosage = st.text_input("Dosage (e.g., 500mg)") stock = st.number_input("Stock Quantity", min_value=0, step=1) submit_button = st.form_submit_button(label="Add Record") if submit_button: if med_name and dosage: try: add_sql_record(med_name, dosage, stock) st.success(f"Successfully added '{med_name}' to the database!") except Exception as e: st.error(f"Failed to write to database: {e}") else: st.warning("Please fill in all mandatory fields.") # ========================================== # FEATURE 4: CONVERSATIONAL CHAT BOT (WITH PDF FORMATTING) # ========================================== st.title(f"🤖 {st.session_state.active_chat}") # Display current conversation history for msg in st.session_state.chats[st.session_state.active_chat]: st.chat_message(msg["role"]).write(msg["content"]) # Target PDF report template enforced via system instructions PDF_FORMAT_PROMPT = """ [SYSTEM INSTRUCTION] You must format your entire response to mimic an official PDF Medical/Pharmaceutical Report. Structure all responses utilizing Markdown with the exact sections below: # PHARMACEUTICAL ASSESSMENT REPORT **Document Ref:** PHARMA-GPT-2026 **Status:** FINAL --- ### 1. EXECUTIVE SUMMARY [Provide a concise overview here] ### 2. DETAILED ANALYSIS & FINDINGS [Provide structured detailed items here. Use tables where applicable] ### 3. RECOMMENDATIONS & NEXT STEPS - **Short-term Action:** [Detail item] - **Long-term Strategy:** [Detail item] --- *Confidentiality Notice: This output conforms to the standard automated PDF reporting layout.* """ if user_query := st.chat_input(): # Save user message st.session_state.chats[st.session_state.active_chat].append({"role": "user", "content": user_query}) st.chat_message("user").write(user_query) # Simulate LLM Response generation (Connect this to your actual LLM pipeline) # Ensure you pass PDF_FORMAT_PROMPT along with user_query to your model context simulated_llm_response = f"""# PHARMACEUTICAL ASSESSMENT REPORT **Document Ref:** PHARMA-GPT-2026 **Status:** FINAL --- ### 1. EXECUTIVE SUMMARY Regarding your query on '{user_query}', this assessment covers clinical observations and compliance parameters. ### 2. DETAILED ANALYSIS & FINDINGS | Parameter | Status | Notes | | :--- | :--- | :--- | | Query Focus | Evaluated | Subject investigated fully. | | Compliance | Verified | Meets strict documentation parameters. | ### 3. RECOMMENDATIONS & NEXT STEPS - **Short-term Action:** Review the raw log output. - **Long-term Strategy:** Automate recurring reporting cycles. --- *Confidentiality Notice: This output conforms to the standard automated PDF reporting layout.*""" # Save and display assistant response st.session_state.chats[st.session_state.active_chat].append({"role": "assistant", "content": simulated_llm_response}) st.chat_message("assistant").write(simulated_llm_response)