Spaces:
Sleeping
Sleeping
Upload 8 files
Browse files- Dockerfile +6 -0
- chroma_db.zip +3 -0
- ingest.py +108 -0
- main.py +155 -0
- preprocess.py +121 -0
- rag_chain.py +128 -0
- requirements.txt +123 -0
- streamlit_app.py +507 -0
Dockerfile
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.9
|
| 2 |
+
WORKDIR /code
|
| 3 |
+
COPY ./requirements.txt /code/requirements.txt
|
| 4 |
+
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
|
| 5 |
+
COPY . /code
|
| 6 |
+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
chroma_db.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f3be189cdbc1a367cfef879c6057fbfa55304880f61c759df5f3780d66e12f6c
|
| 3 |
+
size 96126338
|
ingest.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ingest.py
|
| 3 |
+
---------
|
| 4 |
+
Step 2: Embed Q&A pairs with sentence-transformers β store in ChromaDB.
|
| 5 |
+
Output: chroma_db/ (vector index - commit this folder to GitHub!)
|
| 6 |
+
|
| 7 |
+
Run once locally after preprocess.py:
|
| 8 |
+
python ingest.py
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import pandas as pd
|
| 12 |
+
import chromadb
|
| 13 |
+
from chromadb.config import Settings
|
| 14 |
+
from sentence_transformers import SentenceTransformer
|
| 15 |
+
from tqdm import tqdm
|
| 16 |
+
import os
|
| 17 |
+
import sys
|
| 18 |
+
|
| 19 |
+
PARQUET_PATH = "data/clean_qa.parquet"
|
| 20 |
+
CHROMA_PATH = "chroma_db"
|
| 21 |
+
COLLECTION = "python_qa"
|
| 22 |
+
BATCH_SIZE = 128
|
| 23 |
+
MODEL_NAME = "all-MiniLM-L6-v2" # ~90MB, downloads once, very fast at inference
|
| 24 |
+
|
| 25 |
+
# βββ Guard: skip if already ingested βββββββββββββββββββββββββββββββββββββββββ
|
| 26 |
+
if os.path.exists(CHROMA_PATH) and os.listdir(CHROMA_PATH):
|
| 27 |
+
print(f"β
ChromaDB already exists at '{CHROMA_PATH}'. Skipping ingestion.")
|
| 28 |
+
print(" Delete the folder and re-run to re-index.")
|
| 29 |
+
sys.exit(0)
|
| 30 |
+
|
| 31 |
+
# βββ Load data ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 32 |
+
if not os.path.exists(PARQUET_PATH):
|
| 33 |
+
print("β data/clean_qa.parquet not found. Run preprocess.py first.")
|
| 34 |
+
sys.exit(1)
|
| 35 |
+
|
| 36 |
+
print(f"π Loading {PARQUET_PATH}...")
|
| 37 |
+
df = pd.read_parquet(PARQUET_PATH)
|
| 38 |
+
print(f" β
{len(df):,} Q&A pairs loaded")
|
| 39 |
+
|
| 40 |
+
# βββ Build the document string that will be embedded βββββββββββββββββββββββββ
|
| 41 |
+
# Format: "Q: <title>\n<question_body>\nA: <answer_body>"
|
| 42 |
+
# We cap lengths so single docs don't blow up memory
|
| 43 |
+
df["document"] = df.apply(
|
| 44 |
+
lambda r: (
|
| 45 |
+
f"Q: {r['title']}\n"
|
| 46 |
+
f"{str(r['question_body'])[:600]}\n\n"
|
| 47 |
+
f"A: {str(r['answer_body'])[:900]}"
|
| 48 |
+
),
|
| 49 |
+
axis=1,
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
# βββ Load embedding model βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 53 |
+
print(f"\nπ€ Loading embedding model '{MODEL_NAME}'...")
|
| 54 |
+
print(" (Downloads ~90MB on first run, cached afterwards)")
|
| 55 |
+
model = SentenceTransformer(MODEL_NAME)
|
| 56 |
+
print(" β
Model ready")
|
| 57 |
+
|
| 58 |
+
# βββ Setup ChromaDB βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 59 |
+
print(f"\n Setting up ChromaDB at '{CHROMA_PATH}'...")
|
| 60 |
+
client = chromadb.PersistentClient(
|
| 61 |
+
path=CHROMA_PATH,
|
| 62 |
+
settings=Settings(anonymized_telemetry=False)
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
# Fresh collection
|
| 66 |
+
try:
|
| 67 |
+
client.delete_collection(COLLECTION)
|
| 68 |
+
except Exception:
|
| 69 |
+
pass
|
| 70 |
+
|
| 71 |
+
collection = client.create_collection(
|
| 72 |
+
name=COLLECTION,
|
| 73 |
+
metadata={"hnsw:space": "cosine"}, # cosine similarity for semantic search
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
# βββ Embed & Index in batches βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 77 |
+
print(f"\nβοΈ Embedding and indexing {len(df):,} documents (batch={BATCH_SIZE})...")
|
| 78 |
+
print(" This takes ~5-15 minutes on CPU. Grab a coffee β")
|
| 79 |
+
|
| 80 |
+
total_indexed = 0
|
| 81 |
+
for i in tqdm(range(0, len(df), BATCH_SIZE), desc="Indexing"):
|
| 82 |
+
batch = df.iloc[i : i + BATCH_SIZE]
|
| 83 |
+
|
| 84 |
+
docs = batch["document"].tolist()
|
| 85 |
+
ids = [str(qid) for qid in batch["question_id"].tolist()]
|
| 86 |
+
metas = [
|
| 87 |
+
{
|
| 88 |
+
"title": str(row["title"])[:200],
|
| 89 |
+
"question_score": int(row["question_score"]),
|
| 90 |
+
"answer_score": int(row["answer_score"]),
|
| 91 |
+
}
|
| 92 |
+
for _, row in batch.iterrows()
|
| 93 |
+
]
|
| 94 |
+
|
| 95 |
+
embeddings = model.encode(docs, show_progress_bar=False).tolist()
|
| 96 |
+
|
| 97 |
+
collection.add(
|
| 98 |
+
documents=docs,
|
| 99 |
+
embeddings=embeddings,
|
| 100 |
+
ids=ids,
|
| 101 |
+
metadatas=metas,
|
| 102 |
+
)
|
| 103 |
+
total_indexed += len(batch)
|
| 104 |
+
|
| 105 |
+
print(f"\nβ
Done! Indexed {collection.count():,} documents into ChromaDB")
|
| 106 |
+
print(f" Folder: {os.path.abspath(CHROMA_PATH)}")
|
| 107 |
+
print("\nπ Next step: commit the 'chroma_db/' folder to your GitHub repo")
|
| 108 |
+
print(" Then deploy to Render β no re-indexing needed!")
|
main.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
main.py
|
| 3 |
+
-------
|
| 4 |
+
FastAPI application β the public-facing API.
|
| 5 |
+
|
| 6 |
+
Endpoints:
|
| 7 |
+
GET / β API info
|
| 8 |
+
GET /health β health check (required by assessment)
|
| 9 |
+
POST /ask β ask a Python question (required by assessment)
|
| 10 |
+
|
| 11 |
+
Run locally:
|
| 12 |
+
uvicorn main:app --reload --port 8000
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import time
|
| 16 |
+
import os
|
| 17 |
+
import zipfile
|
| 18 |
+
from contextlib import asynccontextmanager
|
| 19 |
+
from typing import List
|
| 20 |
+
|
| 21 |
+
from fastapi import FastAPI, HTTPException, Request
|
| 22 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 23 |
+
from pydantic import BaseModel, Field
|
| 24 |
+
|
| 25 |
+
import rag_chain # Importing this triggers model/DB load at startup
|
| 26 |
+
|
| 27 |
+
# βββ App state ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 28 |
+
_state: dict = {}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@asynccontextmanager
|
| 32 |
+
async def lifespan(app: FastAPI):
|
| 33 |
+
"""Startup and shutdown events."""
|
| 34 |
+
print("π Starting Python Q&A Assistant...")
|
| 35 |
+
_state["start_time"] = time.time()
|
| 36 |
+
_state["request_count"] = 0
|
| 37 |
+
yield
|
| 38 |
+
print("π Shutting down.")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# βββ FastAPI app ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 42 |
+
app = FastAPI(
|
| 43 |
+
title="Python Q&A Assistant",
|
| 44 |
+
description=(
|
| 45 |
+
"AI-powered Python programming Q&A backed by real Stack Overflow data. "
|
| 46 |
+
"Uses a RAG pipeline: sentence-transformers + ChromaDB + Groq LLaMA-3.3-70b."
|
| 47 |
+
),
|
| 48 |
+
version="1.0.0",
|
| 49 |
+
lifespan=lifespan,
|
| 50 |
+
docs_url="/docs",
|
| 51 |
+
redoc_url="/redoc",
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
app.add_middleware(
|
| 55 |
+
CORSMiddleware,
|
| 56 |
+
allow_origins=["*"],
|
| 57 |
+
allow_methods=["*"],
|
| 58 |
+
allow_headers=["*"],
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# βββ Schemas ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 63 |
+
class QuestionRequest(BaseModel):
|
| 64 |
+
question: str = Field(
|
| 65 |
+
...,
|
| 66 |
+
min_length=5,
|
| 67 |
+
max_length=1000,
|
| 68 |
+
example="How do I reverse a list in Python?",
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class AnswerResponse(BaseModel):
|
| 73 |
+
question: str
|
| 74 |
+
answer: str
|
| 75 |
+
sources: List[str] = Field(description="Stack Overflow question titles used as context")
|
| 76 |
+
model: str = Field(description="LLM model used to generate the answer")
|
| 77 |
+
docs_retrieved: int = Field(description="Number of SO documents retrieved as context")
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class HealthResponse(BaseModel):
|
| 81 |
+
status: str
|
| 82 |
+
uptime_seconds: float
|
| 83 |
+
requests_served: int
|
| 84 |
+
index_size: int
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
# βββ Middleware: count requests βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 88 |
+
@app.middleware("http")
|
| 89 |
+
async def count_requests(request: Request, call_next):
|
| 90 |
+
_state["request_count"] = _state.get("request_count", 0) + 1
|
| 91 |
+
return await call_next(request)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# βββ Endpoints ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 95 |
+
@app.get("/", tags=["Info"])
|
| 96 |
+
def root():
|
| 97 |
+
"""API overview."""
|
| 98 |
+
return {
|
| 99 |
+
"name": "Python Q&A Assistant",
|
| 100 |
+
"description": "Ask any Python programming question and get answers grounded in Stack Overflow data.",
|
| 101 |
+
"version": "1.0.0",
|
| 102 |
+
"endpoints": {
|
| 103 |
+
"POST /ask": "Ask a Python question",
|
| 104 |
+
"GET /health": "Health check",
|
| 105 |
+
"GET /docs": "Interactive Swagger docs",
|
| 106 |
+
},
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@app.get("/health", response_model=HealthResponse, tags=["Health"])
|
| 111 |
+
def health():
|
| 112 |
+
"""
|
| 113 |
+
Health check endpoint.
|
| 114 |
+
Returns API status, uptime, request count, and index size.
|
| 115 |
+
"""
|
| 116 |
+
uptime = time.time() - _state.get("start_time", time.time())
|
| 117 |
+
try:
|
| 118 |
+
index_size = rag_chain._collection.count()
|
| 119 |
+
except Exception:
|
| 120 |
+
index_size = -1
|
| 121 |
+
|
| 122 |
+
return HealthResponse(
|
| 123 |
+
status="ok",
|
| 124 |
+
uptime_seconds=round(uptime, 2),
|
| 125 |
+
requests_served=_state.get("request_count", 0),
|
| 126 |
+
index_size=index_size,
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
@app.post("/ask", response_model=AnswerResponse, tags=["Q&A"])
|
| 131 |
+
def ask(request: QuestionRequest):
|
| 132 |
+
"""
|
| 133 |
+
Ask a Python programming question.
|
| 134 |
+
|
| 135 |
+
The system will:
|
| 136 |
+
1. Embed your question using sentence-transformers
|
| 137 |
+
2. Retrieve the 5 most relevant Stack Overflow Q&As
|
| 138 |
+
3. Feed them as context to Groq LLaMA-3.3-70b
|
| 139 |
+
4. Return a grounded, accurate answer
|
| 140 |
+
|
| 141 |
+
**Example:**
|
| 142 |
+
```json
|
| 143 |
+
{ "question": "How do I read a CSV file with pandas?" }
|
| 144 |
+
```
|
| 145 |
+
"""
|
| 146 |
+
q = request.question.strip()
|
| 147 |
+
if not q:
|
| 148 |
+
raise HTTPException(status_code=400, detail="Question cannot be empty.")
|
| 149 |
+
|
| 150 |
+
try:
|
| 151 |
+
result = rag_chain.get_answer(q)
|
| 152 |
+
except Exception as e:
|
| 153 |
+
raise HTTPException(status_code=500, detail=f"RAG pipeline error: {str(e)}")
|
| 154 |
+
|
| 155 |
+
return AnswerResponse(**result)
|
preprocess.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
preprocess.py
|
| 3 |
+
-------------
|
| 4 |
+
Step 1: Filter Python-tagged questions, join best answers, clean HTML.
|
| 5 |
+
Output: data/clean_qa.parquet (~15K top-scored Python Q&A pairs)
|
| 6 |
+
|
| 7 |
+
Run once locally before ingesting:
|
| 8 |
+
python preprocess.py
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import pandas as pd
|
| 12 |
+
from bs4 import BeautifulSoup
|
| 13 |
+
import re
|
| 14 |
+
import os
|
| 15 |
+
|
| 16 |
+
DATASET_PATH = "dataset/archive"
|
| 17 |
+
OUTPUT_PATH = "data/clean_qa.parquet"
|
| 18 |
+
TOP_N = 15000 # Keep top N questions by score (keeps file sizes manageable)
|
| 19 |
+
|
| 20 |
+
# βββ 1. Load Tags β get Python question IDs ββββββββββββββββββββββββββββββββββ
|
| 21 |
+
print("π Loading Tags.csv...")
|
| 22 |
+
tags = pd.read_csv(f"{DATASET_PATH}/Tags.csv", encoding="latin-1")
|
| 23 |
+
python_ids = set(tags[tags["Tag"] == "python"]["Id"].tolist())
|
| 24 |
+
print(f" β
{len(python_ids):,} Python-tagged question IDs found")
|
| 25 |
+
|
| 26 |
+
# βββ 2. Load Questions in chunks (file is ~888MB) ββββββββββββββββββββββββββββ
|
| 27 |
+
print("\nπ Loading Questions.csv (chunked, this may take a minute)...")
|
| 28 |
+
q_chunks = []
|
| 29 |
+
for chunk in pd.read_csv(
|
| 30 |
+
f"{DATASET_PATH}/Questions.csv",
|
| 31 |
+
encoding="latin-1",
|
| 32 |
+
chunksize=50_000,
|
| 33 |
+
on_bad_lines="skip",
|
| 34 |
+
):
|
| 35 |
+
filtered = chunk[chunk["Id"].isin(python_ids)]
|
| 36 |
+
if not filtered.empty:
|
| 37 |
+
q_chunks.append(filtered)
|
| 38 |
+
|
| 39 |
+
questions = pd.concat(q_chunks, ignore_index=True)
|
| 40 |
+
print(f" β
{len(questions):,} Python questions loaded")
|
| 41 |
+
|
| 42 |
+
# Keep only top N by vote score
|
| 43 |
+
questions = questions.sort_values("Score", ascending=False).head(TOP_N)
|
| 44 |
+
print(f" β
Trimmed to top {len(questions):,} by score")
|
| 45 |
+
|
| 46 |
+
# βββ 3. Load Answers for only those questions ββββββββββββββββββββββββββββββββ
|
| 47 |
+
print("\nπ Loading Answers.csv (chunked, this may take a minute)...")
|
| 48 |
+
target_ids = set(questions["Id"].tolist())
|
| 49 |
+
a_chunks = []
|
| 50 |
+
for chunk in pd.read_csv(
|
| 51 |
+
f"{DATASET_PATH}/Answers.csv",
|
| 52 |
+
encoding="latin-1",
|
| 53 |
+
chunksize=50_000,
|
| 54 |
+
on_bad_lines="skip",
|
| 55 |
+
):
|
| 56 |
+
filtered = chunk[chunk["ParentId"].isin(target_ids)]
|
| 57 |
+
if not filtered.empty:
|
| 58 |
+
a_chunks.append(filtered)
|
| 59 |
+
|
| 60 |
+
answers = pd.concat(a_chunks, ignore_index=True)
|
| 61 |
+
print(f" β
{len(answers):,} answers loaded")
|
| 62 |
+
|
| 63 |
+
# βββ 4. Pick best answer per question (highest score) ββββββββββββββββββββββββ
|
| 64 |
+
best_answers = (
|
| 65 |
+
answers.sort_values("Score", ascending=False)
|
| 66 |
+
.groupby("ParentId", as_index=False)
|
| 67 |
+
.first()
|
| 68 |
+
)
|
| 69 |
+
best_answers = best_answers.rename(
|
| 70 |
+
columns={"ParentId": "QuestionId", "Body": "AnswerBody", "Score": "AnswerScore"}
|
| 71 |
+
)
|
| 72 |
+
print(f" β
{len(best_answers):,} best answers selected")
|
| 73 |
+
|
| 74 |
+
# βββ 5. Clean HTML ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 75 |
+
def clean_html(html: str) -> str:
|
| 76 |
+
"""Strip HTML tags, preserve code blocks with backtick markers."""
|
| 77 |
+
if pd.isna(html):
|
| 78 |
+
return ""
|
| 79 |
+
soup = BeautifulSoup(str(html), "html.parser")
|
| 80 |
+
# Mark code blocks so they stay readable
|
| 81 |
+
for code in soup.find_all("code"):
|
| 82 |
+
code.string = f"\n```\n{code.get_text()}\n```\n"
|
| 83 |
+
text = soup.get_text(separator=" ")
|
| 84 |
+
text = re.sub(r"\s+", " ", text).strip()
|
| 85 |
+
return text
|
| 86 |
+
|
| 87 |
+
print("\nπ§Ή Cleaning HTML bodies...")
|
| 88 |
+
questions["CleanBody"] = questions["Body"].apply(clean_html)
|
| 89 |
+
best_answers["CleanAnswer"] = best_answers["AnswerBody"].apply(clean_html)
|
| 90 |
+
|
| 91 |
+
# βββ 6. Merge questions + best answers βββββββββββββββββββββββββββββββββββββββ
|
| 92 |
+
merged = questions.merge(
|
| 93 |
+
best_answers[["QuestionId", "CleanAnswer", "AnswerScore"]],
|
| 94 |
+
left_on="Id",
|
| 95 |
+
right_on="QuestionId",
|
| 96 |
+
how="inner",
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
merged = merged[[
|
| 100 |
+
"Id", "Title", "CleanBody", "Score", "CleanAnswer", "AnswerScore"
|
| 101 |
+
]].copy()
|
| 102 |
+
merged.columns = [
|
| 103 |
+
"question_id", "title", "question_body", "question_score",
|
| 104 |
+
"answer_body", "answer_score"
|
| 105 |
+
]
|
| 106 |
+
|
| 107 |
+
# βββ 7. Basic quality filters βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 108 |
+
merged = merged[merged["answer_body"].str.len() > 50]
|
| 109 |
+
merged = merged[merged["question_body"].str.len() > 20]
|
| 110 |
+
merged = merged[merged["title"].str.len() > 5]
|
| 111 |
+
merged = merged.drop_duplicates(subset="question_id")
|
| 112 |
+
|
| 113 |
+
print(f"\nβ
Final dataset: {len(merged):,} Q&A pairs")
|
| 114 |
+
|
| 115 |
+
# βββ 8. Save ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 116 |
+
os.makedirs("data", exist_ok=True)
|
| 117 |
+
merged.to_parquet(OUTPUT_PATH, index=False)
|
| 118 |
+
print(f"πΎ Saved β {OUTPUT_PATH}")
|
| 119 |
+
|
| 120 |
+
print("\nSample row:")
|
| 121 |
+
print(merged.iloc[0][["title", "question_body", "answer_body"]].to_string())
|
rag_chain.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
rag_chain.py
|
| 3 |
+
------------
|
| 4 |
+
Core RAG (Retrieval-Augmented Generation) pipeline.
|
| 5 |
+
Loaded once at startup by main.py β all objects are module-level singletons.
|
| 6 |
+
|
| 7 |
+
Flow:
|
| 8 |
+
User question
|
| 9 |
+
β embed with sentence-transformers
|
| 10 |
+
β query ChromaDB for top-5 similar Q&As
|
| 11 |
+
β build prompt with those Q&As as context
|
| 12 |
+
β call Groq LLaMA-3.3-70b
|
| 13 |
+
β return grounded answer
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import os
|
| 17 |
+
import chromadb
|
| 18 |
+
from chromadb.config import Settings
|
| 19 |
+
from sentence_transformers import SentenceTransformer
|
| 20 |
+
from groq import Groq
|
| 21 |
+
from dotenv import load_dotenv
|
| 22 |
+
|
| 23 |
+
load_dotenv()
|
| 24 |
+
|
| 25 |
+
# βββ Config ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 26 |
+
CHROMA_PATH = os.getenv("CHROMA_PATH", "chroma_db")
|
| 27 |
+
COLLECTION = "python_qa"
|
| 28 |
+
MODEL_NAME = "all-MiniLM-L6-v2"
|
| 29 |
+
GROQ_MODEL = os.getenv("GROQ_MODEL", "llama-3.3-70b-versatile")
|
| 30 |
+
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
| 31 |
+
TOP_K = 5 # How many SO Q&As to retrieve as context
|
| 32 |
+
|
| 33 |
+
if not GROQ_API_KEY:
|
| 34 |
+
raise EnvironmentError("β GROQ_API_KEY not set. Add it to your .env file.")
|
| 35 |
+
|
| 36 |
+
# βββ Load once at module import (not per-request!) βββββββββββββββββββββββββββ
|
| 37 |
+
print(f"π€ Loading embedding model '{MODEL_NAME}'...")
|
| 38 |
+
_embedder = SentenceTransformer(MODEL_NAME)
|
| 39 |
+
|
| 40 |
+
print(f"Connecting to ChromaDB at '{CHROMA_PATH}'...")
|
| 41 |
+
_chroma_client = chromadb.PersistentClient(
|
| 42 |
+
path=CHROMA_PATH,
|
| 43 |
+
settings=Settings(anonymized_telemetry=False)
|
| 44 |
+
)
|
| 45 |
+
_collection = _chroma_client.get_collection(COLLECTION)
|
| 46 |
+
print(f" β
{_collection.count():,} documents in index")
|
| 47 |
+
|
| 48 |
+
print(f"β‘ Initializing Groq client (model: {GROQ_MODEL})...")
|
| 49 |
+
_groq = Groq(api_key=GROQ_API_KEY)
|
| 50 |
+
|
| 51 |
+
# βββ System prompt βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 52 |
+
_SYSTEM_PROMPT = """You are an expert Python programming assistant powered by real Stack Overflow data.
|
| 53 |
+
|
| 54 |
+
Rules:
|
| 55 |
+
1. Answer ONLY based on the Stack Overflow context provided below.
|
| 56 |
+
2. If the context does not fully cover the question, say so briefly, then answer from your knowledge.
|
| 57 |
+
3. Always include working code examples in Python using markdown code blocks (```python ... ```).
|
| 58 |
+
4. Be concise but complete β avoid unnecessary padding.
|
| 59 |
+
5. If multiple approaches exist, list them with trade-offs.
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
# βββ Main function called by FastAPI βββββββββββββββββββββββββββββββββββββββββ
|
| 63 |
+
def get_answer(question: str) -> dict:
|
| 64 |
+
"""
|
| 65 |
+
Parameters
|
| 66 |
+
----------
|
| 67 |
+
question : str β The user's Python question
|
| 68 |
+
|
| 69 |
+
Returns
|
| 70 |
+
-------
|
| 71 |
+
dict with keys: question, answer, sources, model, docs_retrieved
|
| 72 |
+
"""
|
| 73 |
+
# 1οΈβ£ Embed the question
|
| 74 |
+
query_vec = _embedder.encode(question).tolist()
|
| 75 |
+
|
| 76 |
+
# 2οΈβ£ Retrieve top-K similar Q&As from vector DB
|
| 77 |
+
results = _collection.query(
|
| 78 |
+
query_embeddings=[query_vec],
|
| 79 |
+
n_results=TOP_K,
|
| 80 |
+
include=["documents", "metadatas", "distances"],
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
docs = results["documents"][0]
|
| 84 |
+
metas = results["metadatas"][0]
|
| 85 |
+
distances = results["distances"][0]
|
| 86 |
+
|
| 87 |
+
# 3οΈβ£ Build context block from retrieved docs
|
| 88 |
+
context_parts = []
|
| 89 |
+
source_titles = []
|
| 90 |
+
for i, (doc, meta, dist) in enumerate(zip(docs, metas, distances), 1):
|
| 91 |
+
title = meta.get("title", "Unknown")
|
| 92 |
+
score = meta.get("question_score", 0)
|
| 93 |
+
context_parts.append(
|
| 94 |
+
f"--- Stack Overflow Result {i} ---\n"
|
| 95 |
+
f"Title: {title} (votes: {score})\n"
|
| 96 |
+
f"Relevance: {(1 - dist) * 100:.1f}%\n\n"
|
| 97 |
+
f"{doc}"
|
| 98 |
+
)
|
| 99 |
+
source_titles.append(title)
|
| 100 |
+
|
| 101 |
+
context_str = "\n\n".join(context_parts)
|
| 102 |
+
|
| 103 |
+
# 4οΈβ£ Build prompt and call Groq
|
| 104 |
+
user_message = (
|
| 105 |
+
f"Python Question: {question}\n\n"
|
| 106 |
+
f"Stack Overflow Context:\n{context_str}\n\n"
|
| 107 |
+
f"Please answer the question based on the context above."
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
response = _groq.chat.completions.create(
|
| 111 |
+
model=GROQ_MODEL,
|
| 112 |
+
messages=[
|
| 113 |
+
{"role": "system", "content": _SYSTEM_PROMPT},
|
| 114 |
+
{"role": "user", "content": user_message},
|
| 115 |
+
],
|
| 116 |
+
temperature=0.1, # low temp = more factual, deterministic
|
| 117 |
+
max_tokens=1024,
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
answer = response.choices[0].message.content
|
| 121 |
+
|
| 122 |
+
return {
|
| 123 |
+
"question": question,
|
| 124 |
+
"answer": answer,
|
| 125 |
+
"sources": source_titles,
|
| 126 |
+
"model": GROQ_MODEL,
|
| 127 |
+
"docs_retrieved": TOP_K,
|
| 128 |
+
}
|
requirements.txt
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
aiohappyeyeballs==2.6.2
|
| 2 |
+
aiohttp==3.14.1
|
| 3 |
+
aiosignal==1.4.0
|
| 4 |
+
altair==6.2.1
|
| 5 |
+
annotated-doc==0.0.4
|
| 6 |
+
annotated-types==0.7.0
|
| 7 |
+
anyio==4.13.0
|
| 8 |
+
attrs==26.1.0
|
| 9 |
+
bcrypt==5.0.0
|
| 10 |
+
beautifulsoup4==4.15.0
|
| 11 |
+
blinker==1.9.0
|
| 12 |
+
build==1.5.0
|
| 13 |
+
cachetools==7.1.4
|
| 14 |
+
certifi==2026.5.20
|
| 15 |
+
charset-normalizer==3.4.7
|
| 16 |
+
chromadb==1.5.9
|
| 17 |
+
click==8.4.1
|
| 18 |
+
colorama==0.4.6
|
| 19 |
+
distro==1.9.0
|
| 20 |
+
dnspython==2.8.0
|
| 21 |
+
durationpy==0.10
|
| 22 |
+
email-validator==2.3.0
|
| 23 |
+
fastapi
|
| 24 |
+
fastapi-cli==0.0.24
|
| 25 |
+
filelock==3.29.3
|
| 26 |
+
flatbuffers==25.12.19
|
| 27 |
+
frozenlist==1.8.0
|
| 28 |
+
fsspec==2026.4.0
|
| 29 |
+
gitdb==4.0.12
|
| 30 |
+
GitPython==3.1.50
|
| 31 |
+
googleapis-common-protos==1.75.0
|
| 32 |
+
groq==1.4.0
|
| 33 |
+
grpcio==1.81.1
|
| 34 |
+
h11==0.16.0
|
| 35 |
+
hf-xet==1.5.1
|
| 36 |
+
httpcore==1.0.9
|
| 37 |
+
httptools==0.8.0
|
| 38 |
+
httpx==0.28.1
|
| 39 |
+
huggingface_hub==1.19.0
|
| 40 |
+
idna==3.18
|
| 41 |
+
importlib_resources==7.1.0
|
| 42 |
+
itsdangerous==2.2.0
|
| 43 |
+
Jinja2==3.1.6
|
| 44 |
+
joblib==1.5.3
|
| 45 |
+
jsonschema==4.26.0
|
| 46 |
+
jsonschema-specifications==2025.9.1
|
| 47 |
+
kubernetes==36.0.2
|
| 48 |
+
lxml==6.1.1
|
| 49 |
+
markdown-it-py==4.2.0
|
| 50 |
+
MarkupSafe==3.0.3
|
| 51 |
+
mdurl==0.1.2
|
| 52 |
+
mmh3==5.2.1
|
| 53 |
+
mpmath==1.3.0
|
| 54 |
+
multidict==6.7.1
|
| 55 |
+
narwhals==2.22.1
|
| 56 |
+
networkx==3.6.1
|
| 57 |
+
numpy==2.4.6
|
| 58 |
+
oauthlib==3.3.1
|
| 59 |
+
onnxruntime==1.26.0
|
| 60 |
+
opentelemetry-api==1.42.1
|
| 61 |
+
opentelemetry-exporter-otlp-proto-common==1.42.1
|
| 62 |
+
opentelemetry-exporter-otlp-proto-grpc==1.42.1
|
| 63 |
+
opentelemetry-proto==1.42.1
|
| 64 |
+
opentelemetry-sdk==1.42.1
|
| 65 |
+
opentelemetry-semantic-conventions==0.63b1
|
| 66 |
+
orjson==3.11.9
|
| 67 |
+
overrides==7.7.0
|
| 68 |
+
packaging==26.2
|
| 69 |
+
pandas==3.0.3
|
| 70 |
+
pillow==12.2.0
|
| 71 |
+
propcache==0.5.2
|
| 72 |
+
protobuf==6.33.6
|
| 73 |
+
pyarrow==24.0.0
|
| 74 |
+
pybase64==1.4.3
|
| 75 |
+
pydantic==2.13.4
|
| 76 |
+
pydantic-settings==2.14.1
|
| 77 |
+
pydantic_core==2.46.4
|
| 78 |
+
pydeck==0.9.2
|
| 79 |
+
Pygments==2.20.0
|
| 80 |
+
PyPika==0.51.1
|
| 81 |
+
pyproject_hooks==1.2.0
|
| 82 |
+
python-dateutil==2.9.0.post0
|
| 83 |
+
python-dotenv==1.2.2
|
| 84 |
+
python-multipart==0.0.32
|
| 85 |
+
PyYAML==6.0.3
|
| 86 |
+
referencing==0.37.0
|
| 87 |
+
regex==2026.5.9
|
| 88 |
+
requests==2.34.2
|
| 89 |
+
requests-oauthlib==2.0.0
|
| 90 |
+
rich==15.0.0
|
| 91 |
+
rich-toolkit==0.20.1
|
| 92 |
+
rpds-py==2026.5.1
|
| 93 |
+
safetensors==0.8.0
|
| 94 |
+
scikit-learn==1.9.0
|
| 95 |
+
scipy==1.17.1
|
| 96 |
+
sentence-transformers==5.5.1
|
| 97 |
+
setuptools==81.0.0
|
| 98 |
+
shellingham==1.5.4
|
| 99 |
+
six==1.17.0
|
| 100 |
+
smmap==5.0.3
|
| 101 |
+
sniffio==1.3.1
|
| 102 |
+
soupsieve==2.8.4
|
| 103 |
+
streamlit
|
| 104 |
+
sympy==1.14.0
|
| 105 |
+
tenacity==9.1.4
|
| 106 |
+
threadpoolctl==3.6.0
|
| 107 |
+
tokenizers==0.22.2
|
| 108 |
+
toml==0.10.2
|
| 109 |
+
torch==2.12.0
|
| 110 |
+
tqdm==4.68.2
|
| 111 |
+
transformers==5.11.0
|
| 112 |
+
typer==0.25.1
|
| 113 |
+
typing-inspection==0.4.2
|
| 114 |
+
typing_extensions==4.15.0
|
| 115 |
+
tzdata==2026.2
|
| 116 |
+
ujson==5.12.1
|
| 117 |
+
urllib3==2.7.0
|
| 118 |
+
uvicorn==0.30.1
|
| 119 |
+
watchdog==6.0.0
|
| 120 |
+
watchfiles==1.2.0
|
| 121 |
+
websocket-client==1.9.0
|
| 122 |
+
websockets==16.0
|
| 123 |
+
yarl==1.24.2
|
streamlit_app.py
ADDED
|
@@ -0,0 +1,507 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
streamlit_app.py
|
| 3 |
+
----------------
|
| 4 |
+
Beautiful Streamlit GUI for the Python Q&A Assistant.
|
| 5 |
+
Talks to the FastAPI backend running at localhost:8000.
|
| 6 |
+
|
| 7 |
+
Run with:
|
| 8 |
+
streamlit run streamlit_app.py
|
| 9 |
+
(Make sure the FastAPI server is also running: uvicorn main:app --port 8000)
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import streamlit as st
|
| 13 |
+
import requests
|
| 14 |
+
import time
|
| 15 |
+
from datetime import datetime
|
| 16 |
+
|
| 17 |
+
# βββ Page config (MUST be first Streamlit call) ββββββββββββββββββββββββββββββ
|
| 18 |
+
st.set_page_config(
|
| 19 |
+
page_title="Python Q&A Assistant",
|
| 20 |
+
page_icon="π",
|
| 21 |
+
layout="wide",
|
| 22 |
+
initial_sidebar_state="expanded",
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
API_BASE = "http://localhost:8000"
|
| 26 |
+
|
| 27 |
+
# βββ Custom CSS βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 28 |
+
st.markdown("""
|
| 29 |
+
<style>
|
| 30 |
+
/* ββ Google Font ββ */
|
| 31 |
+
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Fira+Code:wght@400;500&display=swap');
|
| 32 |
+
|
| 33 |
+
/* ββ Global ββ */
|
| 34 |
+
html, body, [class*="css"] {
|
| 35 |
+
font-family: 'Inter', sans-serif;
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
/* ββ Hide default streamlit chrome ββ */
|
| 39 |
+
#MainMenu, footer, header { visibility: hidden; }
|
| 40 |
+
|
| 41 |
+
/* ββ Main background ββ */
|
| 42 |
+
.stApp {
|
| 43 |
+
background: linear-gradient(135deg, #0a0e1a 0%, #0d1528 50%, #0a1020 100%);
|
| 44 |
+
min-height: 100vh;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
/* ββ Hero header ββ */
|
| 48 |
+
.hero {
|
| 49 |
+
background: linear-gradient(135deg, #1a2744 0%, #0f1e3d 60%, #162040 100%);
|
| 50 |
+
border: 1px solid rgba(99, 179, 237, 0.15);
|
| 51 |
+
border-radius: 20px;
|
| 52 |
+
padding: 36px 40px 28px;
|
| 53 |
+
margin-bottom: 28px;
|
| 54 |
+
position: relative;
|
| 55 |
+
overflow: hidden;
|
| 56 |
+
}
|
| 57 |
+
.hero::before {
|
| 58 |
+
content: '';
|
| 59 |
+
position: absolute;
|
| 60 |
+
top: -60px; right: -60px;
|
| 61 |
+
width: 200px; height: 200px;
|
| 62 |
+
background: radial-gradient(circle, rgba(99,179,237,0.12) 0%, transparent 70%);
|
| 63 |
+
border-radius: 50%;
|
| 64 |
+
}
|
| 65 |
+
.hero-title {
|
| 66 |
+
font-size: 2.4rem;
|
| 67 |
+
font-weight: 700;
|
| 68 |
+
background: linear-gradient(135deg, #63b3ed, #90cdf4, #4299e1);
|
| 69 |
+
-webkit-background-clip: text;
|
| 70 |
+
-webkit-text-fill-color: transparent;
|
| 71 |
+
margin: 0 0 8px 0;
|
| 72 |
+
line-height: 1.2;
|
| 73 |
+
}
|
| 74 |
+
.hero-subtitle {
|
| 75 |
+
color: #94a3b8;
|
| 76 |
+
font-size: 1rem;
|
| 77 |
+
font-weight: 400;
|
| 78 |
+
margin: 0;
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
/* ββ Question input card ββ */
|
| 82 |
+
.question-card {
|
| 83 |
+
background: rgba(255,255,255,0.04);
|
| 84 |
+
border: 1px solid rgba(99, 179, 237, 0.2);
|
| 85 |
+
border-radius: 16px;
|
| 86 |
+
padding: 24px 28px;
|
| 87 |
+
margin-bottom: 20px;
|
| 88 |
+
backdrop-filter: blur(10px);
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
/* ββ Answer card ββ */
|
| 92 |
+
.answer-card {
|
| 93 |
+
background: linear-gradient(135deg, rgba(26,39,68,0.8), rgba(15,30,61,0.9));
|
| 94 |
+
border: 1px solid rgba(99, 179, 237, 0.25);
|
| 95 |
+
border-left: 4px solid #4299e1;
|
| 96 |
+
border-radius: 16px;
|
| 97 |
+
padding: 28px 32px;
|
| 98 |
+
margin: 16px 0;
|
| 99 |
+
backdrop-filter: blur(10px);
|
| 100 |
+
animation: fadeIn 0.4s ease;
|
| 101 |
+
}
|
| 102 |
+
@keyframes fadeIn {
|
| 103 |
+
from { opacity: 0; transform: translateY(12px); }
|
| 104 |
+
to { opacity: 1; transform: translateY(0); }
|
| 105 |
+
}
|
| 106 |
+
.answer-text {
|
| 107 |
+
color: #e2e8f0;
|
| 108 |
+
font-size: 0.97rem;
|
| 109 |
+
line-height: 1.75;
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
/* ββ History item ββ */
|
| 113 |
+
.history-item {
|
| 114 |
+
background: rgba(255,255,255,0.04);
|
| 115 |
+
border: 1px solid rgba(255,255,255,0.07);
|
| 116 |
+
border-radius: 10px;
|
| 117 |
+
padding: 12px 16px;
|
| 118 |
+
margin-bottom: 8px;
|
| 119 |
+
cursor: pointer;
|
| 120 |
+
transition: all 0.2s;
|
| 121 |
+
}
|
| 122 |
+
.history-item:hover {
|
| 123 |
+
border-color: rgba(99,179,237,0.3);
|
| 124 |
+
background: rgba(99,179,237,0.05);
|
| 125 |
+
}
|
| 126 |
+
.history-q {
|
| 127 |
+
color: #90cdf4;
|
| 128 |
+
font-size: 0.85rem;
|
| 129 |
+
font-weight: 500;
|
| 130 |
+
margin: 0 0 4px 0;
|
| 131 |
+
white-space: nowrap;
|
| 132 |
+
overflow: hidden;
|
| 133 |
+
text-overflow: ellipsis;
|
| 134 |
+
}
|
| 135 |
+
.history-time {
|
| 136 |
+
color: #4a5568;
|
| 137 |
+
font-size: 0.75rem;
|
| 138 |
+
margin: 0;
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
/* ββ Metric badges ββ */
|
| 142 |
+
.metric-row {
|
| 143 |
+
display: flex;
|
| 144 |
+
gap: 12px;
|
| 145 |
+
margin-top: 16px;
|
| 146 |
+
flex-wrap: wrap;
|
| 147 |
+
}
|
| 148 |
+
.metric-badge {
|
| 149 |
+
background: rgba(66,153,225,0.12);
|
| 150 |
+
border: 1px solid rgba(66,153,225,0.25);
|
| 151 |
+
border-radius: 20px;
|
| 152 |
+
padding: 5px 14px;
|
| 153 |
+
font-size: 0.8rem;
|
| 154 |
+
color: #90cdf4;
|
| 155 |
+
font-weight: 500;
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
/* ββ Source chip ββ */
|
| 159 |
+
.source-chip {
|
| 160 |
+
display: inline-block;
|
| 161 |
+
background: rgba(72,187,120,0.1);
|
| 162 |
+
border: 1px solid rgba(72,187,120,0.25);
|
| 163 |
+
border-radius: 6px;
|
| 164 |
+
padding: 4px 10px;
|
| 165 |
+
font-size: 0.78rem;
|
| 166 |
+
color: #68d391;
|
| 167 |
+
margin: 3px 3px 3px 0;
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
/* ββ Sidebar ββ */
|
| 171 |
+
[data-testid="stSidebar"] {
|
| 172 |
+
background: linear-gradient(180deg, #0d1528 0%, #0a0e1a 100%);
|
| 173 |
+
border-right: 1px solid rgba(99,179,237,0.1);
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
/* ββ Example button ββ */
|
| 177 |
+
.stButton > button {
|
| 178 |
+
width: 100%;
|
| 179 |
+
background: rgba(255,255,255,0.04) !important;
|
| 180 |
+
color: #90cdf4 !important;
|
| 181 |
+
border: 1px solid rgba(99,179,237,0.2) !important;
|
| 182 |
+
border-radius: 10px !important;
|
| 183 |
+
text-align: left !important;
|
| 184 |
+
font-size: 0.85rem !important;
|
| 185 |
+
padding: 10px 14px !important;
|
| 186 |
+
transition: all 0.2s !important;
|
| 187 |
+
white-space: normal !important;
|
| 188 |
+
height: auto !important;
|
| 189 |
+
}
|
| 190 |
+
.stButton > button:hover {
|
| 191 |
+
background: rgba(99,179,237,0.1) !important;
|
| 192 |
+
border-color: rgba(99,179,237,0.4) !important;
|
| 193 |
+
transform: translateX(3px) !important;
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
/* ββ Text area ββ */
|
| 197 |
+
.stTextArea textarea {
|
| 198 |
+
background: rgba(255,255,255,0.05) !important;
|
| 199 |
+
border: 1px solid rgba(99,179,237,0.25) !important;
|
| 200 |
+
border-radius: 12px !important;
|
| 201 |
+
color: #e2e8f0 !important;
|
| 202 |
+
font-family: 'Inter', sans-serif !important;
|
| 203 |
+
font-size: 0.95rem !important;
|
| 204 |
+
resize: none !important;
|
| 205 |
+
}
|
| 206 |
+
.stTextArea textarea:focus {
|
| 207 |
+
border-color: rgba(99,179,237,0.6) !important;
|
| 208 |
+
box-shadow: 0 0 0 3px rgba(99,179,237,0.1) !important;
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
/* ββ Submit button override ββ */
|
| 212 |
+
div[data-testid="stForm"] .stButton > button {
|
| 213 |
+
background: linear-gradient(135deg, #2b6cb0, #3182ce) !important;
|
| 214 |
+
color: white !important;
|
| 215 |
+
border: none !important;
|
| 216 |
+
font-weight: 600 !important;
|
| 217 |
+
font-size: 1rem !important;
|
| 218 |
+
padding: 14px 28px !important;
|
| 219 |
+
border-radius: 12px !important;
|
| 220 |
+
letter-spacing: 0.3px !important;
|
| 221 |
+
}
|
| 222 |
+
div[data-testid="stForm"] .stButton > button:hover {
|
| 223 |
+
background: linear-gradient(135deg, #3182ce, #4299e1) !important;
|
| 224 |
+
transform: translateY(-1px) !important;
|
| 225 |
+
box-shadow: 0 6px 20px rgba(66,153,225,0.35) !important;
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
/* ββ Status dot ββ */
|
| 229 |
+
.status-dot {
|
| 230 |
+
display: inline-block;
|
| 231 |
+
width: 8px; height: 8px;
|
| 232 |
+
border-radius: 50%;
|
| 233 |
+
background: #48bb78;
|
| 234 |
+
margin-right: 6px;
|
| 235 |
+
animation: pulse 2s infinite;
|
| 236 |
+
}
|
| 237 |
+
@keyframes pulse {
|
| 238 |
+
0%,100% { opacity: 1; }
|
| 239 |
+
50% { opacity: 0.4; }
|
| 240 |
+
}
|
| 241 |
+
.status-text { color: #68d391; font-size: 0.85rem; font-weight: 500; }
|
| 242 |
+
|
| 243 |
+
/* ββ Code blocks inside answers ββ */
|
| 244 |
+
code { font-family: 'Fira Code', monospace !important; }
|
| 245 |
+
|
| 246 |
+
/* ββ Expander ββ */
|
| 247 |
+
[data-testid="stExpander"] {
|
| 248 |
+
background: rgba(255,255,255,0.02) !important;
|
| 249 |
+
border: 1px solid rgba(255,255,255,0.07) !important;
|
| 250 |
+
border-radius: 10px !important;
|
| 251 |
+
}
|
| 252 |
+
</style>
|
| 253 |
+
""", unsafe_allow_html=True)
|
| 254 |
+
|
| 255 |
+
# βββ Session state init βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 256 |
+
if "history" not in st.session_state:
|
| 257 |
+
st.session_state.history = [] # list of {question, answer, sources, latency, ts}
|
| 258 |
+
if "current_question" not in st.session_state:
|
| 259 |
+
st.session_state.current_question = ""
|
| 260 |
+
if "api_ok" not in st.session_state:
|
| 261 |
+
st.session_state.api_ok = False
|
| 262 |
+
|
| 263 |
+
# βββ Helper: call API βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 264 |
+
def ask_api(question: str) -> dict | None:
|
| 265 |
+
try:
|
| 266 |
+
t0 = time.time()
|
| 267 |
+
resp = requests.post(
|
| 268 |
+
f"{API_BASE}/ask",
|
| 269 |
+
json={"question": question},
|
| 270 |
+
timeout=60,
|
| 271 |
+
)
|
| 272 |
+
elapsed = time.time() - t0
|
| 273 |
+
if resp.status_code == 200:
|
| 274 |
+
data = resp.json()
|
| 275 |
+
data["latency"] = round(elapsed, 2)
|
| 276 |
+
return data
|
| 277 |
+
else:
|
| 278 |
+
st.error(f"API error {resp.status_code}: {resp.text}")
|
| 279 |
+
return None
|
| 280 |
+
except requests.exceptions.ConnectionError:
|
| 281 |
+
st.error("Cannot connect to FastAPI backend. Make sure `uvicorn main:app --port 8000` is running.")
|
| 282 |
+
return None
|
| 283 |
+
|
| 284 |
+
def check_health() -> dict | None:
|
| 285 |
+
try:
|
| 286 |
+
resp = requests.get(f"{API_BASE}/health", timeout=5)
|
| 287 |
+
if resp.status_code == 200:
|
| 288 |
+
return resp.json()
|
| 289 |
+
except Exception:
|
| 290 |
+
pass
|
| 291 |
+
return None
|
| 292 |
+
|
| 293 |
+
# βββ Sidebar ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 294 |
+
with st.sidebar:
|
| 295 |
+
st.markdown("### π Python Q&A Assistant")
|
| 296 |
+
st.markdown("---")
|
| 297 |
+
|
| 298 |
+
# Health check
|
| 299 |
+
health = check_health()
|
| 300 |
+
if health:
|
| 301 |
+
st.session_state.api_ok = True
|
| 302 |
+
st.markdown(
|
| 303 |
+
f'<span class="status-dot"></span>'
|
| 304 |
+
f'<span class="status-text">API Online</span>',
|
| 305 |
+
unsafe_allow_html=True,
|
| 306 |
+
)
|
| 307 |
+
st.caption(f"π {health['index_size']:,} Q&As indexed")
|
| 308 |
+
st.caption(f"β±οΈ Uptime: {health['uptime_seconds']:.0f}s")
|
| 309 |
+
st.caption(f"π’ Requests: {health['requests_served']}")
|
| 310 |
+
else:
|
| 311 |
+
st.markdown("π΄ API Offline")
|
| 312 |
+
st.warning("Start the API:\n```\nuvicorn main:app --port 8000\n```")
|
| 313 |
+
|
| 314 |
+
st.markdown("---")
|
| 315 |
+
st.markdown("#### π‘ Example Questions")
|
| 316 |
+
|
| 317 |
+
EXAMPLES = [
|
| 318 |
+
"How do I reverse a list in Python?",
|
| 319 |
+
"What is a Python decorator?",
|
| 320 |
+
"How do I handle exceptions in Python?",
|
| 321 |
+
"What is the difference between list and tuple?",
|
| 322 |
+
"How do I sort a dictionary by value?",
|
| 323 |
+
"How do I use *args and **kwargs?",
|
| 324 |
+
"What does the yield keyword do?",
|
| 325 |
+
"How do I read a CSV file with pandas?",
|
| 326 |
+
]
|
| 327 |
+
for ex in EXAMPLES:
|
| 328 |
+
if st.button(ex, key=f"ex_{ex[:20]}"):
|
| 329 |
+
st.session_state.current_question = ex
|
| 330 |
+
|
| 331 |
+
st.markdown("---")
|
| 332 |
+
|
| 333 |
+
# History
|
| 334 |
+
if st.session_state.history:
|
| 335 |
+
st.markdown("#### π Recent Questions")
|
| 336 |
+
for i, h in enumerate(reversed(st.session_state.history[-8:])):
|
| 337 |
+
st.markdown(
|
| 338 |
+
f'<div class="history-item">'
|
| 339 |
+
f'<p class="history-q">{h["question"][:60]}{"..." if len(h["question"]) > 60 else ""}</p>'
|
| 340 |
+
f'<p class="history-time">{h["ts"]} Β· {h["latency"]}s</p>'
|
| 341 |
+
f'</div>',
|
| 342 |
+
unsafe_allow_html=True,
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
if st.session_state.history:
|
| 346 |
+
if st.button("ποΈ Clear History"):
|
| 347 |
+
st.session_state.history = []
|
| 348 |
+
st.rerun()
|
| 349 |
+
|
| 350 |
+
# βββ Main content βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 351 |
+
# Hero
|
| 352 |
+
st.markdown("""
|
| 353 |
+
<div class="hero">
|
| 354 |
+
<h1 class="hero-title">π Python Q&A Assistant</h1>
|
| 355 |
+
<p class="hero-subtitle">
|
| 356 |
+
Powered by <strong>Stack Overflow</strong> data Β· <strong>RAG Pipeline</strong> Β·
|
| 357 |
+
<strong>Groq LLaMA-3.3-70b</strong> Β· 14,864 real Q&A pairs
|
| 358 |
+
</p>
|
| 359 |
+
</div>
|
| 360 |
+
""", unsafe_allow_html=True)
|
| 361 |
+
|
| 362 |
+
# βββ Question input form βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 363 |
+
with st.form("question_form", clear_on_submit=False):
|
| 364 |
+
question = st.text_area(
|
| 365 |
+
"Ask a Python question",
|
| 366 |
+
value=st.session_state.current_question,
|
| 367 |
+
placeholder="e.g. How do I reverse a list in Python? What is a lambda function? How does GIL work?",
|
| 368 |
+
height=110,
|
| 369 |
+
label_visibility="collapsed",
|
| 370 |
+
)
|
| 371 |
+
col1, col2, col3 = st.columns([3, 1, 1])
|
| 372 |
+
with col1:
|
| 373 |
+
submitted = st.form_submit_button("π Ask Question", use_container_width=True)
|
| 374 |
+
with col2:
|
| 375 |
+
st.form_submit_button("", disabled=True, use_container_width=True) # spacer
|
| 376 |
+
with col3:
|
| 377 |
+
pass
|
| 378 |
+
|
| 379 |
+
# βββ Handle submission ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 380 |
+
if submitted and question.strip():
|
| 381 |
+
st.session_state.current_question = question.strip()
|
| 382 |
+
|
| 383 |
+
with st.spinner("π Searching Stack Overflow knowledge base..."):
|
| 384 |
+
result = ask_api(question.strip())
|
| 385 |
+
|
| 386 |
+
if result:
|
| 387 |
+
entry = {
|
| 388 |
+
"question": question.strip(),
|
| 389 |
+
"answer": result["answer"],
|
| 390 |
+
"sources": result.get("sources", []),
|
| 391 |
+
"latency": result.get("latency", 0),
|
| 392 |
+
"model": result.get("model", ""),
|
| 393 |
+
"docs": result.get("docs_retrieved", 5),
|
| 394 |
+
"ts": datetime.now().strftime("%H:%M"),
|
| 395 |
+
}
|
| 396 |
+
st.session_state.history.append(entry)
|
| 397 |
+
|
| 398 |
+
elif submitted and not question.strip():
|
| 399 |
+
st.warning("Please type a question first!")
|
| 400 |
+
|
| 401 |
+
# βββ Display latest answer ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 402 |
+
if st.session_state.history:
|
| 403 |
+
latest = st.session_state.history[-1]
|
| 404 |
+
|
| 405 |
+
st.markdown("---")
|
| 406 |
+
|
| 407 |
+
# Question bubble
|
| 408 |
+
st.markdown(
|
| 409 |
+
f"""
|
| 410 |
+
<div style="
|
| 411 |
+
background: rgba(66,153,225,0.1);
|
| 412 |
+
border: 1px solid rgba(66,153,225,0.2);
|
| 413 |
+
border-radius: 14px 14px 4px 14px;
|
| 414 |
+
padding: 14px 20px;
|
| 415 |
+
margin-bottom: 4px;
|
| 416 |
+
display: inline-block;
|
| 417 |
+
max-width: 80%;
|
| 418 |
+
float: right;
|
| 419 |
+
clear: both;
|
| 420 |
+
">
|
| 421 |
+
<span style="color:#90cdf4; font-weight:600; font-size:0.95rem;">
|
| 422 |
+
{latest['question']}
|
| 423 |
+
</span>
|
| 424 |
+
</div>
|
| 425 |
+
<div style="clear:both; margin-bottom:16px;"></div>
|
| 426 |
+
""",
|
| 427 |
+
unsafe_allow_html=True,
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
# Answer card
|
| 431 |
+
st.markdown('<div class="answer-card">', unsafe_allow_html=True)
|
| 432 |
+
|
| 433 |
+
# Metrics row
|
| 434 |
+
sources_html = "".join(
|
| 435 |
+
f'<span class="source-chip">π {s[:55]}{"..." if len(s)>55 else ""}</span>'
|
| 436 |
+
for s in latest["sources"]
|
| 437 |
+
)
|
| 438 |
+
st.markdown(
|
| 439 |
+
f"""
|
| 440 |
+
<div class="metric-row">
|
| 441 |
+
<span class="metric-badge">β‘ {latest['latency']}s</span>
|
| 442 |
+
<span class="metric-badge">π€ {latest['model'].split('-')[0]+'-'+latest['model'].split('-')[1] if '-' in latest['model'] else latest['model']}</span>
|
| 443 |
+
<span class="metric-badge">π {latest['docs']} sources</span>
|
| 444 |
+
<span class="metric-badge">π {latest['ts']}</span>
|
| 445 |
+
</div>
|
| 446 |
+
""",
|
| 447 |
+
unsafe_allow_html=True,
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
st.markdown("<br>", unsafe_allow_html=True)
|
| 451 |
+
|
| 452 |
+
# Answer text (rendered as markdown for code highlighting)
|
| 453 |
+
st.markdown(latest["answer"])
|
| 454 |
+
|
| 455 |
+
# Sources expander
|
| 456 |
+
if latest["sources"]:
|
| 457 |
+
with st.expander("π View Stack Overflow Sources", expanded=False):
|
| 458 |
+
for i, src in enumerate(latest["sources"], 1):
|
| 459 |
+
st.markdown(
|
| 460 |
+
f'<span class="source-chip">#{i} {src}</span>',
|
| 461 |
+
unsafe_allow_html=True,
|
| 462 |
+
)
|
| 463 |
+
|
| 464 |
+
st.markdown("</div>", unsafe_allow_html=True)
|
| 465 |
+
|
| 466 |
+
# ββ Previous Q&As ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 467 |
+
if len(st.session_state.history) > 1:
|
| 468 |
+
st.markdown("<br>", unsafe_allow_html=True)
|
| 469 |
+
st.markdown("#### π Previous Answers")
|
| 470 |
+
for h in reversed(st.session_state.history[:-1]):
|
| 471 |
+
with st.expander(f"Q: {h['question'][:80]}... ({h['ts']} Β· {h['latency']}s)"):
|
| 472 |
+
st.markdown(h["answer"])
|
| 473 |
+
if h["sources"]:
|
| 474 |
+
srcs = " ".join(
|
| 475 |
+
f'<span class="source-chip">π {s[:50]}</span>'
|
| 476 |
+
for s in h["sources"]
|
| 477 |
+
)
|
| 478 |
+
st.markdown(srcs, unsafe_allow_html=True)
|
| 479 |
+
|
| 480 |
+
else:
|
| 481 |
+
# Empty state
|
| 482 |
+
st.markdown("<br>", unsafe_allow_html=True)
|
| 483 |
+
col1, col2, col3 = st.columns(3)
|
| 484 |
+
cards = [
|
| 485 |
+
("π", "RAG Powered", "Retrieves real Stack Overflow answers as context before generating"),
|
| 486 |
+
("β‘", "Groq LLaMA 3.3", "Blazing fast inference with the best open-source LLM"),
|
| 487 |
+
("π", "14,864 Q&As", "Indexed from 607K Python Stack Overflow questions"),
|
| 488 |
+
]
|
| 489 |
+
for col, (icon, title, desc) in zip([col1, col2, col3], cards):
|
| 490 |
+
with col:
|
| 491 |
+
st.markdown(
|
| 492 |
+
f"""
|
| 493 |
+
<div style="
|
| 494 |
+
background: rgba(255,255,255,0.03);
|
| 495 |
+
border: 1px solid rgba(255,255,255,0.08);
|
| 496 |
+
border-radius: 14px;
|
| 497 |
+
padding: 24px 20px;
|
| 498 |
+
text-align: center;
|
| 499 |
+
height: 160px;
|
| 500 |
+
">
|
| 501 |
+
<div style="font-size:2rem; margin-bottom:10px;">{icon}</div>
|
| 502 |
+
<div style="color:#90cdf4; font-weight:600; font-size:0.95rem; margin-bottom:6px;">{title}</div>
|
| 503 |
+
<div style="color:#64748b; font-size:0.82rem; line-height:1.5;">{desc}</div>
|
| 504 |
+
</div>
|
| 505 |
+
""",
|
| 506 |
+
unsafe_allow_html=True,
|
| 507 |
+
)
|