""" streamlit_app.py ---------------- Beautiful Streamlit GUI for the Python Q&A Assistant. Talks to the FastAPI backend running at localhost:8000. Run with: streamlit run streamlit_app.py (Make sure the FastAPI server is also running: uvicorn main:app --port 8000) """ import streamlit as st import requests import time from datetime import datetime # ─── Page config (MUST be first Streamlit call) ────────────────────────────── st.set_page_config( page_title="Python Q&A Assistant", page_icon="🐍", layout="wide", initial_sidebar_state="expanded", ) API_BASE = "http://localhost:8000" # ─── Custom CSS ─────────────────────────────────────────────────────────────── st.markdown(""" """, unsafe_allow_html=True) # ─── Session state init ─────────────────────────────────────────────────────── if "history" not in st.session_state: st.session_state.history = [] # list of {question, answer, sources, latency, ts} if "current_question" not in st.session_state: st.session_state.current_question = "" if "api_ok" not in st.session_state: st.session_state.api_ok = False # ─── Helper: call API ───────────────────────────────────────────────────────── def ask_api(question: str) -> dict | None: try: t0 = time.time() resp = requests.post( f"{API_BASE}/ask", json={"question": question}, timeout=60, ) elapsed = time.time() - t0 if resp.status_code == 200: data = resp.json() data["latency"] = round(elapsed, 2) return data else: st.error(f"API error {resp.status_code}: {resp.text}") return None except requests.exceptions.ConnectionError: st.error("Cannot connect to FastAPI backend. Make sure `uvicorn main:app --port 8000` is running.") return None def check_health() -> dict | None: try: resp = requests.get(f"{API_BASE}/health", timeout=5) if resp.status_code == 200: return resp.json() except Exception: pass return None # ─── Sidebar ────────────────────────────────────────────────────────────────── with st.sidebar: st.markdown("### 🐍 Python Q&A Assistant") st.markdown("---") # Health check health = check_health() if health: st.session_state.api_ok = True st.markdown( f'' f'API Online', unsafe_allow_html=True, ) st.caption(f"📚 {health['index_size']:,} Q&As indexed") st.caption(f"⏱️ Uptime: {health['uptime_seconds']:.0f}s") st.caption(f"🔢 Requests: {health['requests_served']}") else: st.markdown("🔴 API Offline") st.warning("Start the API:\n```\nuvicorn main:app --port 8000\n```") st.markdown("---") st.markdown("#### 💡 Example Questions") EXAMPLES = [ "How do I reverse a list in Python?", "What is a Python decorator?", "How do I handle exceptions in Python?", "What is the difference between list and tuple?", "How do I sort a dictionary by value?", "How do I use *args and **kwargs?", "What does the yield keyword do?", "How do I read a CSV file with pandas?", ] for ex in EXAMPLES: if st.button(ex, key=f"ex_{ex[:20]}"): st.session_state.current_question = ex st.markdown("---") # History if st.session_state.history: st.markdown("#### 🕘 Recent Questions") for i, h in enumerate(reversed(st.session_state.history[-8:])): st.markdown( f'
' f'

{h["question"][:60]}{"..." if len(h["question"]) > 60 else ""}

' f'

{h["ts"]} · {h["latency"]}s

' f'
', unsafe_allow_html=True, ) if st.session_state.history: if st.button("🗑️ Clear History"): st.session_state.history = [] st.rerun() # ─── Main content ───────────────────────────────────────────────────────────── # Hero st.markdown("""

🐍 Python Q&A Assistant

Powered by Stack Overflow data · RAG Pipeline · Groq LLaMA-3.3-70b · 14,864 real Q&A pairs

""", unsafe_allow_html=True) # ─── Question input form ─────────────────────────────────────────────────────── with st.form("question_form", clear_on_submit=False): question = st.text_area( "Ask a Python question", value=st.session_state.current_question, placeholder="e.g. How do I reverse a list in Python? What is a lambda function? How does GIL work?", height=110, label_visibility="collapsed", ) col1, col2, col3 = st.columns([3, 1, 1]) with col1: submitted = st.form_submit_button("🔍 Ask Question", use_container_width=True) with col2: st.form_submit_button("", disabled=True, use_container_width=True) # spacer with col3: pass # ─── Handle submission ──────────────────────────────────────────────────────── if submitted and question.strip(): st.session_state.current_question = question.strip() with st.spinner("🔍 Searching Stack Overflow knowledge base..."): result = ask_api(question.strip()) if result: entry = { "question": question.strip(), "answer": result["answer"], "sources": result.get("sources", []), "latency": result.get("latency", 0), "model": result.get("model", ""), "docs": result.get("docs_retrieved", 5), "ts": datetime.now().strftime("%H:%M"), } st.session_state.history.append(entry) elif submitted and not question.strip(): st.warning("Please type a question first!") # ─── Display latest answer ──────────────────────────────────────────────────── if st.session_state.history: latest = st.session_state.history[-1] st.markdown("---") # Question bubble st.markdown( f"""
{latest['question']}
""", unsafe_allow_html=True, ) # Answer card st.markdown('
', unsafe_allow_html=True) # Metrics row sources_html = "".join( f'📎 {s[:55]}{"..." if len(s)>55 else ""}' for s in latest["sources"] ) st.markdown( f"""
⚡ {latest['latency']}s 🤖 {latest['model'].split('-')[0]+'-'+latest['model'].split('-')[1] if '-' in latest['model'] else latest['model']} 📚 {latest['docs']} sources 🕐 {latest['ts']}
""", unsafe_allow_html=True, ) st.markdown("
", unsafe_allow_html=True) # Answer text (rendered as markdown for code highlighting) st.markdown(latest["answer"]) # Sources expander if latest["sources"]: with st.expander("📎 View Stack Overflow Sources", expanded=False): for i, src in enumerate(latest["sources"], 1): st.markdown( f'#{i} {src}', unsafe_allow_html=True, ) st.markdown("
", unsafe_allow_html=True) # ── Previous Q&As ────────────────────────────────────────────────────────── if len(st.session_state.history) > 1: st.markdown("
", unsafe_allow_html=True) st.markdown("#### 📜 Previous Answers") for h in reversed(st.session_state.history[:-1]): with st.expander(f"Q: {h['question'][:80]}... ({h['ts']} · {h['latency']}s)"): st.markdown(h["answer"]) if h["sources"]: srcs = " ".join( f'📎 {s[:50]}' for s in h["sources"] ) st.markdown(srcs, unsafe_allow_html=True) else: # Empty state st.markdown("
", unsafe_allow_html=True) col1, col2, col3 = st.columns(3) cards = [ ("🔍", "RAG Powered", "Retrieves real Stack Overflow answers as context before generating"), ("⚡", "Groq LLaMA 3.3", "Blazing fast inference with the best open-source LLM"), ("📚", "14,864 Q&As", "Indexed from 607K Python Stack Overflow questions"), ] for col, (icon, title, desc) in zip([col1, col2, col3], cards): with col: st.markdown( f"""
{icon}
{title}
{desc}
""", unsafe_allow_html=True, )