Spaces:
Sleeping
Sleeping
Update app.py
Browse files185 unmodified lines186187188189190191192193194195196197231 unmodified lines429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581185 unmodified linesdef configure_page():"""Configure Streamlit page settings."""config = st.session_state.configpage_title = config.get("ui.page_title", "π¬ ProfillyBot")page_icon = config.get("ui.page_icon", "π€")layout = config.get("ui.layout", "centered")st.set_page_config(page_title=page_title, page_icon=page_icon, layout=layout)231 unmodified linesdef display_chat_messages():"""Display chat messages."""config = st.session_state.configshow_timestamps = config.get("ui.show_timestamps", True)for message in st.session_state.messages:with st.chat_message(message["role"]):st.markdown(message["content"])# Display timestamp if enabledif show_timestamps and "timestamp" in message:st.caption(f"_{message['timestamp']}_")# Display sources if availableif "sources" in message and message["sources"]:with st.expander("π Sources"):st.markdown(message["sources"])def process_user_input(prompt: str):"""Process user input and generate response.Args:prompt: User's question"""config = st.session_state.configrag_pipeline = st.session_state.rag_pipeline# Add user messagetimestamp = datetime.now().strftime("%H:%M:%S")st.session_state.messages.append({"role": "user", "content": prompt, "timestamp": timestamp})# Display user messagewith st.chat_message("user"):st.markdown(prompt)if config.get("ui.show_timestamps", True):st.caption(f"_{timestamp}_")# Extract and prepare chat historychat_history = []if config.get("chat.enable_history", True):# Extract history excluding the current message we just addedraw_history = extract_chat_history(st.session_state.messages, exclude_last=True)# Truncate based on configurationmax_turns = config.get("chat.max_history_turns", 10)max_tokens = config.get("chat.max_history_tokens", 2000)chat_history = truncate_chat_history(raw_history,max_turns=max_turns if max_turns > 0 else None,max_tokens=max_tokens if max_tokens > 0 else None,)if chat_history:logger.debug(f"Including {len(chat_history)} messages from chat history")# Generate streaming responsewith st.chat_message("assistant"):try:# Create placeholder for streaming contentresponse_placeholder = st.empty()# Stream the response token by token with spinnerstreamed_content = ""with st.spinner("Thinking (this may take a few minutes on a free-tier HF space)..."):for chunk in rag_pipeline.stream_answer(prompt, chat_history=chat_history):streamed_content += chunkresponse_placeholder.markdown(streamed_content + "β")# Remove cursor and show final streamed contentresponse_placeholder.markdown(streamed_content)# Enhance the response for better tone (post-stream enhancement)answer = streamed_contentif config.get("rag.enhance_responses", True):from src.response_enhancer import get_response_enhancerenhancer = get_response_enhancer()enhanced_answer = enhancer.enhance_with_context(streamed_content, prompt)if enhanced_answer != streamed_content:answer = enhanced_answer# Update display with enhanced versionresponse_placeholder.markdown(answer)logger.debug("Response enhanced for better tone")# Get source documents (after streaming completes)sources = rag_pipeline.get_source_documents(prompt, chat_history=chat_history)sources_text = ""if config.get("rag.include_sources", True) and sources:sources_text = rag_pipeline.format_sources(sources)with st.expander("π Sources"):st.markdown(sources_text)# Add to message historytimestamp = datetime.now().strftime("%H:%M:%S")st.session_state.messages.append({"role": "assistant","content": answer,"timestamp": timestamp,"sources": sources_text,})except Exception as e:error_msg = f"I apologize, but I encountered an error: {e}"st.error(error_msg)logger.error(f"Error generating response: {e}", exc_info=True)st.session_state.messages.append({"role": "assistant", "content": error_msg, "timestamp": timestamp})def main():"""Main application entry point."""# Initialize session stateinit_session_state()# Load configurationload_config()# Configure pageconfigure_page()# Load RAG pipelineload_rag_pipeline()# Display UIdisplay_header()display_sidebar()# Display chat messagesdisplay_chat_messages()# Process pending question from example button clickif st.session_state.pending_question:pending = st.session_state.pending_questionst.session_state.pending_question = Noneprocess_user_input(pending)st.rerun()# Chat inputif prompt := st.chat_input("Ask me anything about the profile..."):process_user_input(prompt)# Limit chat historymax_history = st.session_state.config.get("ui.max_chat_history", 50)if len(st.session_state.messages) > max_history:st.session_state.messages = st.session_state.messages[-max_history:]185 unmodified lines186187188189190191192193194195196197198199200231 unmodified lines432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615185 unmodified linesdef configure_page():"""Configure Streamlit page settings (must run before other st.* calls)."""# Defaults first so set_page_config can run even if config is not readypage_title = "π¬ ProfillyBot"page_icon = "π€"layout = "centered"if st.session_state.config is not None:page_title = st.session_state.config.get("ui.page_title", page_title)page_icon = st.session_state.config.get("ui.page_icon", page_icon)layout = st.session_state.config.get("ui.layout", layout)st.set_page_config(page_title=page_title, page_icon=page_icon, layout=layout)231 unmodified linesdef display_chat_messages():"""Render conversation history with Streamlit chat elements.Uses ``st.chat_message`` containers as documented at:https://docs.streamlit.io/develop/api-reference/chat"""config = st.session_state.configshow_timestamps = config.get("ui.show_timestamps", True)for message in st.session_state.messages:role = message["role"]avatar = "π§βπ»" if role == "user" else "π€"with st.chat_message(role, avatar=avatar):st.markdown(message["content"])if show_timestamps and message.get("timestamp"):st.caption(f"_{message['timestamp']}_")if message.get("sources"):with st.expander("π Sources"):st.markdown(message["sources"])if message.get("retrieval_panel"):with st.expander("π Retrieval (query + chunks)", expanded=False):st.markdown(message["retrieval_panel"])def _prepare_chat_history(config) -> list[dict]:"""Build truncated prior-turn history for the RAG pipeline."""if not config.get("chat.enable_history", True):return []raw_history = extract_chat_history(st.session_state.messages, exclude_last=True)max_turns = config.get("chat.max_history_turns", 10)max_tokens = config.get("chat.max_history_tokens", 2000)chat_history = truncate_chat_history(raw_history,max_turns=max_turns if max_turns > 0 else None,max_tokens=max_tokens if max_tokens > 0 else None,)if chat_history:logger.debug("Including %s messages from chat history", len(chat_history))return chat_historydef process_user_input(prompt: str):"""Handle a user prompt with ``st.chat_message`` + ``st.write_stream``.Args:prompt: User's question"""config = st.session_state.configrag_pipeline = st.session_state.rag_pipelinetimestamp = datetime.now().strftime("%H:%M:%S")# 1) Persist + show user turnst.session_state.messages.append({"role": "user", "content": prompt, "timestamp": timestamp})with st.chat_message("user", avatar="π§βπ»"):st.markdown(prompt)if config.get("ui.show_timestamps", True):st.caption(f"_{timestamp}_")chat_history = _prepare_chat_history(config)# 2) Stream assistant reply into a chat_message containerwith st.chat_message("assistant", avatar="π€"):try:# Retrieve once, then stream the answersources = []retrieval_panel = ""if config.get("rag.include_sources", True) or config.get("rag.show_retrieval_panel", True):sources = rag_pipeline.get_source_documents(prompt, chat_history=chat_history)if config.get("rag.show_retrieval_panel", True):retrieval_panel = rag_pipeline.format_retrieval_panel(prompt, sources=sources)with st.expander("π Retrieval (query + chunks)", expanded=True):st.markdown(retrieval_panel)streamed_content = st.write_stream(rag_pipeline.stream_answer(prompt, chat_history=chat_history))if streamed_content is None:streamed_content = ""elif not isinstance(streamed_content, str):streamed_content = str(streamed_content)# Keep the streamed UI as-is; persist an enhanced copy in history if enabledanswer = streamed_contentif config.get("rag.enhance_responses", True) and streamed_content:from src.response_enhancer import get_response_enhancerenhancer = get_response_enhancer()enhanced = enhancer.enhance_with_context(streamed_content, prompt)if enhanced != streamed_content:answer = enhancedlogger.debug("Response enhanced for better tone (stored in history)")sources_text = ""if config.get("rag.include_sources", True) and sources:sources_text = rag_pipeline.format_sources(sources)with st.expander("π Sources"):st.markdown(sources_text)st.session_state.messages.append({"role": "assistant","content": answer,"timestamp": datetime.now().strftime("%H:%M:%S"),"sources": sources_text,"retrieval_panel": retrieval_panel,})except Exception as e:error_msg = f"I apologize, but I encountered an error: {e}"st.error(error_msg)logger.error("Error generating response: %s", e, exc_info=True)st.session_state.messages.append({"role": "assistant","content": error_msg,"timestamp": timestamp,})def main():"""Main application entry point."""init_session_state()# set_page_config must be the first Streamlit commandconfigure_page()load_config()# Re-apply title from config if needed is already handled via defaults aboveload_rag_pipeline()display_header()display_sidebar()# Conversation history (st.chat_message)display_chat_messages()# Example-question buttons inject into the same chat flowif st.session_state.pending_question:pending = st.session_state.pending_questionst.session_state.pending_question = Noneprocess_user_input(pending)st.rerun()# Pinned chat composer (st.chat_input)# https://docs.streamlit.io/develop/api-reference/chat/st.chat_inputchat_input_kwargs = {"key": "profilly_chat_input","max_chars": 4000,}# submit_mode is available on newer Streamlit versionstry:prompt = st.chat_input("Ask me anything about the profile...",submit_mode="disable",**chat_input_kwargs,)except TypeError:prompt = st.chat_input("Ask me anything about the profile...",**chat_input_kwargs,)if prompt:# Newer Streamlit may return a dict-like object when files/audio are enabledif not isinstance(prompt, str):prompt = getattr(prompt, "text", None) or str(prompt)if prompt:process_user_input(prompt)max_history = st.session_state.config.get("ui.max_chat_history", 50)if len(st.session_state.messages) > max_history:st.session_state.messages = st.session_state.messages[-max_history:]
app.py+115-81