import streamlit as st import requests import uuid import os import time from dotenv import load_dotenv # --- CONFIGURATION --- load_dotenv() API_BASE_URL = os.getenv("MINDNET_API_URL", "http://localhost:8002") CHAT_ENDPOINT = f"{API_BASE_URL}/chat" FEEDBACK_ENDPOINT = f"{API_BASE_URL}/feedback" # Timeout-Strategie timeout_setting = os.getenv("MINDNET_API_TIMEOUT") or os.getenv("MINDNET_LLM_TIMEOUT") API_TIMEOUT = float(timeout_setting) if timeout_setting else 300.0 # --- PAGE SETUP --- st.set_page_config( page_title="mindnet v2.3.1", page_icon="🧠", layout="centered" ) st.markdown(""" """, unsafe_allow_html=True) # --- SESSION STATE --- if "messages" not in st.session_state: st.session_state.messages = [] if "user_id" not in st.session_state: st.session_state.user_id = str(uuid.uuid4()) # --- API FUNCTIONS --- def send_chat_message(message: str, top_k: int, explain: bool): payload = {"message": message, "top_k": top_k, "explain": explain} try: response = requests.post(CHAT_ENDPOINT, json=payload, timeout=API_TIMEOUT) response.raise_for_status() return response.json() except requests.exceptions.ReadTimeout: return {"error": f"Timeout ({int(API_TIMEOUT)}s). Das lokale LLM rechnet noch."} except Exception as e: return {"error": str(e)} def submit_feedback(query_id: str, node_id: str, score: int, comment: str = None): """Sendet Feedback asynchron.""" payload = { "query_id": query_id, "node_id": node_id, "score": score, "comment": comment } try: requests.post(FEEDBACK_ENDPOINT, json=payload, timeout=5) # Wir nutzen st.toast für dezentes Feedback ohne Rerun target = "Antwort" if node_id == "generated_answer" else "Quelle" st.toast(f"Feedback für {target} gespeichert! (Score: {score})") except Exception as e: st.error(f"Feedback-Fehler: {e}") # --- UI COMPONENTS --- def render_sidebar(): with st.sidebar: st.header("⚙️ Konfiguration") st.caption(f"Backend: `{API_BASE_URL}`") st.subheader("Retrieval") top_k = st.slider("Quellen Anzahl", 1, 10, 5) explain_mode = st.toggle("Explanation Layer", value=True) st.divider() st.info("WP-10: Advanced Feedback Loop Active") if st.button("Reset Chat"): st.session_state.messages = [] st.rerun() return top_k, explain_mode def render_intent_badge(intent, source): icon = "🧠" if intent == "EMPATHY": icon = "❤️" elif intent == "DECISION": icon = "⚖️" elif intent == "CODING": icon = "💻" elif intent == "FACT": icon = "📚" return f"""
{icon} Intent: {intent} ({source})
""" def render_sources(sources, query_id): """ Rendert Quellen inklusive granularem Feedback-Mechanismus. """ if not sources: return st.markdown("#### 📚 Verwendete Quellen") for idx, hit in enumerate(sources): score = hit.get('total_score', 0) node_id = hit.get('node_id') title = hit.get('note_id', 'Unbekannt') payload = hit.get('payload', {}) note_type = payload.get('type', 'unknown') # Icon basierend auf Score score_icon = "🟢" if score > 0.8 else "🟡" if score > 0.5 else "⚪" expander_title = f"{score_icon} {title} (Typ: {note_type}, Score: {score:.2f})" with st.expander(expander_title): # 1. Inhalt text = hit.get('source', {}).get('text', 'Kein Text') st.markdown(f"_{text[:300]}..._") # 2. Explanation (Why-Layer) if 'explanation' in hit and hit['explanation']: st.caption("**Warum gefunden?**") for r in hit['explanation'].get('reasons', []): st.caption(f"- {r.get('message')}") # 3. Granulares Feedback (Source Level) st.markdown("---") c1, c2 = st.columns([3, 1]) with c1: st.caption("War diese Quelle hilfreich für die Antwort?") with c2: # Callback Wrapper für Source-Feedback def on_source_fb(qid=query_id, nid=node_id, k=f"fb_src_{node_id}"): val = st.session_state.get(k) # Mapping: Thumbs Up (1) -> Score 5, Thumbs Down (0) -> Score 1 mapped_score = 5 if val == 1 else 1 submit_feedback(qid, nid, mapped_score, comment="Source Feedback via UI") st.feedback( "thumbs", key=f"fb_src_{query_id}_{node_id}", # Unique Key pro Query/Node on_change=on_source_fb, kwargs={"qid": query_id, "nid": node_id, "k": f"fb_src_{query_id}_{node_id}"} ) # --- MAIN APP --- top_k, show_explain = render_sidebar() st.title("mindnet v2.3.1") # 1. Chat History Rendern for msg in st.session_state.messages: with st.chat_message(msg["role"]): if msg["role"] == "assistant": # Meta-Daten if "intent" in msg: st.markdown(render_intent_badge(msg["intent"], msg.get("intent_source", "?")), unsafe_allow_html=True) # Antwort-Text st.markdown(msg["content"]) # Quellen (mit Feedback-Option, aber Status ist readonly für alte Nachrichten in Streamlit oft schwierig, # daher rendern wir Feedback-Controls idealerweise nur für die letzte Nachricht oder speichern Status) # In dieser Version rendern wir sie immer, Streamlit State managed das. if "sources" in msg: render_sources(msg["sources"], msg["query_id"]) # Globales Feedback (Sterne) qid = msg["query_id"] def on_global_fb(q=qid, k=f"fb_glob_{qid}"): val = st.session_state.get(k) # Liefert 0-4 if val is not None: submit_feedback(q, "generated_answer", val + 1, comment="Global Star Rating") st.caption("Wie gut war diese Antwort?") st.feedback( "stars", key=f"fb_glob_{qid}", on_change=on_global_fb ) else: st.markdown(msg["content"]) # 2. User Input if prompt := st.chat_input("Deine Frage an das System..."): # User Message anzeigen st.session_state.messages.append({"role": "user", "content": prompt}) with st.chat_message("user"): st.markdown(prompt) # API Call with st.chat_message("assistant"): with st.spinner("Thinking..."): resp = send_chat_message(prompt, top_k, show_explain) if "error" in resp: st.error(resp["error"]) else: # Daten extrahieren answer = resp.get("answer", "") intent = resp.get("intent", "FACT") source = resp.get("intent_source", "Unknown") query_id = resp.get("query_id") hits = resp.get("sources", []) # Sofort rendern (damit User nicht auf Rerun warten muss) st.markdown(render_intent_badge(intent, source), unsafe_allow_html=True) st.markdown(answer) render_sources(hits, query_id) # Feedback Slot für die NEUE Nachricht vorbereiten st.caption("Wie gut war diese Antwort?") st.feedback("stars", key=f"fb_glob_{query_id}", on_change=lambda: submit_feedback(query_id, "generated_answer", st.session_state[f"fb_glob_{query_id}"] + 1)) # In History speichern st.session_state.messages.append({ "role": "assistant", "content": answer, "intent": intent, "intent_source": source, "sources": hits, "query_id": query_id })