Spaces:
Sleeping
Sleeping
Delete AgileAdvisor-v0.6.py
Browse filesTransformation from AgileAdvisor Clone to AgileCraft
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815import gradio as grimport chromadbfrom chromadb.utils import embedding_functionsfrom groq import Groqimport osimport requestsimport jsonimport loggingfrom typing import List, Optional, Tuplefrom dataclasses import dataclassimport re
# =========================# LOGGING SETUP (HF Spaces compatible)# =========================logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")logger = logging.getLogger(__name__)
# =========================# CONFIGURATION# =========================
@dataclassclass Config: """Centralized configuration - optimized for Hugging Face Spaces"""
# GitHub Gist Config GITHUB_USERNAME: str = "suryasticsai" GIST_ID: str = "c25ec2898e91a2ce09ab74930741907e" GIST_FILENAME: str = "agile-knowledge-base.txt"
# ChromaDB Config COLLECTION_NAME: str = "agile_knowledge" # Use ./chroma_db for persistent storage (survives restarts in HF Spaces) CHROMA_PERSIST_DIR: str = "./chroma_db"
# Limits MAX_QUERY_LENGTH: int = 500 MAX_FEED_LENGTH: int = 10000 DEFAULT_N_RESULTS: int = 3
# Groq Config GROQ_MODEL: str = "llama-3.1-8b-instant" GROQ_TEMPERATURE: float = 0.5 GROQ_MAX_TOKENS: int = 4096
# API Timeouts REQUEST_TIMEOUT: int = 10 GROQ_TIMEOUT: float = 60.0
@property def gist_url(self) -> str: return f"https://gist.githubusercontent.com/{self.GITHUB_USERNAME}/{self.GIST_ID}/raw/{self.GIST_FILENAME}"
@property def gist_api_url(self) -> str: return f"https://api.github.com/gists/{self.GIST_ID}"
CONFIG = Config()
# =========================# KNOWLEDGE BASE MANAGER# =========================
class KnowledgeBase: """ Encapsulates ChromaDB + Gist operations. Optimized for Hugging Face Spaces with persistent storage. """
def __init__(self): self.config = CONFIG
# Initialize ChromaDB with persistent storage # HF Spaces allows writing to ./ (app directory) which persists across restarts self.client = chromadb.PersistentClient(path=self.config.CHROMA_PERSIST_DIR) self.emb = embedding_functions.DefaultEmbeddingFunction() self.collection = self._init_collection()
# Initialize Groq client with proper timeout groq_key = os.environ.get("GROQ_API_KEY") if not groq_key: logger.error("GROQ_API_KEY not found in environment/secrets!") # Create dummy client to avoid crash, will fail on actual use self.groq_client = None else: self.groq_client = Groq( api_key=groq_key, timeout=self.config.GROQ_TIMEOUT, max_retries=2 ) logger.info("Groq client initialized")
# Load data from Gist or defaults self._load_data()
def _init_collection(self): """Get or create collection safely""" try: collection = self.client.get_or_create_collection( name=self.config.COLLECTION_NAME, embedding_function=self.emb, metadata={ "description": "Agile knowledge base for RAG", "version": "1.0", "source": "github_gist", }, ) count = collection.count() logger.info(f"Collection ready with {count} documents") return collection except Exception as e: logger.error(f"Failed to initialize collection: {e}") raise RuntimeError(f"ChromaDB init failed: {e}")
def _load_data(self): """Load from Gist, fallback to defaults""" try: response = requests.get( self.config.gist_url, timeout=self.config.REQUEST_TIMEOUT ) response.raise_for_status()
documents = [ line.strip() for line in response.text.split("\n") if line.strip() ]
if documents: self._update_collection(documents, replace=True) logger.info(f"Loaded {len(documents)} documents from Gist") else: logger.warning("Gist empty, loading defaults") self._load_defaults()
except Exception as e: logger.warning(f"Could not load from Gist: {e}") self._load_defaults()
def _load_defaults(self): """Fallback Agile knowledge""" defaults = [ "Sprint Planning is where the Scrum Team selects work from the Product Backlog for the upcoming Sprint", "Daily Standup is a 15-minute time-boxed event for the Development Team to synchronize activities and plan for the next 24 hours", "Sprint Review is held at the end of the Sprint to inspect the Increment and adapt the Product Backlog if needed", "Sprint Retrospective is an opportunity for the Scrum Team to inspect itself and create a plan for improvements for the next Sprint", "Product Owner is responsible for maximizing the value of the product resulting from work of the Development Team", "Scrum Master is responsible for promoting and supporting Scrum by helping everyone understand Scrum theory, practice, rules, and values", "Definition of Done is a shared understanding of what it means for work to be complete, ensuring transparency and quality", "Velocity is a measure of the amount of work a Team can tackle during a single Sprint, used for planning not performance measurement", ] self._update_collection(defaults, replace=True) logger.info(f"Loaded {len(defaults)} default documents")
def _update_collection(self, documents: List[str], replace: bool = False): """Safely update ChromaDB collection""" try: if replace: # Clear existing try: existing = self.collection.get() if existing and existing.get("ids"): self.collection.delete(ids=existing["ids"]) logger.info(f"Cleared {len(existing['ids'])} existing docs") except Exception: pass # No existing data
if documents: # Add with hashed IDs to prevent collisions self.collection.add( documents=documents, ids=[ f"doc_{i}_{abs(hash(doc)) % 100000}" for i, doc in enumerate(documents) ], metadatas=[ {"source": "gist", "index": i} for i in range(len(documents)) ], ) logger.info(f"Added {len(documents)} documents")
except Exception as e: logger.error(f"Failed to update collection: {e}") raise
def query(self, question: str, n_results: int = None) -> Tuple[List[str], str]: """ Query knowledge base. Returns: (documents_list, formatted_context_string) """ if not question or not question.strip(): return [], "No question provided."
n_results = n_results or self.config.DEFAULT_N_RESULTS
try: # Ensure we don't request more than available available = self.collection.count() n_results = min(n_results, available or 1)
results = self.collection.query( query_texts=[question.strip()], n_results=n_results, include=["documents", "distances", "metadatas"], )
docs = results["documents"][0] if results.get("documents") else []
if not docs: return [], "No relevant documents found in the knowledge base."
# Format with relevance scores context_parts = [] distances = results.get("distances", [[]])[0] or []
for i, (doc, dist) in enumerate(zip(docs, distances), 1): # Lower distance = higher relevance in ChromaDB if dist < 0.3: relevance = "High" elif dist < 0.6: relevance = "Medium" else: relevance = "Low"
context_parts.append(f"[Match {i}] (Relevance: {relevance})\n{doc}")
return docs, "\n\n".join(context_parts)
except Exception as e: logger.error(f"Query failed: {e}") return [], f"Query error: {str(e)}"
def update_gist(self, new_text: str) -> str: """Update GitHub Gist and refresh vector DB"""
# Validation if not new_text or not new_text.strip(): return "Empty input! Please provide some Agile knowledge to feed."
if len(new_text) > self.config.MAX_FEED_LENGTH: return ( f"Too long! ({len(new_text)} chars). Max: {self.config.MAX_FEED_LENGTH}" )
token = os.environ.get("GITHUB_TOKEN") if not token: return "GITHUB_TOKEN not found! Add it in HF Spaces Settings > Secrets."
try: headers = { "Authorization": f"token {token}", "Accept": "application/vnd.github.v3+json", }
# Fetch current Gist response = requests.get( self.config.gist_api_url, headers=headers, timeout=self.config.REQUEST_TIMEOUT, ) response.raise_for_status()
gist_data = response.json() current_content = gist_data["files"][self.config.GIST_FILENAME]["content"]
# Deduplication check new_lines = [line.strip() for line in new_text.split("\n") if line.strip()] existing_lines = set( line.strip() for line in current_content.split("\n") if line.strip() )
unique_lines = [line for line in new_lines if line not in existing_lines]
if not unique_lines: return "All content already exists! No duplicates added."
# Append new unique content updated_content = current_content.rstrip() + "\n" + "\n".join(unique_lines)
# Update Gist via API payload = { "files": {self.config.GIST_FILENAME: {"content": updated_content}} }
update_resp = requests.patch( self.config.gist_api_url, headers=headers, data=json.dumps(payload), timeout=self.config.REQUEST_TIMEOUT, ) update_resp.raise_for_status()
# Refresh ChromaDB all_docs = [ line.strip() for line in updated_content.split("\n") if line.strip() ] self._update_collection(all_docs, replace=True)
return f"Success! Added {len(unique_lines)} new facts. Total: {len(all_docs)} documents."
except requests.RequestException as e: logger.error(f"GitHub API error: {e}") return f"GitHub API error: {str(e)}" except Exception as e: logger.error(f"Update failed: {e}") return f"Error: {str(e)}"
def get_stats(self) -> dict: """Get KB stats for UI display""" try: return { "total_documents": self.collection.count(), "collection_name": self.config.COLLECTION_NAME, "storage": self.config.CHROMA_PERSIST_DIR, "groq_ready": self.groq_client is not None, } except Exception as e: return {"error": str(e)}
# =========================# HTML SANITIZATION# =========================
def sanitize_html(text: str) -> str: """Prevent XSS - strip dangerous tags and attributes""" if not text: return "" # Remove script tags text = re.sub( r"<script[^>]*>.*?</script>", "", text, flags=re.DOTALL | re.IGNORECASE ) # Remove event handlers text = re.sub(r'\s*on\w+\s*=\s*["\'][^"\']*["\']', "", text, flags=re.IGNORECASE) # Remove javascript: URLs text = re.sub(r"javascript:", "", text, flags=re.IGNORECASE) return text
# =========================# SYSTEM PROMPT (IMPROVED)# =========================
SYSTEM_PROMPT = """You are Scrum Wizard — a sharp, witty, brutally honest Agile Coach with 10 years of SAFe experience.You cut through corporate fluff. You celebrate good Agile. You roast bad Agile with humor and love.
CRITICAL RULES:- You ALWAYS respond in pure HTML only. No markdown. No plain text. No code fences.- ALWAYS show the DATASET FACT CARD first before any explanation.- If factual data exists in context, show it clearly and accurately.- Fill ALL template placeholders below. Never leave placeholders empty.
Your response MUST follow this EXACT structure:
<div style="font-family:sans-serif;max-width:800px;margin:0 auto;padding:8px">
<!-- DATASET CARD --> <div style="background:linear-gradient(135deg,#052e16,#064e3b);border:1px solid rgba(16,185,129,0.25);border-left:5px solid #10b981;border-radius:14px;padding:18px 22px;margin-bottom:16px;box-shadow:0 0 0 1px rgba(16,185,129,0.05)"> <div style="display:flex;align-items:center;gap:10px;margin-bottom:10px"> <div style="width:34px;height:34px;border-radius:10px;background:rgba(16,185,129,0.15);display:flex;align-items:center;justify-content:center;font-size:1rem">📦</div> <div> <div style="font-size:0.72rem;color:#6ee7b7;font-weight:700;letter-spacing:2px;text-transform:uppercase">Data Retrieved From Dataset</div> <div style="font-size:0.75rem;color:#86efac;margin-top:2px">Exact matched Agile knowledge retrieved from vector memory</div> </div> </div> <div style="background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.05);padding:16px 18px;border-radius:12px"> <div style="color:#ecfdf5;font-size:0.96rem;line-height:1.8;font-weight:500">{dataset_match}</div> </div> </div>
<!-- MAIN EXPLANATION CARD --> <div style="background:linear-gradient(135deg,#1a1a2e,#16213e);border-left:4px solid #00d4aa;border-radius:12px;padding:20px 24px;margin-bottom:16px"> <div style="font-size:0.7rem;color:#00d4aa;font-weight:700;letter-spacing:2px;text-transform:uppercase;margin-bottom:8px">âš¡ AgileAdvisor Says</div> <div style="font-size:1.1rem;font-weight:700;color:#f1f5f9;margin-bottom:8px">{topic_title}</div> <div style="color:#94a3b8;font-size:0.9rem;line-height:1.7">{explanation}</div> </div>
<!-- KEY POINTS --> <div style="background:#111827;border:1px solid #1e293b;border-radius:12px;padding:20px 24px;margin-bottom:16px"> <div style="font-size:0.7rem;color:#8b5cf6;font-weight:700;letter-spacing:2px;text-transform:uppercase;margin-bottom:14px">📖 What This Actually Means</div> <div style="display:flex;flex-direction:column;gap:10px"> <div style="display:flex;gap:12px;align-items:flex-start"> <div style="background:#8b5cf6;color:#fff;border-radius:6px;padding:4px 10px;font-size:0.75rem;font-weight:700;white-space:nowrap;margin-top:2px">01</div> <div style="color:#cbd5e1;font-size:0.88rem;line-height:1.6">{key_point_1}</div> </div> <div style="display:flex;gap:12px;align-items:flex-start"> <div style="background:#8b5cf6;color:#fff;border-radius:6px;padding:4px 10px;font-size:0.75rem;font-weight:700;white-space:nowrap;margin-top:2px">02</div> <div style="color:#cbd5e1;font-size:0.88rem;line-height:1.6">{key_point_2}</div> </div> <div style="display:flex;gap:12px;align-items:flex-start"> <div style="background:#8b5cf6;color:#fff;border-radius:6px;padding:4px 10px;font-size:0.75rem;font-weight:700;white-space:nowrap;margin-top:2px">03</div> <div style="color:#cbd5e1;font-size:0.88rem;line-height:1.6">{key_point_3}</div> </div> </div> </div>
<!-- PEOPLE FLOW --> <div style="background:#111827;border:1px solid #1e293b;border-radius:12px;padding:20px 24px;margin-bottom:16px"> <div style="font-size:0.7rem;color:#f59e0b;font-weight:700;letter-spacing:2px;text-transform:uppercase;margin-bottom:16px">👥 Who's Involved & In What Order</div> <div style="display:flex;flex-direction:column;gap:0"> <div style="display:flex;align-items:center;gap:12px;padding:12px 16px;background:#0c101a;border:1px solid #1e293b;border-radius:10px;margin-bottom:4px"> <div style="width:32px;height:32px;border-radius:50%;background:linear-gradient(135deg,#8b5cf6,#7c3aed);display:flex;align-items:center;justify-content:center;font-size:0.85rem;flex-shrink:0">🎯</div> <div> <div style="font-weight:700;font-size:0.88rem;color:#f1f5f9">{role_1_name}</div> <div style="font-size:0.78rem;color:#64748b;margin-top:2px">{role_1_action}</div> </div> <div style="margin-left:auto;padding:3px 10px;border-radius:20px;font-size:0.7rem;font-weight:600;background:rgba(139,92,246,0.15);color:#8b5cf6;border:1px solid rgba(139,92,246,0.3)">Step 1</div> </div> <div style="text-align:center;color:#334155;font-size:1.2rem;margin:2px 0">↓</div> <div style="display:flex;align-items:center;gap:12px;padding:12px 16px;background:#0c101a;border:1px solid #1e293b;border-radius:10px;margin-bottom:4px"> <div style="width:32px;height:32px;border-radius:50%;background:linear-gradient(135deg,#00d4aa,#059669);display:flex;align-items:center;justify-content:center;font-size:0.85rem;flex-shrink:0">ðŸ§</div> <div> <div style="font-weight:700;font-size:0.88rem;color:#f1f5f9">{role_2_name}</div> <div style="font-size:0.78rem;color:#64748b;margin-top:2px">{role_2_action}</div> </div> <div style="margin-left:auto;padding:3px 10px;border-radius:20px;font-size:0.7rem;font-weight:600;background:rgba(0,212,170,0.15);color:#00d4aa;border:1px solid rgba(0,212,170,0.3)">Step 2</div> </div> <div style="text-align:center;color:#334155;font-size:1.2rem;margin:2px 0">↓</div> <div style="display:flex;align-items:center;gap:12px;padding:12px 16px;background:#0c101a;border:1px solid #1e293b;border-radius:10px;margin-bottom:4px"> <div style="width:32px;height:32px;border-radius:50%;background:linear-gradient(135deg,#3b82f6,#1d4ed8);display:flex;align-items:center;justify-content:center;font-size:0.85rem;flex-shrink:0">💻</div> <div> <div style="font-weight:700;font-size:0.88rem;color:#f1f5f9">{role_3_name}</div> <div style="font-size:0.78rem;color:#64748b;margin-top:2px">{role_3_action}</div> </div> <div style="margin-left:auto;padding:3px 10px;border-radius:20px;font-size:0.7rem;font-weight:600;background:rgba(59,130,246,0.15);color:#3b82f6;border:1px solid rgba(59,130,246,0.3)">Step 3</div> </div> </div> </div>
<!-- COMMON MISTAKE --> <div style="background:linear-gradient(135deg,rgba(239,68,68,0.08),rgba(239,68,68,0.03));border:1px solid rgba(239,68,68,0.25);border-radius:12px;padding:18px 24px;margin-bottom:16px"> <div style="font-size:0.7rem;color:#ef4444;font-weight:700;letter-spacing:2px;text-transform:uppercase;margin-bottom:8px">🚩 Common Mistake</div> <div style="color:#fca5a5;font-size:0.88rem;line-height:1.6">{common_mistake}</div> </div>
<!-- QUOTE --> <div style="background:linear-gradient(135deg,rgba(0,212,170,0.08),rgba(139,92,246,0.08));border:1px solid rgba(0,212,170,0.2);border-radius:12px;padding:16px 24px;text-align:center"> <div style="color:#00d4aa;font-style:italic;font-size:0.9rem;font-weight:600">"{quote}"</div> <div style="color:#475569;font-size:0.75rem;margin-top:6px">— AgileAdvisor 🤙</div> </div>
</div>
TONE RULES:- Be like a coach who has seen it all and has zero patience for excuses- Use phrases like: "Let me be real", "Nobody asked but here's the truth", "If your team skips this..."- For bad practices, say: "Congratulations, you've invented chaos"- Always end with energy- NEVER ignore factual dataset matches- DATASET CARD should contain exact retrieved context before interpretation
ROLE COLORS:- SM = #00d4aa- PO = #8b5cf6- Dev = #3b82f6- QA = #f59e0b- RTE = #ec4899"""
# =========================# AI ADVISOR CLASS# =========================
class AgileAdvisor: """Handles AI generation with RAG context"""
def __init__(self, kb: KnowledgeBase): self.kb = kb self.config = CONFIG
def ask(self, question: str) -> str: """Main entry: retrieve context + generate HTML response"""
# Validation if not question or not question.strip(): return self._error_card( "Please enter a question! Even Agile coaches need a prompt." )
if len(question) > self.config.MAX_QUERY_LENGTH: return self._error_card( f"Question too long ({len(question)} chars). Max: {self.config.MAX_QUERY_LENGTH}" )
# Check Groq availability if not self.kb.groq_client: return self._error_card( "Groq API not configured. Add GROQ_API_KEY in HF Spaces Settings > Secrets." )
try: # Step 1: Retrieve from Vector DB docs, context = self.kb.query(question)
# Step 2: Generate with Groq response = self.kb.groq_client.chat.completions.create( model=self.config.GROQ_MODEL, messages=[ {"role": "system", "content": SYSTEM_PROMPT}, { "role": "user", "content": f"""RETRIEVED CONTEXT FROM KNOWLEDGE BASE:{context}
USER QUESTION:{question}
INSTRUCTIONS:1. Use the retrieved context to fill the DATASET CARD with exact facts2. Answer the question with wit and expertise3. Fill ALL placeholders: dataset_match, topic_title, explanation, key_point_1, key_point_2, key_point_3, role_1_name, role_1_action, role_2_name, role_2_action, role_3_name, role_3_action, common_mistake, quote4. Output valid HTML only""", }, ], temperature=self.config.GROQ_TEMPERATURE, max_tokens=self.config.GROQ_MAX_TOKENS, )
content = response.choices[0].message.content
# Sanitize and wrap if needed content = sanitize_html(content) if not content.strip().startswith("<"): content = f'<div style="font-family:sans-serif;max-width:800px;margin:0 auto;padding:20px">{content}</div>'
return content
except Exception as e: logger.error(f"AI generation failed: {e}") return self._error_card(f"AI generation failed: {str(e)}")
def _error_card(self, message: str) -> str: """Generate error HTML card""" return ( '<div style="font-family:sans-serif;max-width:800px;margin:0 auto;padding:20px">' '<div style="background:linear-gradient(135deg,#7f1d1d,#991b1b);' "border:1px solid rgba(239,68,68,0.3);border-radius:12px;" 'padding:20px;color:#fca5a5">' '<div style="font-size:1.2rem;font-weight:700;margin-bottom:8px">âš ï¸ Oops!</div>' f'<div style="line-height:1.6">{message}</div>' "</div></div>" )
# =========================# GRADIO UI BUILDER# =========================
def build_app(kb: KnowledgeBase, advisor: AgileAdvisor): """Build Gradio interface optimized for HF Spaces"""
# Custom CSS for better look custom_css = """ .stats-bar { background: linear-gradient(135deg, #1e293b, #0f172a); border-radius: 12px; padding: 12px 16px; margin-bottom: 16px; border: 1px solid #334155; color: #94a3b8; font-size: 0.85rem; } .stats-bar strong { color: #00d4aa; } .footer { text-align: center; margin-top: 24px; color: #64748b; font-size: 0.8rem; padding: 16px; } """
with gr.Blocks(title="AgileAdvisor RAG", css=custom_css) as app:
# Header gr.Markdown( """ # 🧞 AgileAdvisor ### Your RAG-powered Agile Coach with attitude """ )
# Stats bar stats = kb.get_stats() status_color = "🟢" if stats.get("groq_ready") else "🔴" gr.Markdown( f""" <div class="stats-bar"> {status_color} <strong>Knowledge Base:</strong> {stats.get('total_documents', 0)} documents | <strong>Storage:</strong> {stats.get('storage', 'N/A')} | <strong>Model:</strong> {CONFIG.GROQ_MODEL} </div> """ )
# ===================== # TAB 1: ASK # ===================== with gr.Tab("Ask AgileAdvisor âš¡"): with gr.Row(): with gr.Column(scale=3): question_input = gr.Textbox( placeholder="e.g. What is Sprint Planning? Why do teams fail at Daily Standups?", label="Your Agile Question", lines=3, max_lines=5, )
with gr.Row(): ask_btn = gr.Button( "Ask the Wizard 🔮", variant="primary", size="lg", scale=3 ) clear_q_btn = gr.Button( "Clear 🗑ï¸", variant="stop", size="sm", scale=1 )
with gr.Column(scale=1): gr.Markdown( """ **💡 Tips for best results:** - Ask about specific Scrum events - Mention roles (PO, SM, Dev Team) - Ask about anti-patterns - Keep questions focused """ )
# Response area answer_output = gr.HTML(label="Response")
# Example questions gr.Examples( examples=[ "What happens in Sprint Planning and who attends?", "Why is my Daily Standup taking 45 minutes?", "What does a Product Owner actually do all day?", "Explain the Definition of Done vs Definition of Ready", "Common mistakes during Sprint Retrospective", "What is velocity and how should we use it?", "My Scrum Master is just scheduling meetings, is that right?", ], inputs=question_input, label="🔥 Quick Questions (Click to try)", )
# Event handlers ask_btn.click(fn=advisor.ask, inputs=question_input, outputs=answer_output)
clear_q_btn.click(fn=lambda: "", inputs=None, outputs=question_input)
# ===================== # TAB 2: FEED DATASET # ===================== with gr.Tab("Feed Dataset 📦"): with gr.Row(): with gr.Column(scale=2): dataset_input = gr.Textbox( placeholder="""Paste new Agile knowledge here... Example format (one fact per line): Sprint 0 is a preparation phase before the first official sprint where the team sets up infrastructure The Definition of Ready ensures Product Backlog items are actionable and clear before Sprint Planning Velocity is a planning metric, not a performance target or deadline enforcement tool A Sprint Goal provides flexibility by allowing the Development Team to adapt the Sprint Backlog while maintaining focus""", label="New Agile Knowledge", lines=12, max_lines=25, )
with gr.Row(): feed_btn = gr.Button( "Feed Into Dataset 🚀", variant="secondary", scale=3 ) clear_feed_btn = gr.Button("Clear 🗑ï¸", variant="stop", scale=1)
with gr.Column(scale=1): gr.Markdown( """ **📋 Feeding Guidelines:**
✅ **DO:** - One fact per line - Be specific and factual - Include role names (PO, SM, Dev) - Mention ceremony names clearly - Include real-world context
⌠**DON'T:** - Add opinions or fluff - Duplicate existing facts - Add code or markdown - Exceed 10,000 characters
**Examples of good facts:** - "Sprint Review should never be a demo-only session" - "The Scrum Master protects the team from external interruptions" - "Refinement is not a mandatory Scrum event but is highly recommended" """ )
feed_output = gr.Textbox(label="Feed Status", interactive=False, lines=2)
# Event handlers feed_btn.click(fn=kb.update_gist, inputs=dataset_input, outputs=feed_output)
clear_feed_btn.click(fn=lambda: "", inputs=None, outputs=dataset_input)
# ===================== # TAB 3: ABOUT # ===================== with gr.Tab("About ℹï¸"): gr.Markdown( """ ## How AgileAdvisor Works
This is a **RAG (Retrieval-Augmented Generation)** application:
1. **Vector Database**: Stores Agile knowledge as embeddings using ChromaDB 2. **Retrieval**: When you ask a question, it finds the most relevant facts 3. **Generation**: Groq LLM combines retrieved facts with its knowledge to answer 4. **Dataset**: Lives in a GitHub Gist and can be expanded by feeding new facts
## Architecture
``` User Question → ChromaDB (Similarity Search) → Groq LLM + Context → HTML Response ↑ GitHub Gist (Source of Truth) ```
## Hero Tech Stack
- **Hero**: Sai Varakala â˜€ï¸ (@suryasticsai) - **Frontend**: Gradio - **Vector DB**: ChromaDB (persistent) - **Embeddings**: Default (all-MiniLM-L6-v2) - **LLM**: Groq (Llama 3.1 8B Instant) - **Storage**: GitHub Gist + local persistence """ )
# Footer gr.Markdown( """ <div class="footer"> 🚀 Built with Love by Sai Surya â˜€ï¸ | 💾 Data persists via GitHub Gist + Local Vector DB | 🔄 Auto-syncs on every feed </div> """ )
return app
# =========================# MAIN ENTRY# =========================
def main(): """Initialize and launch on Hugging Face Spaces"""
# Log environment status (don't expose actual keys!) has_groq = bool(os.environ.get("GROQ_API_KEY")) has_github = bool(os.environ.get("GITHUB_TOKEN"))
logger.info( f"Secrets check - GROQ_API_KEY: {'OK' if has_groq else 'MISSING'}, GITHUB_TOKEN: {'OK' if has_github else 'MISSING'}" )
if not has_groq: logger.warning( "GROQ_API_KEY missing! AI responses will show error. Add it in HF Spaces Settings > Secrets." ) if not has_github: logger.warning( "GITHUB_TOKEN missing! Dataset updates will show error. Add it in HF Spaces Settings > Secrets." )
try: # Initialize knowledge base logger.info("Initializing Knowledge Base...") kb = KnowledgeBase()
# Initialize advisor advisor = AgileAdvisor(kb)
# Build and launch UI logger.info("Building Gradio UI...") app = build_app(kb, advisor)
# HF Spaces compatible launch app.launch( server_name="0.0.0.0", server_port=7860, share=False, show_error=True, quiet=False, theme=gr.themes.Soft(), )
except Exception as e: logger.critical(f"Fatal error starting app: {e}") raise
if __name__ == "__main__": main()AgileAdvisor-v0.6.pyDeleted-815