""" Bettermind Labs Project Generator Backend - Milestone 4 (Research-Backed Discovery Engine) Implements problem-first discovery loops, hybrid semantic-archetype matching matrices, student archetype engines, and multi-student group compatibility mapping layers. Preserves FastAPI routing signatures, Tally ingestion layers, and strict API contracts. Refactored to enforce Trajectory-Based Opportunity Discovery over generic interest matching. """ import os import uuid import json import time import logging import asyncio import sqlite3 from datetime import datetime from typing import List, Dict, Any, Optional import numpy as np import pandas as pd import httpx from dotenv import load_dotenv from fastapi import FastAPI, HTTPException, status from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel, EmailStr, Field from sentence_transformers import SentenceTransformer from groq import Groq load_dotenv() logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", handlers=[logging.StreamHandler()] ) logger = logging.getLogger("bettermind-backend") app = FastAPI( title="Bettermind Labs Project Discovery Platform", version="4.2.0", description="Milestone 4 - Trajectory-Driven Problem Verification Flow & Hybrid Strategic Match Engine" ) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # --------------------------------------------------------------------------- # GLOBAL STATE & DENSE EMBEDDING CORES # --------------------------------------------------------------------------- SESSIONS: Dict[str, Dict[str, Any]] = {} EMBEDDING_MODEL: Optional[SentenceTransformer] = None PROJECTS_DF: Optional[pd.DataFrame] = None PROJECT_EMBEDDINGS: Optional[np.ndarray] = None PROJECT_TAGS_MAP: Dict[int, set] = {} # Maps dataframe row index to extracted keyword tags CSV_FILE_PATH = "student_projects.csv" GROQ_API_KEY = os.getenv("GROQ_API_KEY") groq_client = Groq(api_key=GROQ_API_KEY) if GROQ_API_KEY else None TALLY_API_KEY = os.getenv("TALLY_API_KEY") TALLY_FORM_ID = os.getenv("TALLY_FORM_ID", "0Q6NNB") VALID_THEMES = [ "AI + Transportation", "AI + Space Exploration", "AI + Healthcare", "AI + Humanities", "AI + Cybersecurity", "AI + Education", "AI + Finance", "AI + Law", "AI + Environment", "AI + Sports", "AI + Social Good", "AI + Business", "AI + Robotics", "AI + Quants", "AI + Psychology" ] # --------------------------------------------------------------------------- # DATABASE HELPERS # --------------------------------------------------------------------------- def init_db(): conn = sqlite3.connect("signals.db") cursor = conn.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS generations ( id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, mode TEXT, email TEXT, full_name TEXT, grade TEXT, future_goal TEXT, intended_major TEXT, interest_areas TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ''') cursor.execute(''' CREATE TABLE IF NOT EXISTS generated_ideas ( id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, idea_number INTEGER, title TEXT, problem_area TEXT, difficulty TEXT, feasibility_score INTEGER, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ''') conn.commit() conn.close() logger.info("Database initialized.") def save_generation(session_id: str, mode: str, email: str, full_name: str, grade: str, future_goal: str, intended_major: str, interest_areas: str): conn = sqlite3.connect("signals.db") cursor = conn.cursor() cursor.execute(''' INSERT INTO generations (session_id, mode, email, full_name, grade, future_goal, intended_major, interest_areas) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ''', (session_id, mode, email, full_name, grade, future_goal, intended_major, interest_areas)) conn.commit() conn.close() def save_ideas(session_id: str, ideas: List['ProjectIdea']): conn = sqlite3.connect("signals.db") cursor = conn.cursor() for idx, idea in enumerate(ideas, start=1): cursor.execute(''' INSERT INTO generated_ideas (session_id, idea_number, title, problem_area, difficulty, feasibility_score) VALUES (?, ?, ?, ?, ?, ?) ''', (session_id, idx, idea.title, idea.problem_area, idea.difficulty, idea.feasibility_score)) conn.commit() conn.close() # --------------------------------------------------------------------------- # LOCAL IVY ADMISSIONS PATTERN KNOWLEDGE BASE (STEP 4) # --------------------------------------------------------------------------- IVY_ADMISSIONS_DATABASE = [ { "domain": "AI + Finance / Quants", "research_style": "Empirical Quantitative Research & Macro Financial Risk Modeling", "validation_type": "Historical Out-of-Sample Backtesting & Monte Carlo Tail-Risk Stressing", "technical_depth": "Order-Book Liquidity Contagion, Temporal Graph Neural Networks", "competition_pathway": "Regeneron ISEF, Wharton Global High School Investment Competition, Davidson Fellows", "admissions_signal": "Exceptional mathematical abstraction, structural systemic risk awareness, production-grade backtesting architecture" }, { "domain": "AI + Law / Policy / Governance", "research_style": "Computational Jurisprudence & Natural Language Statutory Reasoning", "validation_type": "Ablation Studies on Statutory Interpretation & Zero-Shot Counterfactual Policy Analysis", "technical_depth": "Hierarchical Legal NLP, Retrieval-Augmented Compliance Engines, Deontic Logic Mapping", "competition_pathway": "The Concord Review, Harvard Crimson Global Essay Competition, John Locke Essay Competition", "admissions_signal": "Cross-disciplinary elite semantic reasoning, formal policy design, rigorous algorithmic governance" }, { "domain": "AI + Healthcare / Medicine", "research_style": "Translational Biomedical Informatics & Clinical Predictive Modeling", "validation_type": "Cross-Dataset Institutional Validation & Out-of-Distribution Robustness Metrics", "technical_depth": "3D Convolutional Neural Networks, Generative Synthetic Medical Cohort Architectures, Survival Analysis Models", "competition_pathway": "BioGENEius Challenge, JSHS (Junior Science and Humanities Symposium), Regeneron ISEF", "admissions_signal": "High immediate societal utility, deep understanding of stochastic data lifecycles, clinical validation compliance" }, { "domain": "AI + Aerospace / Space Exploration / Physics", "research_style": "Astrodynamics Simulation & Orbital Mechanics Anomaly Tracking", "validation_type": "Physics-Informed Neural Network (PINN) Loss Convergence Verification", "technical_depth": "Telemetry Time-Series Transformers, Multi-Body Gravitational Physics Simulation, High-Dimensional Optimization", "competition_pathway": "AIAA Student Conferences, NASA Space Apps Challenge, JSHS", "admissions_signal": "Advanced structural engineering mindset, complex multi-variable physical boundary processing" } ] # --------------------------------------------------------------------------- # PYDANTIC ROUTING SCHEMAS (PRESERVED FOR FORWARD/BACKWARD COMPATIBILITY) # --------------------------------------------------------------------------- class StudentProfile(BaseModel): email: Optional[EmailStr] = None grade: int = Field(..., ge=8, le=12) city: str interest_areas: str future_goal: str intended_major: str programming_experience: str ai_ml_experience: str programming_languages: List[str] clubs_and_activities: str toughest_project: str program_goals: str proposed_idea: Optional[str] = "" preferred_college: Optional[str] = "" session_id: Optional[str] = None class ParticipantInput(BaseModel): email: EmailStr interest_areas: Optional[str] = None grade: Optional[int] = Field(None, ge=9, le=12) proposed_idea: Optional[str] = None class BettermindGenerateRequest(BaseModel): mode: str = Field("bettermind", description="Must be exactly 'bettermind'") primary_student: ParticipantInput participants: List[ParticipantInput] = Field(default_factory=list) class SimilarProject(BaseModel): title: str student_name: str description: str github_url: str youtube_url: str project_category: str project_page: str similarity_score: float matching_reason: str class DiscoveryMetadata(BaseModel): generation_framework: str research_basis: str personalization_summary: str class ProjectIdea(BaseModel): # Original Legacy Fields (Preserved for strict frontend compatibility) id: str title: str problem_area: str guiding_question: str project_description: str why_it_matters: str why_this_fits_you: List[str] target_users: str datasets: str tools: str technical_approach: str difficulty: str feasibility_score: int feasibility_reasoning: str week1_plan: str week2_plan: str week3_plan: str final_demo: str college_application_value: str similar_projects: List[SimilarProject] = [] # New BetterMind Problem-First Discovery Engine Fields problem_context: str who_experiences_this_problem: str why_this_problem_exists: str potential_project_direction: str college_narrative: str # Trajectory-Driven Opportunity Architecture Fields student_history_connection: str class GenerateIdeasResponse(BaseModel): session_id: str discovery_metadata: DiscoveryMetadata ideas: List[ProjectIdea] class NicheDownRequest(BaseModel): session_id: str idea_id: str # --------------------------------------------------------------------------- # AUTOMATED REGEX/KEYWORD-BASED TAG EXTRACTION SERVICE # --------------------------------------------------------------------------- def extract_domain_tags(text_corpus: str) -> set: tags = set() keywords_library = { "ipo", "finance", "quant", "liquidity", "nlp", "sentiment", "portfolio", "trading", "stock", "market", "risk", "fraud", "credit", "banking", "ledger", "alpha", "healthcare", "medical", "chiral", "biosynthetic", "pathway", "diagnosis", "clinical", "imaging", "mri", "disease", "patient", "genomic", "protein", "cell", "neuro", "climate", "carbon", "nanotube", "environment", "sensor", "pollution", "noaa", "satellite", "telemetry", "orbit", "space", "propulsion", "nasa", "trajectory", "cybersecurity", "phishing", "threat", "network", "anomaly", "malware", "encryption", "robotics", "hardware", "drone", "maze", "navigation", "control", "cv", "vision", "education", "pedagogy", "curriculum", "learning", "classroom", "grading", "gnn", "cnn", "lstm", "transformer", "regression", "classification", "timeseries" } normalized_text = text_corpus.lower() for keyword in keywords_library: if keyword in normalized_text: tags.add(keyword) return tags # --------------------------------------------------------------------------- # STUDENT HISTORY ASSETS EXTRACTION SERVICE # --------------------------------------------------------------------------- def extract_student_history_assets(profile: Dict[str, Any]) -> List[str]: assets = set() mapping = { "3d cnn": "3D CNN forecasting", "cnn": "computer vision modeling", "gnn": "graph neural networks", "lstm": "time-series modeling", "transformer": "natural language transformers", "robotics": "robotics builder", "drone": "autonomous systems engineering", "hardware": "hardware prototyping", "lidar": "lidar mapping", "arduino": "arduino programming", "satellite": "satellite systems engineering", "quant": "quantitative finance research", "trading": "financial markets analysis", "finance": "financial systems architecture", "economics club": "economics club leadership", "math team": "advanced mathematical modeling", "healthcare ml": "healthcare ML pipelines", "pneumonia": "pneumonia detection modeling", "medical": "medical data analytics", "climate": "climate science research", "environment": "environmental sensing infrastructure", "game modding": "game modding environment loops", "debate": "speech and debate communications", "speech": "speech and debate communications", "founder": "startup building structures", "startup": "startup building structures", "fundraise": "community fundraising logistics", "forecast": "predictive forecasting configurations", "legal": "legal document analysis", "law": "legal reasoning systems", "contract": "contract intelligence", "contracts": "contract intelligence", "court": "judicial analytics", "judge": "judicial analytics", "judicial": "judicial outcome prediction", "litigation": "litigation analytics", "precedent": "legal precedent analysis", "case law": "legal precedent analysis", "compliance": "regulatory compliance systems", "regulation": "regulatory intelligence", "regulatory": "regulatory intelligence", "policy": "policy intelligence", "statute": "statutory analysis", "attorney": "legal workflow systems", "lawyer": "legal workflow systems", "legal document": "legal document analysis" } fields_to_analyze = [ "club_information", "toughest_project", "future_goal", "major", "program_goals", "existing_project_idea" ] for field in fields_to_analyze: text_val = str(profile.get(field, "")).lower() for check_key, asset_tag in mapping.items(): if check_key in text_val: assets.add(asset_tag) if not assets: major_clean = str(profile.get("major", "Computer Science")).lower() assets.add(f"{major_clean} processing systems") return sorted(list(assets)) def infer_student_archetype(profile: Dict[str, Any]) -> str: goal = str(profile.get("future_goal", "")).lower() major = str(profile.get("major", "")).lower() toughest = str(profile.get("toughest_project", "")).lower() idea = str(profile.get("existing_project_idea", "")).lower() combined_context = f"{goal} {major} {toughest} {idea}" if "quant" in combined_context or "high-frequency" in combined_context or "trading" in combined_context: return "Quant Researcher" if "hospital" in combined_context or "medical" in combined_context or "healthcare" in combined_context or "biomedical" in combined_context or "disease" in combined_context: return "Healthcare Innovator" if "climate" in combined_context or "environment" in combined_context or "carbon" in combined_context or "green" in combined_context or "pollution" in combined_context: return "Climate Scientist" if "robot" in combined_context or "hardware" in combined_context or "robotics" in combined_context or "drone" in combined_context or "sensor" in combined_context: return "Robotics Builder" if "policy" in combined_context or "law" in combined_context or "government" in combined_context or "ethics" in combined_context: return "Policy Thinker" if "found" in combined_context or "startup" in combined_context or "entrepreneur" in combined_context or "saas" in combined_context or "business" in combined_context: return "Founder" if "research" in combined_context or "phd" in combined_context or "academic" in combined_context or "paper" in combined_context: return "Researcher" if "teach" in combined_context or "education" in combined_context or "learn" in combined_context or "school" in combined_context: return "Education Builder" if "social" in combined_context or "good" in combined_context or "community" in combined_context or "ngo" in combined_context: return "Social Impact Builder" return "Engineer" # --------------------------------------------------------------------------- # TALLY IN-MEMORY TELEMETRY LAYERS # --------------------------------------------------------------------------- class TallyProfileService: def __init__(self): self.cache: Dict[str, Dict[str, Any]] = {} self.last_updated: Optional[datetime] = None self.lock = asyncio.Lock() def get_mock_submissions(self) -> List[Dict[str, Any]]: return [ { "submissionId": "mock_sub_1", "fields": [ {"label": "Your Full Name", "value": "Aarav Roy"}, {"label": "Your Email", "value": "aarav@example.com"}, {"label": "Your Grade", "value": "11"}, {"label": "Time Zone", "value": "EST"}, {"label": "Your City", "value": "New York"}, {"label": "Your State", "value": "NY"}, {"label": "Which school do you go to?", "value": "Stuyvesant High School"}, {"label": "Want to pursue in future", "value": "Wants to build a quantitative high-frequency trading platform and lead multi-agent fintech systems."}, {"label": "Major to pursue", "value": "Computer Science and Quantitative Economics"}, {"label": "What kind of project themes are you interested in? (min 3, max 4)", "value": "AI + Finance, AI + Quants, AI + Business"}, {"label": "Programming Exp", "value": "Advanced"}, {"label": "AI/ML Exp", "value": "Advanced"}, {"label": "Which programing language are you familiar with?", "value": "Python, C++, Rust"}, {"label": "Which subject is most challenging for you in your curriculum?", "value": "Multivariable Calculus"}, {"label": "Are you part of any club or community? if yes what is your role there, describe briefly.", "value": "Founder of Student Quant Investment Club, Captain of Math Team"}, {"label": "What is the toughest project you have worked so far?", "value": "Published a 3D CNN network architecture for modeling order-book liquidity distribution changes."}, {"label": "Great, please tell us what you'd like to explore or build?", "value": "Liquidity risk analysis and NLP tracking of underpriced tech sector IPO allocations."} ] } ] async def fetch_all_submissions(self): async with self.lock: if not TALLY_API_KEY: logger.warning("TALLY_API_KEY config missing. Initializing Sandbox Fallbacks.") submissions = self.get_mock_submissions() else: try: logger.info(f"Syncing with Tally Context Reference Form ID: {TALLY_FORM_ID}") all_fetched_submissions = [] page = 1 async with httpx.AsyncClient(timeout=15.0) as client: while True: url = f"https://api.tally.so/forms/{TALLY_FORM_ID}/submissions" params = {"filter": "completed", "page": page, "limit": 50} headers = {"Authorization": f"Bearer {TALLY_API_KEY}"} response = await client.get(url, params=params, headers=headers) if response.status_code != 200: if page == 1: all_fetched_submissions = self.get_mock_submissions() break data = response.json() submissions_chunk = data.get("submissions", []) if not submissions_chunk: break q_items = data.get("questions", []) questions_map = {q["id"]: q["title"] for q in q_items if isinstance(q, dict) and "id" in q and "title" in q} for sub in submissions_chunk: fields = [] for res in sub.get("responses", []): q_title = questions_map.get(res.get("questionId")) if q_title and res.get("answer") is not None: fields.append({"label": q_title, "value": res.get("answer")}) all_fetched_submissions.append({"submissionId": sub.get("id", "N/A"), "fields": fields}) if not data.get("hasMore") or page > 30: break page += 1 submissions = all_fetched_submissions except Exception as e: logger.error(f"Fallback executed due to Tally API error: {str(e)}") submissions = self.get_mock_submissions() new_cache = {} for item in submissions: normalized = self._normalize_fields(item.get("fields", [])) if normalized.get("email"): new_cache[normalized["email"]] = normalized self.cache = new_cache self.last_updated = datetime.utcnow() logger.info(f"Tally synchronization complete. Pool size: {len(self.cache)} profiles.") def _normalize_fields(self, fields: List[Dict[str, Any]]) -> Dict[str, Any]: raw_map = {f.get("label", "").lower().strip(): f.get("value") for f in fields if f.get("label")} extracted = { "full_name": raw_map.get("your full name", ""), "email": raw_map.get("your email", ""), "grade": raw_map.get("your grade", raw_map.get("grade", "")), "timezone": raw_map.get("time zone", ""), "city": raw_map.get("your city", ""), "state": raw_map.get("your state", ""), "school": raw_map.get("which school do you go to?", ""), "future_goal": raw_map.get("want to pursue in future", ""), "major": raw_map.get("major to pursue", ""), "challenging_subject": raw_map.get("which subject is most challenging for you in your curriculum?", ""), "project_themes": raw_map.get("what kind of project themes are you interested in? (min 3, max 4)", []), "programming_experience": raw_map.get("programming exp", 0), "ai_ml_experience": raw_map.get("ai/ml exp", 0), "programming_languages": raw_map.get("which programing language are you familiar with?", []), "program_goals": raw_map.get("what are you hoping to gain from this program? are there specific skills, projects, or experiences you’re most excited about?", ""), "club_information": raw_map.get("are you part of any club or community? if yes what is your role there, describe briefly.", ""), "toughest_project": raw_map.get("what is the toughest project you have worked so far?", ""), "has_project_idea": raw_map.get("do you have an idea on what you'd like to build during the program", []), "existing_project_idea": raw_map.get("great, please tell us what you'd like to explore or build?", ""), } if isinstance(extracted["email"], str): extracted["email"] = extracted["email"].lower().strip() if isinstance(extracted["project_themes"], str): extracted["project_themes"] = [t.strip() for t in extracted["project_themes"].split(",") if t.strip()] elif not isinstance(extracted["project_themes"], list): extracted["project_themes"] = [] extracted["project_themes"] = [t for t in extracted["project_themes"] if t in VALID_THEMES] return extracted def lookup_student(self, email: str) -> Optional[Dict[str, Any]]: return self.cache.get(email.lower().strip()) TALLY_SERVICE = TallyProfileService() async def cache_refresh_scheduler(): while True: await asyncio.sleep(1800) try: await TALLY_SERVICE.fetch_all_submissions() except Exception as e: logger.error(f"Error inside scheduler routine: {str(e)}") BANNED_PATTERNS = [ "stock prediction", "stock predictor", "portfolio optimizer", "portfolio optimization", "contract review", "contract analyzer", "legal chatbot", "document summarizer", "resume screener", "sentiment analysis", "disease classifier", "house price prediction", "fake news detection", "legal document analysis", "legal document analyzer", "contract intelligence", "intellectual property protection", "regulatory compliance engine", ] # --------------------------------------------------------------------------- # STARTUP SEQUENCING & VECTOR SYNC # --------------------------------------------------------------------------- @app.on_event("startup") async def startup_pipeline_sequence(): global EMBEDDING_MODEL, PROJECTS_DF, PROJECT_EMBEDDINGS, PROJECT_TAGS_MAP init_db() logger.info("Initializing Dense Vector Architecture Layer (all-MiniLM-L6-v2)...") EMBEDDING_MODEL = SentenceTransformer("all-MiniLM-L6-v2") if not os.path.exists(CSV_FILE_PATH): mock_data = { "Title": ["ChiralAI", "EcoSense Nano", "AlphaSpread GNN", "DeFi Risk Engine"], "Category": ["Healthcare", "Environment", "Finance", "Quants"], "Description": [ "AI model predicting biosynthetic pathways for hard-to-make chiral molecules used in medicine.", "Low-cost carbon nanotube sensor array mapping particulate pollution vector changes across urban centers.", "Temporal Graph Neural Network modeling liquidity cascades and risk contagion inside order-books.", "Automated multi-agent execution pipeline simulating decentralized liquidation parameters under historical tail-risk scenarios." ], "StudentName": ["Alexei Manuel", "Sarah Jenkins", "Ethan Zhao", "Rohan Mehta"], "Github URL": ["https://github.com/aalxi/ChiralAI", "https://github.com/sj/ecosense", "https://github.com/ez/alphaspread", "https://github.com/rm/defirisk"], "Youtube URL": ["https://youtube.com/watch?v=mock1", "https://youtube.com/watch?v=mock2", "https://youtube.com/watch?v=mock3", "https://youtube.com/watch?v=mock4"], "Project Category": ["AI + Healthcare", "Hardware + Climate", "AI + Finance", "AI + Quants"] } PROJECTS_DF = pd.DataFrame(mock_data) PROJECTS_DF.to_csv(CSV_FILE_PATH, index=False) else: PROJECTS_DF = pd.read_csv(CSV_FILE_PATH) for col in PROJECTS_DF.columns: PROJECTS_DF[col] = PROJECTS_DF[col].fillna("").astype(str).str.strip() logger.info("Building enriched multi-dimensional text anchors and tag indices for benchmarks...") enriched_docs = [] PROJECT_TAGS_MAP.clear() for idx, row in PROJECTS_DF.iterrows(): title = row.get("Title", "") desc = row.get("Description", "") cat = row.get("Project Category", "") category = row.get("Category", "") dense_doc = ( f"TITLE: {title} | DOMAIN: {cat} | SECTOR: {category}\n" f"CORE BLUEPRINT DESCRIPTION: {desc}\n" ) enriched_docs.append(dense_doc) PROJECTS_DF.at[idx, "search_doc"] = dense_doc combined_metadata_text = f"{title} {desc} {cat} {category}" PROJECT_TAGS_MAP[idx] = extract_domain_tags(combined_metadata_text) logger.info("Generating corpus vector matrix space...") PROJECT_EMBEDDINGS = EMBEDDING_MODEL.encode(enriched_docs, convert_to_numpy=True) await TALLY_SERVICE.fetch_all_submissions() asyncio.create_task(cache_refresh_scheduler()) # --------------------------------------------------------------------------- # HYBRID RETRIEVAL MATCH ENGINE (USED ONLY FOR SIMILAR_PROJECTS RETRIEVAL) # --------------------------------------------------------------------------- def execute_hybrid_retrieval(query_context: str, student_info: Dict[str, Any], top_k: int = 2) -> List[Dict[str, Any]]: if PROJECTS_DF is None or PROJECTS_DF.empty or EMBEDDING_MODEL is None or PROJECT_EMBEDDINGS is None: return [] target_themes = [t.lower().strip() for t in student_info.get("project_themes", [])] if not target_themes and student_info.get("declared_themes"): target_themes = [t.lower().strip() for t in str(student_info.get("declared_themes")).split(",")] opportunity_tags = extract_domain_tags(query_context) history_assets = [str(a).lower() for a in student_info.get("history_assets", student_info.get("group_history_assets", []))] query_vec = EMBEDDING_MODEL.encode([query_context], convert_to_numpy=True) scores = np.dot(PROJECT_EMBEDDINGS, query_vec.T).flatten() norms = np.linalg.norm(PROJECT_EMBEDDINGS, axis=1) * np.linalg.norm(query_vec) semantic_sims = np.divide(scores, norms, out=np.zeros_like(scores), where=norms != 0) candidate_matches = [] for idx, row in PROJECTS_DF.iterrows(): row_cat = str(row.get("Project Category", "")).lower().strip() row_sector = str(row.get("Category", "")).lower().strip() row_desc = str(row.get("Description", "")).lower().strip() row_title = str(row.get("Title", "")).lower().strip() combined_row_text = f"{row_cat} {row_sector} {row_desc} {row_title}" category_match = 0.0 for theme in target_themes: if theme in row_cat or theme in row_sector or row_cat in theme: category_match = 1.0 break row_tags = PROJECT_TAGS_MAP.get(idx, set()) tag_overlap_count = len(opportunity_tags.intersection(row_tags)) asset_overlap_count = 0 for asset in history_assets: if asset in combined_row_text: asset_overlap_count += 1 total_overlap = tag_overlap_count + asset_overlap_count tag_overlap_score = min(1.0, total_overlap / 5.0) if total_overlap > 0 else 0.0 sem_score = max(0.0, min(1.0, float(semantic_sims[idx]))) final_score = (0.45 * category_match) + (0.35 * tag_overlap_score) + (0.20 * sem_score) if final_score < 0.25: continue matched_shared_keywords = list(opportunity_tags.intersection(row_tags)) if matched_shared_keywords: reason = f"Matched via overlap involving {', '.join(matched_shared_keywords[:3])} within the {row.get('Project Category')} domain." else: reason = f"Matched structural pipeline alignment inside the {row.get('Project Category')} track." candidate_matches.append({ "title": row.get("Title"), "student_name": row.get("StudentName"), "description": row.get("Description"), "github_url": row.get("Github URL"), "youtube_url": row.get("Youtube URL"), "project_category": row.get("Project Category"), "project_page": f"https://bettermindlabs.com/projects/{str(row.get('Title')).lower().replace(' ', '-')}", "similarity_score": round(final_score, 3), "matching_reason": reason }) candidate_matches.sort(key=lambda x: x["similarity_score"], reverse=True) return candidate_matches[:top_k] def is_too_similar(idea_text, student_info): matches = execute_hybrid_retrieval( idea_text, student_info, top_k=1 ) if not matches: return False score = matches[0]["similarity_score"] return score > 0.85 # --------------------------------------------------------------------------- # COHORT INTERSECTION GENERATOR & INDEPENDENT PERSONALIZATION PIPELINE # --------------------------------------------------------------------------- def resolve_and_score_profile(inp: ParticipantInput) -> Dict[str, Any]: email = inp.email.lower().strip() tally = TALLY_SERVICE.lookup_student(email) or {} resolved = { "full_name": tally.get("full_name", inp.email.split("@")[0].capitalize()), "email": email, "grade": str(inp.grade) if inp.grade else tally.get("grade", "11"), "city": tally.get("city", "Unknown"), "future_goal": tally.get("future_goal", ""), "major": tally.get("major", "Computer Science"), "project_themes": tally.get("project_themes", []), "programming_experience": tally.get("programming_experience", "Intermediate"), "ai_ml_experience": tally.get("ai_ml_experience", "Beginner"), "programming_languages": tally.get("programming_languages", ""), "club_information": tally.get("club_information", ""), "program_goals": tally.get("program_goals", ""), "toughest_project": tally.get("toughest_project", ""), "existing_project_idea": inp.proposed_idea or tally.get("existing_project_idea", "") } if not tally: if inp.interest_areas: manual_themes = [t.strip() for t in inp.interest_areas.split(",") if t.strip()] resolved["project_themes"] = [t for t in manual_themes if t in VALID_THEMES] resolved["toughest_project"] = resolved["toughest_project"] or f"Advanced engineering build featuring {inp.interest_areas or 'applied machine learning software tools'}" resolved["future_goal"] = resolved["future_goal"] or f"Research and system deployment inside the {inp.interest_areas or 'computational sciences'} industry" resolved["club_information"] = resolved["club_information"] or "Founder of regional computing group and local engineering builder circles" resolved["program_goals"] = resolved["program_goals"] or "Scale non-trivial predictive pipelines targeting production-grade real-world deployment challenges" if inp.interest_areas: manual = [t.strip() for t in inp.interest_areas.split(",") if t.strip()] resolved["project_themes"] = list(set([t for t in manual if t in VALID_THEMES] + resolved["project_themes"])) resolved["archetype"] = infer_student_archetype(resolved) resolved["history_assets"] = extract_student_history_assets(resolved) return resolved def compile_identity_graph(profiles: List[Dict[str, Any]]) -> Dict[str, Any]: all_themes = [t for p in profiles for t in p["project_themes"]] unique_themes = list(set(all_themes)) shared_interests = list(set.intersection(*map(set, [p["project_themes"] for p in profiles if p["project_themes"]]))) if len(profiles) > 1 else unique_themes all_history_assets = [] for p in profiles: all_history_assets.extend(p.get("history_assets", [])) group_history_assets = list(set(all_history_assets)) roles = ["Data Engineering & Infrastructure", "Algorithmic Modeling & Core Training", "Frontend Prototyping & Interface Loops"] role_split = {} for idx, p in enumerate(profiles): assigned_role = roles[idx % len(roles)] role_split[p["full_name"]] = f"Assigned: {assigned_role} (Archetype: {p['archetype']})" group_matrix_breakdown = [] for p in profiles: group_matrix_breakdown.append({ "student_name": p["full_name"], "archetype": p["archetype"], "strongest_project": p["toughest_project"], "strongest_skill": f"Languages: {p['programming_languages']} (AI/ML Exp: {p['ai_ml_experience']})", "future_goal": p["future_goal"], "leadership_experience": p["club_information"], "project_themes": p["project_themes"], "intended_major": p["major"], "history_assets": p.get("history_assets", []) }) return { "shared_interests": shared_interests if shared_interests else ["AI + General Engineering"], "complementary_skills": [f"{p['full_name']}: {p['programming_languages']} (Prog: {p['programming_experience']}, AI: {p['ai_ml_experience']})" for p in profiles], "collaboration_strengths": "High balance across complementary engineering archetypes tracking structural crossovers.", "recommended_role_split": role_split, "combined_interests": unique_themes, "archetypes": [p["archetype"] for p in profiles], "individual_profiles": profiles, "new_group_analysis_matrix": group_matrix_breakdown, "group_history_assets": group_history_assets } # --------------------------------------------------------------------------- # REFACTORED MASTER GENERATION PROMPT ENGINE (STEPS 1, 2, 3, 4, 5, 6) # --------------------------------------------------------------------------- def generate_master_reasoning_prompt( student_matrix: str, historical_pool: str, group_rules: str ) -> str: ivy_db_string = json.dumps(IVY_ADMISSIONS_DATABASE, indent=2) return f""" You are the Principal AI Systems Architect and Elite Research Mentor at BetterMind Labs. Your objective is to run an internal 6-step architecture discovery pipeline to turn raw high-school profile vectors into world-class, rigorous, publication-grade academic computer science research configurations. FOUNDER ARCHETYPE DETECTION If student has: - startup experience - DECA - BPA - entrepreneurship programs - fundraising - investment clubs Prefer: - market intelligence systems - decision support systems - workflow automation - behavioral economics - financial infrastructure - investor tooling - resource allocation systems Avoid: - generic scientific simulations - generic classifiers - generic prediction tools unless strongly supported by prior evidence. --- STEP 1: STUDENT TRAJECTORY ENGINE --- Your primary objective is NOT to generate impressive projects. Your primary objective is to generate projects that naturally emerge from the student's demonstrated trajectory. Use the following weighting: 35% → future_goal 20% → intended_major 15% → toughest_project 10% → clubs_and_communities 10% → programming_experience 5% → ai_ml_experience 3% → proposed_idea 2% → project_themes --- FUTURE GOAL ALIGNMENT TEST --- Every idea must emerge from the intersection of: 1. Future Goal 2. Intended Major 3. Demonstrated Evidence 4. Interest Areas Formula: Project = Future Goal × Major × Evidence × Interests Projects that only satisfy Future Goal or only satisfy Interests are invalid. INTERSECTION REQUIREMENT Every idea must explicitly combine: A) one interest area AND B) the future goal Examples: Corporate Lawyer + Finance → Securities regulation → M&A due diligence → Compliance monitoring Corporate Lawyer + Space → Space treaty analysis → Satellite liability systems → Orbital governance Corporate Lawyer + AI → Regulatory benchmarking → Policy simulation If an idea cannot be expressed as: Future Goal × Interest REJECT. For each idea internally answer: 1. What skill does this teach? 2. Why is this skill useful for the student's future_goal? 3. Why is this useful for their intended_major? If either answer is weak: REJECT THE IDEA. NON-NEGOTIABLE RULE: Every generated project must directly improve the student's preparation for: Projects unrelated to this career trajectory are invalid. --- CAPABILITY CALIBRATION ENGINE --- Programming Experience and AI/ML Experience must directly affect project complexity. Scale: 1-3: Beginner 4-6: Intermediate 7-8: Advanced 9-10: Exceptional Rules: Programming <= 3: No distributed systems No custom ML architectures No multi-agent systems Programming 4-6: Standard ML pipelines allowed Simple simulations allowed Programming 7-8: Advanced forecasting Optimization systems Multi-agent architectures Programming 9-10: Research-grade architectures Novel benchmarks Publication-grade systems AI/ML Experience must independently constrain model complexity. IMPORTANT: Project themes are weak signals. Demonstrated evidence is a strong signal. Example: Weak signal: AI + Finance Strong signal: Published research paper on financial forecasting Weak signal: AI + Robotics Strong signal: Built LiDAR system using Arduino Always prioritize demonstrated evidence. Output internally: trajectory_analysis = {{ primary_domain, secondary_domain, exploratory_domain, demonstrated_strengths, execution_capacity, builder_archetype, likely_college_narrative }} --- EVIDENCE-FIRST REASONING GATE --- Before generating ideas, identify: 1. Demonstrated Achievements 2. Demonstrated Skills 3. Demonstrated Communities 4. Demonstrated Leadership 5. Demonstrated Domain Knowledge Generate: student_evidence_profile = {{ " built_things", "led_things", "researched_thing", "competed_in", "domain_exposure" }} Projects MUST emerge primarily from demonstrated evidence. Interest areas may only influence idea selection after evidence analysis is complete. TRAJECTORY AUTHENTICITY TEST For every idea: Explain internally: "What evidence from this student's history makes this project believable?" If the answer is weaker than 2 concrete pieces of evidence: REJECT the idea. --- STEP 3: OPPORTUNITY DISCOVERY ENGINE --- Generate 30 opportunities. Classify: 10 operational inefficiencies 10 underserved user groups 10 emerging technology shifts Score each: - trajectory alignment - novelty - buildability in 8-12 weeks - admissions value - real-world usefulness Projects MUST emerge from the highest scoring opportunities. Reject opportunities requiring: - PhD-level domain expertise - Proprietary datasets - Research labs - Hardware unavailable to high school students Favor: - overlooked workflows - niche communities - underserved markets - operational bottlenecks - emerging technologies --- STEP 4: IVY ADMISSIONS PATTERN ENGINE --- Cross-reference your problem concepts against this local Ivy Project Knowledge Base: {ivy_db_string} For each project, compute an internal "admissions_strength_score" (1-10) based on: - Novel Research Contribution - External Validation/Competition Potential - Technical Pipeline Depth - Longitudinal Portfolio Growth Value Incorporate this explicitly inside the fields. --- STEP 5: GENERIC PROJECT REJECTION FILTER --- Immediately reject: - stock predictor - portfolio optimizer - chatbot - legal chatbot - resume screener - contract analyzer - disease classifier - document summarizer - recommendation engine - AI tutor - sentiment analyzer unless: 1. a novel dataset is created OR 2. a benchmark is created OR 3. a new evaluation framework is introduced OR 4. a previously unsolved workflow problem is addressed The existence of AI alone does not make a project innovative. --- STEP 5.5: DIFFERENTIATION TEST --- For each idea ask: "Could 1000 other students generate this idea from the same interests?" If YES: REJECT. For each accepted idea: The project must contain at least TWO of: - unique community - unique workflow - unique dataset - unique stakeholder - unique deployment environment - unique evaluation method The goal is: "Of course THIS student built this." not "Any AI student could build this." --- STEP 6: GENERATION SCHEMA & CONTRACT REQUIREMENTS --- Return exclusively a valid, parseable JSON block matching the structure below. Do not wrap with conversational text. Ensure all generation parameters are seamlessly injected into the exact schema contract fields as detailed below. DIVERSITY CONSTRAINT IDEA PORTFOLIO DIVERSIFICATION ENGINE Idea 1: Career-Optimized Most aligned with future_goal. Idea 2: Major-Optimized Most aligned with intended_major. Idea 3: Wildcard Adjacent Unexpected but credible opportunity combining future_goal + interests. The three ideas must advance the SAME future career trajectory. They may belong to different industries only if they strengthen the student's future_goal. No two ideas may solve similar problems. Before finalizing each idea: Explain internally in one sentence: Why THIS student would realistically choose to build this. If the explanation is weak, discard the idea. Return EXACTLY 3 ideas. If fewer than 3 ideas are returned, the response is invalid. CRITICAL JSON REQUIREMENT ideas MUST contain EXACTLY 3 objects. Valid: {{ "ideas": [ {{...}}, {{...}}, {{...}} ] }} Invalid: {{ "ideas": [ {{...}} ] }} Invalid: {{ "ideas": [ {{...}}, {{...}} ] }} {{ "ideas": [ {{ "title": "[BrandName: Specific Highly Professional Research Subtitle Formulary]", "problem_area": "[Granular, observable real-world problem statement detailing systematic friction points]", "guiding_question": "[The Core Research Question: Precise testable inquiry evaluating explicit parameters and system boundaries]", "project_description": "[Comprehensive overview mapping why this emerges and how your system isolates it]", "why_it_matters": "[Systemic importance to Stakeholders and specialized ecosystem targets]", "why_this_fits_you": [ "Alignment point 1 mapping to your Step 1 Trajectory Asset...", "Alignment point 2 mapping to your computed Archetype..." ], "student_history_connection": "[Detailed trajectory-driven narrative proving why this is the logical next chapter of your portfolio based on toughest_project milestones and history_assets. For group configurations, detail the exact parallel workload split proving why every participant owns at least 20% of engineering operations and which specific history asset of theirs is integrated]", "target_users": "[Target Stakeholders: Explicit professional personas experiencing this systematic friction]", "datasets": "[Data Source: Explicitly name specific, verified high-fidelity public or professional open repositories, e.g., SEC EDGAR, MIMIC-IV, FRED, NOAA, NASA Open Data. Never use vague terms like Kaggle dataset without specifying the exact title]", "tools": "Python, PyTorch, Streamlit, Pandas, Scikit-Learn", "technical_approach": "[Technical Pipeline & Validation Strategy: Detailed step-by-step pipeline workflow mapping ingest, mathematical processing, modeling, and rigorous out-of-sample/cross-dataset validation strategies]", "difficulty": "Advanced", "feasibility_score": 9, "feasibility_reasoning": "[Clear justification verifying complex backend implementation execution within 3-4 weeks framework bounds]", "week1_plan": "[Data fetching pipeline setups, data cleaning loops, and out-of-bounds check architectures]", "week2_plan": "[Core model training, algorithmic parameter optimization, validation metrics setups]", "week3_plan": "[UI validation dashboard creation using Streamlit, testing real-time manual telemetry parameter changes]", "final_demo": "[Interactive system demo configuration with explicit widgets to toggle inputs and visualize live model convergence/inference]", "college_application_value": "[Competition & Publication Blueprint: Explicitly detail Potential Competition Pathways (e.g., ISEF, JSHS), Potential Publication Targets, Ideal External University Mentor Types to reach out to, and the calculated Admissions Strength Score with justification]", "problem_context": "[Deep overarching systemic overview of the underlying industry friction sphere]", "who_experiences_this_problem": "[Detailed breakdown of specialized market stakeholders impacted]", "why_this_problem_exists": "[Structural, technical, or economic root causes why this remains unresolved by current standard wrappers]", "potential_project_direction": "[Alternative deployment framework variant description]", "college_narrative": "[Admissions Positioning Narrative: Counselor-ready positioning narrative text explaining why a top-tier admissions officer values this project, the exact unique intellectual theme validated, and longitudinal growth options. MUST BE A MINIMUM OF 120 WORDS.]" }} ] }} --- ACTIVE STUDENT MATRICES --- {student_matrix} --- HISTORICAL REFERENCE POOL FOR SIMILARITY VALIDATION --- {historical_pool} --- TRACK CONFIGURATION RULES --- {group_rules} """ def build_trajectory_analysis(student_info): themes = student_info.get("project_themes", []) assets = " ".join(student_info.get("history_assets", [])).lower() toughest = str(student_info.get("toughest_project", "")).lower() idea = str(student_info.get("existing_project_idea", "")).lower() combined = f"{assets} {toughest} {idea}" primary = None secondary = None exploratory = None if any(x in combined for x in [ "legal", "contract", "law", "judicial", "compliance", "regulation" ]): primary = "AI + Law" if any(x in combined for x in [ "finance", "portfolio", "liquidity", "trading", "risk" ]): secondary = "AI + Finance" if any(x in combined for x in [ "space", "satellite", "orbit", "nasa" ]): exploratory = "AI + Space Exploration" remaining = [t for t in themes if t not in [primary, secondary, exploratory]] if not primary and remaining: primary = remaining.pop(0) if not secondary and remaining: secondary = remaining.pop(0) if not exploratory and remaining: exploratory = remaining.pop(0) return { "primary_domain": primary, "secondary_domain": secondary, "exploratory_domain": exploratory, "history_assets": student_info.get("history_assets", []), "archetype": student_info.get("archetype"), } # --------------------------------------------------------------------------- # CORE APPLICATION ROUTING INFRASTRUCTURE # --------------------------------------------------------------------------- @app.get("/") def health_check(): return {"status": "running", "active_records": len(TALLY_SERVICE.cache)} @app.post("/generate", response_model=GenerateIdeasResponse) def generate_ideas_external(profile: StudentProfile): if not groq_client or not EMBEDDING_MODEL: raise HTTPException(status_code=503, detail="AI Compute Engine configuration missing.") try: tally = TALLY_SERVICE.lookup_student(profile.email) or {} if profile.email: tally = TALLY_SERVICE.lookup_student(profile.email) or {} # Step 7: Combine fields into single tracking format student_info = { "full_name": ( tally.get("full_name") or ( profile.email.split("@")[0].capitalize() if profile.email else "External Student" ) ), "email": ( profile.email.lower().strip() if profile.email else "" ), "grade": profile.grade, "city": profile.city, "declared_themes": profile.interest_areas, "project_themes": [ t.strip() for t in profile.interest_areas.split(",") if t.strip() ], "future_goal": profile.future_goal, "major": profile.intended_major, "intended_major": profile.intended_major, "programming_experience": profile.programming_experience, "ai_ml_experience": profile.ai_ml_experience, "programming_languages": ", ".join(profile.programming_languages), "club_information": profile.clubs_and_activities, "program_goals": profile.program_goals, "toughest_project": profile.toughest_project, "existing_project_idea": profile.proposed_idea or "", "proposed_idea": profile.proposed_idea or "", "preferred_college": profile.preferred_college or "" } if profile.interest_areas: manual_themes = [t.strip() for t in profile.interest_areas.split(",") if t.strip()] seen = set() ordered = [] for t in manual_themes + student_info["project_themes"]: if t not in seen: seen.add(t) ordered.append(t) student_info["project_themes"] = ordered student_info["history_assets"] = extract_student_history_assets(student_info) student_info["archetype"] = infer_student_archetype(student_info) trajectory_analysis = build_trajectory_analysis(student_info) student_info["trajectory_analysis"] = trajectory_analysis search_query = f""" Interest Areas: {profile.interest_areas} Toughest Project: {student_info['toughest_project']} Future Goal: {student_info['future_goal']} Existing Project Idea: {student_info['existing_project_idea']} History Assets: {', '.join(student_info['history_assets'])} """ # Step 8: Embedding search is kept strictly for providing the similar_projects nodes initial_pool = execute_hybrid_retrieval(search_query, student_info, top_k=2) formatted_pool_text = "\n".join([ f"- Title: {p['title']} | Category: {p['project_category']} | Description: {p['description']}" for p in initial_pool ]) if initial_pool else "No directly matching historical baselines." sys_prompt = generate_master_reasoning_prompt( student_matrix=json.dumps(student_info, indent=2), historical_pool=formatted_pool_text, group_rules=""" Individual Student Mode Matrix Configuration: Enforce continuous trajectory matching layers via Step 1-6 analysis loops. All 3 opportunities must remain structurally coherent with the trajectory analysis profile. """ ) response = groq_client.chat.completions.create( model="llama-3.3-70b-versatile", messages=[{"role": "user", "content": sys_prompt}], response_format={"type": "json_object"}, temperature=0.30, timeout=30.0 ) def violates_blacklist(idea): text = ( idea.get("title", "") + " " + idea.get("problem_area", "") + " " + idea.get("project_description", "") ).lower() return any( title.lower().strip() == banned for banned in BANNED_PATTERNS ) parsed_output = json.loads(response.choices[0].message.content) raw_ideas = parsed_output.get("ideas", []) logger.info( f"LLM generated {len(raw_ideas)} ideas" ) logger.info(f"Before filtering: {len(raw_ideas)}") filtered = [] for idx, idea in enumerate(raw_ideas): title = idea.get("title","") if violates_blacklist(idea): logger.info(f"BLACKLISTED: {title}") continue idea_text = f""" {idea.get('title')} {idea.get('problem_area')} {idea.get('project_description')} """ matches = execute_hybrid_retrieval( idea_text, student_info, top_k=1 ) score = 0 if matches: score = matches[0]["similarity_score"] logger.info( f"IDEA {idx+1}: {title} | similarity={score}" ) if score > 0.85: logger.info( f"REMOVED FOR SIMILARITY: {title}" ) continue filtered.append(idea) logger.info( f"After filtering: {len(filtered)}" ) raw_ideas = filtered processed_ideas: List[ProjectIdea] = [] for item in raw_ideas[:3]: generated_opportunity_context = f"{item.get('title')} {item.get('problem_area')} {item.get('project_description')}" refined_matched_pool = execute_hybrid_retrieval(generated_opportunity_context, student_info, top_k=2) similar_projects_list = [] for p in refined_matched_pool: similar_projects_list.append(SimilarProject( title=p["title"], student_name=p["student_name"], description=p["description"], github_url=p["github_url"], youtube_url=p["youtube_url"], project_category=p["project_category"], project_page=p["project_page"], similarity_score=p["similarity_score"], matching_reason=p["matching_reason"] )) processed_ideas.append(ProjectIdea( id=f"idea_{uuid.uuid4().hex[:8]}", title=item.get("title", "Advanced Research Discovery Node"), problem_area=item.get("problem_area", "Localized real-world data discrepancies."), guiding_question=item.get("guiding_question", "Inquiry exploring specific system optimizations."), project_description=item.get("project_description", "Problem analysis and targeted engineering loops."), why_it_matters=item.get("why_it_matters", "Reduces friction over critical system parameters."), why_this_fits_you=item.get("why_this_fits_you", [f"Aligned with your trajectory framework choice."]), student_history_connection=item.get("student_history_connection", "This opportunity builds directly on top of your previous technical work."), target_users=item.get("target_users", "Industry specific research networks"), datasets=item.get("datasets", "SEC EDGAR Reference Portal"), tools=item.get("tools", "Python, Streamlit, Pandas, Scikit-Learn"), technical_approach=item.get("technical_approach", "Data cleansing, processing pipeline, validation loops"), difficulty=item.get("difficulty", "Advanced"), feasibility_score=max(1, min(10, int(item.get("feasibility_score", 9)))), feasibility_reasoning=item.get("feasibility_reasoning", "Achievable within standard program bounds."), week1_plan=item.get("week1_plan", "Inference mapping and pipeline checks."), week2_plan=item.get("week2_plan", "Model tuning and architecture construction."), week3_plan=item.get("week3_plan", "Streamlit UI configuration loops."), final_demo=item.get("final_demo", "Interactive visualization performance monitoring setup."), college_application_value=item.get("college_application_value", "Demonstrates elite intellectual traction."), similar_projects=similar_projects_list, problem_context=item.get("problem_context", "Systemic market friction parameters."), who_experiences_this_problem=item.get("who_experiences_this_problem", "Ecosystem stakeholders."), why_this_problem_exists=item.get("why_this_problem_exists", "Lack of granular structured baseline metrics."), potential_project_direction=item.get("potential_project_direction", "Specialized Model Deployment Dashboard"), college_narrative=item.get("college_narrative", "Counselor positioning narrative detailing unique tracking story components.") )) session_id = f"sess_{uuid.uuid4().hex[:12]}" SESSIONS[session_id] = { "source": "individual", "archetype": student_info["archetype"], "profile": profile.model_dump(), "ideas": [i.model_dump() for i in processed_ideas], "niche_ideas": [] } try: save_generation( session_id=session_id, mode="external", email=student_info.get("email", ""), full_name=student_info.get("full_name", ""), grade=str(student_info.get("grade", "")), future_goal=student_info.get("future_goal", ""), intended_major=student_info.get("intended_major", ""), interest_areas=", ".join(student_info.get("project_themes", [])) ) logger.info(f"Generation saved: {session_id}") save_ideas(session_id, processed_ideas) logger.info(f"Ideas saved: {session_id}") except Exception as db_e: logger.error(f"Failed to save to database: {db_e}") discovery_metadata = DiscoveryMetadata( generation_framework="BetterMind Labs Trajectory Problem Discovery Engine v4.2", research_basis="Synthesized across trajectory discovery vectors matching Ivy-grade admissions frameworks.", personalization_summary=f"Overhauled personalization utilizing continuous analytical trajectory tracking anchors and advanced research pipelines." ) return GenerateIdeasResponse(session_id=session_id, discovery_metadata=discovery_metadata, ideas=processed_ideas) except Exception as e: logger.error(f"Critical execution error inside /generate pipeline: {str(e)}") raise HTTPException(status_code=500, detail=str(e)) @app.post("/generate-bml", response_model=GenerateIdeasResponse) def generate_ideas_bettermind(request: BettermindGenerateRequest): if request.mode != "bettermind": raise HTTPException(status_code=400, detail="Invalid application execution mode parameter.") if len(request.participants) + 1 > 3: raise HTTPException(status_code=400, detail="Group configuration limits exceeded (Max 3 members).") if not groq_client or not EMBEDDING_MODEL: raise HTTPException(status_code=503, detail="Required Core Model configurations unassigned.") primary_email = request.primary_student.email.lower().strip() if not TALLY_SERVICE.lookup_student(primary_email): logger.info(f"Student not found: {primary_email}") raise HTTPException(status_code=404, detail="Student not found in BetterMind Labs induction database.") logger.info(f"Student validated: {primary_email}") for p in request.participants: p_email = p.email.lower().strip() if not TALLY_SERVICE.lookup_student(p_email): logger.info(f"Student not found: {p_email}") raise HTTPException(status_code=404, detail=f"Student not found: {p_email}") logger.info(f"Student validated: {p_email}") try: resolved_profiles = [resolve_and_score_profile(request.primary_student)] for p in request.participants: resolved_profiles.append(resolve_and_score_profile(p)) group_identity_graph = compile_identity_graph(resolved_profiles) search_query = " ".join(group_identity_graph.get("combined_interests", [])) initial_pool = execute_hybrid_retrieval(search_query, group_identity_graph, top_k=2) formatted_pool_text = "\n".join([ f"- Title: {p['title']} | Category: {p['project_category']} | Description: {p['description']}" for p in initial_pool ]) if initial_pool else "No direct group benchmarks available." sys_prompt = generate_master_reasoning_prompt( student_matrix=json.dumps(group_identity_graph, indent=2), historical_pool=formatted_pool_text, group_rules=( "Group Mode Cluster Configuration: Synthesize balanced collaborative framework opportunities using Step 1-6 pipelines. " "Every generated opportunity MUST reference at least one historical asset from group_history_assets for every single student. " "Ensure separate execution sub-tasks mapping directly to the explicit recommended_role_split structures. " "Every teammate must actively drive a critical operational or backend processing segment accounting for at least 20% of pipeline code complexity." ) ) response = groq_client.chat.completions.create( model="llama-3.3-70b-versatile", messages=[{"role": "user", "content": sys_prompt}], response_format={"type": "json_object"}, temperature=0.30, timeout=30.0 ) parsed_output = json.loads(response.choices[0].message.content) raw_ideas = parsed_output.get("ideas", []) processed_ideas: List[ProjectIdea] = [] for item in raw_ideas[:3]: generated_opportunity_context = f"{item.get('title')} {item.get('problem_area')} {item.get('project_description')}" refined_matched_pool = execute_hybrid_retrieval(generated_opportunity_context, group_identity_graph, top_k=2) similar_projects_list = [] for p in refined_matched_pool: similar_projects_list.append(SimilarProject( title=p["title"], student_name=p["student_name"], description=p["description"], github_url=p["github_url"], youtube_url=p["youtube_url"], project_category=p["project_category"], project_page=p["project_page"], similarity_score=p["similarity_score"], matching_reason=p["matching_reason"] )) fits_you_summary = item.get("why_this_fits_you", []) fits_you_summary.append("Optimized role division split mapped cleanly across teammate skill distribution parameters.") processed_ideas.append(ProjectIdea( id=f"idea_{uuid.uuid4().hex[:8]}", title=item.get("title", "Synthesized Core Group Concept"), problem_area=item.get("problem_area", "Shared multi-variant problem space friction bounds."), guiding_question=item.get("guiding_question", "Unified testable group execution inquiries."), project_description=item.get("project_description", "Collaborative modular solution implementation parameters."), why_it_matters=item.get("why_it_matters", "Establishes systematic framework controls."), why_this_fits_you=fits_you_summary, student_history_connection=item.get("student_history_connection", "This collaborative project synthesizes the individual technical backgrounds of the cohort members."), target_users=item.get("target_users", "Target ecosystem user bases"), datasets=item.get("datasets", "NOAA Integrated Global Meteorological Repository"), tools=item.get("tools", "Python, Streamlit, Git Workflow, Pandas"), technical_approach=item.get("technical_approach", "Modular component creation, pipeline merging, and cross-validation matrix testing"), difficulty="Advanced", feasibility_score=max(1, min(10, int(item.get("feasibility_score", 9)))), feasibility_reasoning=item.get("feasibility_reasoning", "Calibrated for efficient parallel multi-student execution profiles."), week1_plan=item.get("week1_plan", "Architecture separation and repository initialization setup."), week2_plan=item.get("week2_plan", "Parallel training loops and computational engine updates."), week3_plan=item.get("week3_plan", "Unified interface mapping and presentation verification loops."), final_demo=item.get("final_demo", "Comprehensive multi-widget configuration monitor layout."), college_application_value=item.get("college_application_value", "Highlights collaborative infrastructure engineering and elite competition readiness."), similar_projects=similar_projects_list, problem_context=item.get("problem_context", "Systemic cluster friction parameters."), who_experiences_this_problem=item.get("who_experiences_this_problem", "Target users and group ecosystem stakeholders."), why_this_problem_exists=item.get("why_this_problem_exists", "Lack of parallel baseline data processing benchmarks."), potential_project_direction=item.get("potential_project_direction", "Unified Collaborative Framework"), college_narrative=item.get("college_narrative", "Group counselor positioning text verifying exceptional multi-agent capabilities and specialized problem discovery benchmarks.") )) while len(processed_ideas) < 3 and len(processed_ideas) > 0: processed_ideas.append(processed_ideas[0]) session_id = f"sess_{uuid.uuid4().hex[:12]}" SESSIONS[session_id] = { "source": "bettermind", "group_profile": group_identity_graph, "participants": [p.model_dump() for p in request.participants], "ideas": [i.model_dump() for i in processed_ideas], "niche_ideas": [] } try: for p in resolved_profiles: save_generation( session_id=session_id, mode="bettermind", email=p.get("email", ""), full_name=p.get("full_name", ""), grade=str(p.get("grade", "")), future_goal=p.get("future_goal", ""), intended_major=p.get("major", ""), interest_areas=", ".join(p.get("project_themes", [])) ) logger.info(f"Generation saved: {session_id}") save_ideas(session_id, processed_ideas) logger.info(f"Ideas saved: {session_id}") except Exception as db_e: logger.error(f"Failed to save to database: {db_e}") discovery_metadata = DiscoveryMetadata( generation_framework="BetterMind Labs Trajectory Problem Discovery Engine v4.2", research_basis="Generated using collaborative structural intersections for team configuration models.", personalization_summary=f"Recommendations were synthesized via cohort trajectory matching layers and combined history assets." ) return GenerateIdeasResponse(session_id=session_id, discovery_metadata=discovery_metadata, ideas=processed_ideas) except Exception as e: logger.error(f"Critical execution error inside /generate-bml pipeline: {str(e)}") raise HTTPException(status_code=500, detail=str(e)) @app.post("/niche-down", response_model=GenerateIdeasResponse) def niche_down_endpoint(payload: NicheDownRequest): if payload.session_id not in SESSIONS: raise HTTPException(status_code=404, detail="Target tracking session identifier missing.") session_data = SESSIONS[payload.session_id] all_ideas = session_data.get("ideas", []) + session_data.get("niche_ideas", []) base_idea = next((item for item in all_ideas if item["id"] == payload.idea_id), None) if not base_idea: raise HTTPException(status_code=400, detail="Target baseline project reference node invalid.") if not groq_client: raise HTTPException(status_code=503, detail="AI Inference engine client unassigned.") ivy_db_string = json.dumps(IVY_ADMISSIONS_DATABASE, indent=2) system_prompt = ( "You are an expert mentor helping ambitious high school students discover research-backed problem opportunities.\n" "Your task is to take a chosen parent problem context and generate exactly 3 highly refined, localized iterations " "that narrow down hierarchically into a specialized sub-problem context (e.g. Healthcare -> Mental Health -> Teen Stress). Do NOT switch domains.\n\n" "Ensure titles match the professional format 'BrandName: Specific Research-Oriented Subtitle'. Datasets must be authentic, explicit pipelines.\n" "Strictly filter out all simple CRUD dashboards, trackers, or conversational chatbot apps. Enforce advanced backend computational pipelines.\n" "Cross-reference setups with this Ivy Admissions Pattern matrix to inject high-tier validation and admissions scores:\n" f"{ivy_db_string}\n\n" "Format output strictly inside a parseable JSON block matching this exact schema:\n" "{\n" ' "ideas": [\n' ' {\n' ' "title": "[Refined Specialized BrandName: Specific Research-Oriented Subtitle]",\n' ' "problem_area": "[Hierarchically narrowed sub-problem bounds and granular real-world friction]",\n' ' "guiding_question": "[The Core Research Question: Precise testable sub-inquiry]",\n' ' "project_description": "[Specific solution breakdown avoiding generic chatbots/wrappers]",\n' ' "why_it_matters": "[Localized impact statement]",\n' ' "why_this_fits_you": ["Fits your specialization trajectory path", "Extends prior work context cleanly"],\n' ' "student_history_connection": "[Detailed refinement statement tracking the continuous historical line into this niche scope]",\n' ' "target_users": "[Narrowed niche user base stakeholders]",\n' ' "datasets": "[Target specialized high-fidelity explicit public data source repository]",\n' ' "tools": "Python, Streamlit",\n' ' "technical_approach": "[Refined technical pipeline workflow and out-of-sample validation strategy]",\n' ' "difficulty": "Advanced",\n' ' "feasibility_score": 9,\n' ' "feasibility_reasoning": "[Verified implementation bounds]",\n' ' "week1_plan": "[Data fetching and boundary pipelines]",\n' ' "week2_plan": "[Model training and tuning matrices]",\n' ' "week3_plan": "[UI validation dashboard setups]",\n' ' "final_demo": "[Interface performance monitoring widget parameters]",\n' ' "college_application_value": "[Detail potential competition pathways, publication targets, external mentor profiles, and explicit Admissions Strength Score with justification]",\n' ' "problem_context": "[Deep specialized overarching systemic problem description]",\n' ' "who_experiences_this_problem": "[Specific narrowed stakeholders impacted]",\n' ' "why_this_problem_exists": "[Systemic or structural causes for this localized sub-problem]",\n' ' "potential_project_direction": "[Secondary localized project framework title direction]",\n' ' "college_narrative": "[Counselor-ready positioning narrative detailing unique tracking story components. MUST BE A MINIMUM OF 120 WORDS.]"\n' ' }\n' ' ]\n' "}" ) user_prompt = ( f"Parent Context Problem: {base_idea.get('problem_area')}\n" f"Current Title: {base_idea.get('title')}\n" f"Narrow this scope down by one hierarchical step into an advanced granular analytical sub-problem." ) try: response = groq_client.chat.completions.create( model="llama-3.3-70b-versatile", messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}], response_format={"type": "json_object"}, temperature=0.30, timeout=25.0 ) parsed = json.loads(response.choices[0].message.content) raw_niche = parsed.get("ideas", []) processed: List[ProjectIdea] = [] for item in raw_niche[:3]: processed.append(ProjectIdea( id=f"idea_{uuid.uuid4().hex[:8]}", title=item.get("title", "Specialized Sub-problem Core"), problem_area=item.get("problem_area", base_idea.get("problem_area")), guiding_question=item.get("guiding_question", base_idea.get("guiding_question")), project_description=item.get("project_description", base_idea.get("project_description")), why_it_matters=item.get("why_it_matters", base_idea.get("why_it_matters")), why_this_fits_you=item.get("why_this_fits_you", base_idea.get("why_this_fits_you", [])), student_history_connection=item.get("student_history_connection", base_idea.get("student_history_connection", "Deepens technical lineages.")), target_users=item.get("target_users", base_idea.get("target_users", "Niche user base")), datasets=item.get("datasets", base_idea.get("datasets", "Parent reference dataset")), tools=item.get("tools", base_idea.get("tools", "Python, Streamlit")), technical_approach=item.get("technical_approach", base_idea.get("technical_approach")), difficulty="Advanced", feasibility_score=max(1, min(10, int(item.get("feasibility_score", 9)))), feasibility_reasoning=item.get("feasibility_reasoning", base_idea.get("feasibility_reasoning")), week1_plan=item.get("week1_plan", base_idea.get("week1_plan")), week2_plan=item.get("week2_plan", base_idea.get("week2_plan")), week3_plan=item.get("week3_plan", base_idea.get("week3_plan")), final_demo=item.get("final_demo", base_idea.get("final_demo")), college_application_value=item.get("college_application_value", base_idea.get("college_application_value")), similar_projects=base_idea.get("similar_projects", []), problem_context=item.get("problem_context", base_idea.get("problem_context", "Narrowed niche context parameters.")), who_experiences_this_problem=item.get("who_experiences_this_problem", base_idea.get("who_experiences_this_problem", "Target user subset.")), why_this_problem_exists=item.get("why_this_problem_exists", base_idea.get("why_this_problem_exists", "Structural system blockages.")), potential_project_direction=item.get("potential_project_direction", "Niche Analytical Framework"), college_narrative=item.get("college_narrative", base_idea.get("college_narrative", "Deep niche academic positioning.")) )) while len(processed) < 3 and len(processed) > 0: processed.append(processed[0]) session_data["niche_ideas"] = [i.model_dump() for i in processed] discovery_metadata = DiscoveryMetadata( generation_framework="BetterMind Labs Problem Discovery Engine v4.2", research_basis="Generated using localized structural intersections and niche hierarchical narrowing.", personalization_summary="Hierarchical narrow-down refinement context generated by isolating specialized sub-problem friction boundaries." ) return GenerateIdeasResponse(session_id=payload.session_id, discovery_metadata=discovery_metadata, ideas=processed) except Exception as e: logger.error(f"Error inside niche-down execution pipeline loops: {str(e)}") raise HTTPException(status_code=500, detail=str(e)) @app.get("/session/{session_id}") def get_session_state(session_id: str): if session_id not in SESSIONS: raise HTTPException(status_code=404, detail="Active context tracking index mismatch.") return SESSIONS[session_id] if __name__ == "__main__": import uvicorn uvicorn.run( "main:app", host="0.0.0.0", port=int(os.environ.get("PORT", 8000)) )