# pyright: reportMissingImports=false, reportMissingTypeStubs=false, reportExplicitAny=false, reportAny=false, reportUnknownVariableType=false, reportUnknownArgumentType=false, reportUnknownMemberType=false, reportUnusedCallResult=false import json import os import time from typing import Any, Optional import pandas as pd import requests import streamlit as st APP_TITLE = "AI Prototype Planner" CAPABILITY_DESCRIPTION = "End to End Applied AI Prototyping — Rapid prototyping of full AI experiences. Connect data sources with model layers and interfaces for validation and experimentation." RATE_LIMIT_REQUESTS = 8 RATE_LIMIT_WINDOW_SECONDS = 60 GEMINI_MODEL = "gemini-2.5-flash" PRIMARY_CAPABILITIES = [ "Text Generation", "Image/Video", "Speech/Audio", "Structured Data/Analytics", "Multi-modal", "Agents/Automation", ] TARGET_USERS = [ "Internal team", "B2B customers", "B2C consumers", "Developer API", ] ARCHITECTURE_STAGES = [ "Data Sources", "Processing", "Model Layer", "API Layer", "Frontend", ] def model_catalog() -> dict[str, list[dict[str, str]]]: return { "Text Generation": [ {"model": "GPT-4o", "provider": "OpenAI", "capability_match": "Strong reasoning + tools", "cost_1k_requests": "$28.00", "latency": "Medium", "pros": "High quality + mature ecosystem", "cons": "Premium pricing"}, {"model": "Claude 3.5 Sonnet", "provider": "Anthropic", "capability_match": "Long-context instruction following", "cost_1k_requests": "$22.00", "latency": "Medium", "pros": "Reliable complex writing", "cons": "Tier-dependent limits"}, {"model": "Gemini 1.5 Pro", "provider": "Google", "capability_match": "Large context + multimodal", "cost_1k_requests": "$18.00", "latency": "Medium", "pros": "Great context/cost balance", "cons": "May require strict prompting"}, ], "Image/Video": [ {"model": "SDXL", "provider": "Stability AI", "capability_match": "Image generation and editing", "cost_1k_requests": "$8.00", "latency": "Medium", "pros": "Flexible and open workflow", "cons": "Prompt tuning overhead"}, {"model": "GPT-4o mini vision", "provider": "OpenAI", "capability_match": "Visual understanding", "cost_1k_requests": "$10.00", "latency": "Low", "pros": "Fast image analysis", "cons": "Not specialized for generation"}, {"model": "Gemini 1.5 Flash", "provider": "Google", "capability_match": "Video-aware extraction", "cost_1k_requests": "$9.00", "latency": "Low", "pros": "Fast and cost-efficient", "cons": "Lower quality than premium tiers"}, ], "Speech/Audio": [ {"model": "Whisper-large-v3", "provider": "OpenAI", "capability_match": "Speech-to-text baseline", "cost_1k_requests": "$6.00", "latency": "Low", "pros": "High transcription accuracy", "cons": "Needs downstream NLU layer"}, {"model": "Gemini 1.5 Pro", "provider": "Google", "capability_match": "Audio + text reasoning", "cost_1k_requests": "$18.00", "latency": "Medium", "pros": "Unified multimodal pipeline", "cons": "High cost for always-on streams"}, {"model": "Llama 3.1 70B Instruct", "provider": "Meta / Hosted", "capability_match": "Post-ASR intent handling", "cost_1k_requests": "$7.00", "latency": "Medium", "pros": "Self-host flexibility", "cons": "MLOps complexity"}, ], "Structured Data/Analytics": [ {"model": "Claude 3 Haiku", "provider": "Anthropic", "capability_match": "Fast BI commentary", "cost_1k_requests": "$5.00", "latency": "Low", "pros": "Low-latency narrative insights", "cons": "Less deep reasoning"}, {"model": "GPT-4o", "provider": "OpenAI", "capability_match": "Executive reporting", "cost_1k_requests": "$28.00", "latency": "Medium", "pros": "Best-in-class summaries", "cons": "Can be expensive at scale"}, {"model": "Llama 3.1 8B Instruct", "provider": "Meta / Hosted", "capability_match": "Private analytics copilot", "cost_1k_requests": "$3.00", "latency": "Low", "pros": "Low marginal cost", "cons": "Requires quality tuning"}, ], "Multi-modal": [ {"model": "Gemini 1.5 Pro", "provider": "Google", "capability_match": "Cross-modal context fusion", "cost_1k_requests": "$18.00", "latency": "Medium", "pros": "Native multimodal input", "cons": "Prompt format discipline required"}, {"model": "GPT-4o", "provider": "OpenAI", "capability_match": "High quality multimodal responses", "cost_1k_requests": "$28.00", "latency": "Medium", "pros": "Great tool ecosystem", "cons": "Higher cost"}, {"model": "Claude 3.5 Sonnet", "provider": "Anthropic", "capability_match": "Document + visual reasoning", "cost_1k_requests": "$22.00", "latency": "Medium", "pros": "Strong reliability", "cons": "Fewer native media workflows"}, ], "Agents/Automation": [ {"model": "GPT-4o", "provider": "OpenAI", "capability_match": "Function/tool orchestration", "cost_1k_requests": "$28.00", "latency": "Medium", "pros": "Excellent function calling", "cons": "Costs climb with chain depth"}, {"model": "Claude 3.5 Sonnet", "provider": "Anthropic", "capability_match": "Long-horizon planning", "cost_1k_requests": "$22.00", "latency": "Medium", "pros": "Strong consistency", "cons": "Schema-control needed"}, {"model": "Llama 3.1 70B Instruct", "provider": "Meta / Hosted", "capability_match": "On-prem orchestration", "cost_1k_requests": "$7.00", "latency": "Medium", "pros": "Deployment control", "cons": "Ops burden"}, ], } def template_library() -> dict[str, dict[str, Any]]: return { "Text Generation": {"sources": ["Knowledge Base", "Support Tickets", "Product Docs"], "ingestion": "Batch sync + webhook deltas", "preprocessing": "Chunking, dedupe, metadata, embeddings", "storage": "Object store + vector DB", "serving": "RAG API + moderation", "frontend": "Chat assistant with handoff", "team": "1 PM, 1 AI, 1 Backend, 1 Frontend"}, "Image/Video": {"sources": ["Uploads", "Media feeds", "Moderation queue"], "ingestion": "Event-driven media workers", "preprocessing": "Frame extraction, resizing, safety features", "storage": "Object store + metadata index", "serving": "Async inference gateway", "frontend": "Ops moderation dashboard", "team": "1 PM, 1 CV, 1 Backend, 1 Trust/Safety"}, "Speech/Audio": {"sources": ["Call recordings", "Mobile streams", "CRM logs"], "ingestion": "Realtime collector + batch import", "preprocessing": "Noise reduction, diarization, transcript cleanup", "storage": "Audio lake + transcript warehouse", "serving": "Realtime intent API", "frontend": "Voice-enabled workflow app", "team": "1 PM, 1 Speech, 1 Mobile, 1 Backend"}, "Structured Data/Analytics": {"sources": ["Warehouse", "SaaS exports", "Event tracking"], "ingestion": "Daily ETL + KPI stream", "preprocessing": "Validation, feature derivation, null handling", "storage": "Warehouse mart + feature cache", "serving": "Analytics API + insight jobs", "frontend": "KPI dashboard", "team": "1 PM, 1 Data Engineer, 1 Backend, 1 BI/Frontend"}, "Multi-modal": {"sources": ["Documents", "Images", "Audio", "App events"], "ingestion": "Unified ingest bus + parsers", "preprocessing": "OCR, ASR, segmentation, embeddings", "storage": "Object + vector + metadata DB", "serving": "Multimodal orchestrator", "frontend": "Unified analyst workspace", "team": "1 PM, 2 AI, 1 Platform, 1 Frontend"}, "Agents/Automation": {"sources": ["SOP docs", "System APIs", "Task events"], "ingestion": "Connector framework", "preprocessing": "Tool schema normalization + policy tags", "storage": "Knowledge store + run-history DB", "serving": "Agent runtime + guardrails", "frontend": "Automation cockpit", "team": "1 PM, 1 Agent Eng, 1 Backend, 1 Security"}, } @st.cache_data def load_sample_concepts() -> list[dict[str, Any]]: path = "data/sample_concepts.jsonl" records: list[dict[str, Any]] = [] try: with open(path, "r", encoding="utf-8") as handle: for line in handle: line = line.strip() if not line: continue try: obj = json.loads(line) except json.JSONDecodeError: continue if isinstance(obj, dict): records.append(obj) except OSError: return [] return records def complexity_weight(capability: str) -> float: return { "Text Generation": 1.0, "Image/Video": 1.25, "Speech/Audio": 1.2, "Structured Data/Analytics": 0.9, "Multi-modal": 1.45, "Agents/Automation": 1.35, }.get(capability, 1.0) def risk_note(target_users: str) -> str: if target_users == "Internal team": return "Access controls, SSO, and audit logs." if target_users == "B2B customers": return "Tenant isolation, SLOs, and support runbook." if target_users == "B2C consumers": return "Safety, abuse detection, and high-traffic reliability." return "Versioned APIs, quotas, and auth hardening." def estimate_monthly_requests(target_users: str, budget: int) -> int: baseline = { "Internal team": 90000, "B2B customers": 220000, "B2C consumers": 850000, "Developer API": 500000, }.get(target_users, 100000) scale = max(0.35, min(2.2, budget / 100000)) return int(baseline * scale) def architecture_template(capability: str, target_users: str) -> list[dict[str, str]]: profile = template_library().get(capability, template_library()["Text Generation"]) api_layer = { "Internal team": "Internal API gateway + SSO", "B2B customers": "Tenant-aware API gateway + RBAC", "B2C consumers": "Public API + anti-abuse checks", "Developer API": "Versioned API gateway + key management", }.get(target_users, "API gateway") return [ {"stage": "Data Sources", "tech": ", ".join(profile["sources"]), "details": "Primary data systems feeding context and events."}, {"stage": "Processing", "tech": profile["preprocessing"], "details": "Normalize, enrich, and filter input signals."}, {"stage": "Model Layer", "tech": "Hybrid routing across fast + premium models", "details": "Use quality/cost-aware model switching."}, {"stage": "API Layer", "tech": api_layer, "details": "Authentication, observability, policy checks, and versioning."}, {"stage": "Frontend", "tech": profile["frontend"], "details": "User-facing interface with feedback collection."}, ] def weekly_plan(capability: str, timeline_weeks: int, target_users: str) -> list[dict[str, str]]: phases = [ "Discovery + scope lock", "Data integration", "Model baseline + evaluations", "API and orchestration", "UX integration + user tests", "Hardening + observability", "Pilot launch", ] team = template_library().get(capability, template_library()["Text Generation"]).get("team", "Cross-functional AI team") stride = max(1, int(round(max(2, timeline_weeks) / 6))) rows: list[dict[str, str]] = [] for wk in range(1, timeline_weeks + 1): phase = phases[min((wk - 1) // stride, len(phases) - 1)] deliverable = f"Week {wk} delivery for {phase.lower()}" if wk == 1: deliverable = "Problem framing, KPI targets, and architecture brief" if wk == timeline_weeks: deliverable = "Pilot release, handover docs, and support plan" rows.append( { "Week": str(wk), "Milestone": phase, "Deliverables": deliverable, "Team Allocation": team, "Risk Control": risk_note(target_users), } ) return rows def estimate_costs(capability: str, target_users: str, budget: int, timeline_weeks: int) -> dict[str, Any]: weight = complexity_weight(capability) req = estimate_monthly_requests(target_users, budget) compute = int((budget * 0.18 * weight) + (timeline_weeks * 1100)) storage = int((budget * 0.05) + (timeline_weeks * 320)) model_api = int((req / 1000) * (8 + (weight * 4))) development = int((budget * 0.52) + (timeline_weeks * 2100 * weight)) security = int((budget * 0.08) + (timeline_weeks * 420)) subtotal = compute + storage + model_api + development + security contingency = int(subtotal * 0.15) total = subtotal + contingency fit = "Within target" if total <= budget * 1.1 else "Above target" return { "compute": compute, "storage": storage, "model_api": model_api, "development": development, "security": security, "contingency": contingency, "subtotal": subtotal, "total": total, "fit": fit, } def parse_json_object(text: str) -> Optional[dict[str, Any]]: if not text: return None start = text.find("{") end = text.rfind("}") if start == -1 or end == -1 or end <= start: return None try: data = json.loads(text[start : end + 1]) except json.JSONDecodeError: return None if isinstance(data, dict): return data return None def check_rate_limit() -> tuple[bool, int]: now = time.time() current = [ts for ts in st.session_state.get("request_timestamps", []) if (now - ts) <= RATE_LIMIT_WINDOW_SECONDS] st.session_state["request_timestamps"] = current if len(current) >= RATE_LIMIT_REQUESTS: retry = int(RATE_LIMIT_WINDOW_SECONDS - (now - current[0])) return False, max(retry, 1) current.append(now) st.session_state["request_timestamps"] = current return True, 0 def init_state() -> None: defaults: dict[str, Any] = { "concept_description": "", "primary_capability": PRIMARY_CAPABILITIES[0], "target_users": TARGET_USERS[1], "budget": 75000, "timeline_weeks": 12, "unlocked_step": 1, "request_timestamps": [], "architecture_rows": [], "data_pipeline": {}, "model_options": [], "selected_model_name": "", "build_plan_rows": [], "cost_inputs": {}, "cost_summary": {}, "ai_strategy_note": "", "ai_architecture_text": "", "final_plan": None, "final_plan_source": "", "sample_cursor": 0, } for key, value in defaults.items(): if key not in st.session_state: st.session_state[key] = value def clear_dynamic_widget_keys() -> None: keys = list(st.session_state.keys()) for key in keys: if isinstance(key, str) and (key.startswith("arch_tech_") or key.startswith("arch_details_")): del st.session_state[key] if isinstance(key, str) and key.startswith("pipeline_"): del st.session_state[key] for transient in ["build_plan_editor", "move_week_pick"]: if transient in st.session_state: del st.session_state[transient] def apply_sample(samples: list[dict[str, Any]]) -> None: if not samples: return index = int(st.session_state.get("sample_cursor", 0)) % len(samples) sample = samples[index] st.session_state["sample_cursor"] = (index + 1) % len(samples) st.session_state["concept_description"] = str(sample.get("description", "")) st.session_state["primary_capability"] = str(sample.get("primary_capability", PRIMARY_CAPABILITIES[0])) st.session_state["target_users"] = str(sample.get("target_users", TARGET_USERS[0])) st.session_state["budget"] = int(sample.get("budget", 75000)) st.session_state["timeline_weeks"] = int(sample.get("timeline_weeks", 12)) st.session_state["unlocked_step"] = 1 st.session_state["final_plan"] = None st.session_state["final_plan_source"] = "" clear_dynamic_widget_keys() seed_step_two_state(reset_models=True) seed_step_three_state() def seed_step_two_state(reset_models: bool) -> None: capability = str(st.session_state.get("primary_capability", PRIMARY_CAPABILITIES[0])) target = str(st.session_state.get("target_users", TARGET_USERS[0])) arch = architecture_template(capability, target) pipeline_profile = template_library().get(capability, template_library()["Text Generation"]) pipeline = { "sources": list(pipeline_profile.get("sources", [])), "ingestion": str(pipeline_profile.get("ingestion", "")), "preprocessing": str(pipeline_profile.get("preprocessing", "")), "storage": str(pipeline_profile.get("storage", "")), "serving": str(pipeline_profile.get("serving", "")), } st.session_state["architecture_rows"] = arch st.session_state["data_pipeline"] = pipeline if reset_models: options = [dict(row) for row in model_catalog().get(capability, model_catalog()["Text Generation"])] st.session_state["model_options"] = options st.session_state["selected_model_name"] = options[0]["model"] if options else "" clear_dynamic_widget_keys() def seed_step_three_state() -> None: capability = str(st.session_state.get("primary_capability", PRIMARY_CAPABILITIES[0])) target = str(st.session_state.get("target_users", TARGET_USERS[0])) budget = int(st.session_state.get("budget", 75000)) timeline = int(st.session_state.get("timeline_weeks", 12)) st.session_state["build_plan_rows"] = weekly_plan(capability, timeline, target) costs = estimate_costs(capability, target, budget, timeline) st.session_state["cost_inputs"] = { "compute": costs["compute"], "storage": costs["storage"], "model_api": costs["model_api"], "development": costs["development"], "security": costs["security"], } recalculate_cost_summary() def recalculate_cost_summary() -> None: cost_inputs = st.session_state.get("cost_inputs", {}) budget = int(st.session_state.get("budget", 0)) compute = int(cost_inputs.get("compute", 0)) storage = int(cost_inputs.get("storage", 0)) model_api = int(cost_inputs.get("model_api", 0)) development = int(cost_inputs.get("development", 0)) security = int(cost_inputs.get("security", 0)) subtotal = compute + storage + model_api + development + security contingency = int(subtotal * 0.15) total = subtotal + contingency fit = "Within target" if total <= budget * 1.1 else "Above target" st.session_state["cost_summary"] = { "line_items": [ {"category": "Compute", "estimate_usd": compute, "notes": "Inference + orchestration resources"}, {"category": "Storage", "estimate_usd": storage, "notes": "Object, metadata, and vector storage"}, {"category": "Model API", "estimate_usd": model_api, "notes": "Primary model inference and retries"}, {"category": "Development", "estimate_usd": development, "notes": "Product + engineering implementation effort"}, {"category": "Security", "estimate_usd": security, "notes": "Guardrails, logging, monitoring, compliance"}, {"category": "Contingency (15%)", "estimate_usd": contingency, "notes": "Scope and traffic variance"}, ], "subtotal": subtotal, "contingency": contingency, "total": total, "budget": budget, "fit": fit, } def ensure_architecture_widget_defaults() -> None: rows = st.session_state.get("architecture_rows", []) for idx, row in enumerate(rows): tech_key = f"arch_tech_{idx}" detail_key = f"arch_details_{idx}" if tech_key not in st.session_state: st.session_state[tech_key] = str(row.get("tech", "")) if detail_key not in st.session_state: st.session_state[detail_key] = str(row.get("details", "")) def sync_architecture_from_widgets() -> None: rows = st.session_state.get("architecture_rows", []) updated: list[dict[str, str]] = [] for idx, row in enumerate(rows): updated.append( { "stage": str(row.get("stage", ARCHITECTURE_STAGES[idx] if idx < len(ARCHITECTURE_STAGES) else "Stage")), "tech": str(st.session_state.get(f"arch_tech_{idx}", row.get("tech", ""))), "details": str(st.session_state.get(f"arch_details_{idx}", row.get("details", ""))), } ) st.session_state["architecture_rows"] = updated def ensure_pipeline_widget_defaults() -> None: pipeline = st.session_state.get("data_pipeline", {}) sources = pipeline.get("sources", []) if not isinstance(sources, list): sources = [] if "pipeline_sources" not in st.session_state: st.session_state["pipeline_sources"] = ", ".join([str(item) for item in sources]) for key in ["ingestion", "preprocessing", "storage", "serving"]: widget_key = f"pipeline_{key}" if widget_key not in st.session_state: st.session_state[widget_key] = str(pipeline.get(key, "")) def sync_pipeline_from_widgets() -> None: source_text = str(st.session_state.get("pipeline_sources", "")) sources = [part.strip() for part in source_text.split(",") if part.strip()] st.session_state["data_pipeline"] = { "sources": sources, "ingestion": str(st.session_state.get("pipeline_ingestion", "")), "preprocessing": str(st.session_state.get("pipeline_preprocessing", "")), "storage": str(st.session_state.get("pipeline_storage", "")), "serving": str(st.session_state.get("pipeline_serving", "")), } def build_architecture_diagram_text(architecture_rows: list[dict[str, str]]) -> str: segments: list[str] = [] for row in architecture_rows: stage = str(row.get("stage", "Stage")) tech = str(row.get("tech", "")) segments.append(f"[{stage}] {tech}") return "\n -> ".join(segments) def heuristic_strategy_note(inputs: dict[str, Any], selected_model: str) -> str: return ( f"Design around a modular API-first stack for {inputs['target_users']} so the prototype can validate outcomes quickly. " f"Use {selected_model} as the primary model path while keeping routing abstraction in place for cost and quality tuning." ) def gemini_strategy(inputs: dict[str, Any], architecture_text: str) -> Optional[dict[str, Any]]: api_key = os.getenv("GEMINI_API_KEY") if not api_key: return None endpoint = f"https://generativelanguage.googleapis.com/v1beta/models/{GEMINI_MODEL}:generateContent" schema = { "strategy_note": "string", "architecture_diagram": "string", "execution_focus": ["string"], } prompt = f""" You are a principal AI product architect. Return only valid JSON. Draft a concise but actionable strategy output for this prototype planning workflow. Concept: {inputs['concept_description']} Primary capability: {inputs['primary_capability']} Target users: {inputs['target_users']} Budget: {inputs['budget']} Timeline weeks: {inputs['timeline_weeks']} Selected model: {inputs['selected_model']} Current architecture draft: {architecture_text} Rules: - strategy_note should be 2-4 sentences, practical and specific. - architecture_diagram should preserve 5-stage order: Data Sources -> Processing -> Model Layer -> API Layer -> Frontend. - execution_focus should include exactly 3 bullet-ready phrases. Schema: {json.dumps(schema)} """.strip() payload = { "contents": [{"parts": [{"text": prompt}]}], "generationConfig": {"temperature": 0.2, "maxOutputTokens": 1500, "responseMimeType": "application/json"}, } try: response = requests.post(f"{endpoint}?key={api_key}", json=payload, timeout=45) if response.status_code != 200: return None data = response.json() candidates = data.get("candidates", []) if not candidates: return None parts = candidates[0].get("content", {}).get("parts", []) text = "\n".join([str(part.get("text", "")) for part in parts if isinstance(part, dict)]).strip() parsed = parse_json_object(text) if not parsed: return None return parsed except Exception: return None def assemble_final_plan(strategy_source: str) -> dict[str, Any]: concept = str(st.session_state.get("concept_description", "")).strip() capability = str(st.session_state.get("primary_capability", PRIMARY_CAPABILITIES[0])) target = str(st.session_state.get("target_users", TARGET_USERS[0])) budget = int(st.session_state.get("budget", 0)) timeline = int(st.session_state.get("timeline_weeks", 0)) selected_model_name = str(st.session_state.get("selected_model_name", "")) model_options = st.session_state.get("model_options", []) architecture_rows = st.session_state.get("architecture_rows", []) pipeline = st.session_state.get("data_pipeline", {}) build_rows = st.session_state.get("build_plan_rows", []) cost_summary = st.session_state.get("cost_summary", {}) selected_model = {} for model in model_options: if str(model.get("model", "")) == selected_model_name: selected_model = model break if not selected_model and model_options: selected_model = model_options[0] strategy_note = str(st.session_state.get("ai_strategy_note", "")).strip() architecture_diagram = str(st.session_state.get("ai_architecture_text", "")).strip() if not strategy_note: strategy_note = heuristic_strategy_note( { "concept_description": concept, "primary_capability": capability, "target_users": target, "budget": budget, "timeline_weeks": timeline, }, str(selected_model.get("model", "Primary model")), ) if not architecture_diagram: architecture_diagram = build_architecture_diagram_text(architecture_rows) return { "capability_description": CAPABILITY_DESCRIPTION, "concept": concept, "primary_capability": capability, "target_users": target, "budget": budget, "timeline_weeks": timeline, "strategy_note": strategy_note, "architecture_diagram": architecture_diagram, "architecture": architecture_rows, "selected_model": selected_model, "model_options": model_options, "data_pipeline": pipeline, "build_plan": build_rows, "cost_estimate": cost_summary, "source": strategy_source, } def plan_tab_labels(unlocked_step: int) -> list[str]: labels = [ "1. Define Your Concept", "2. Architecture & Model Selection", "3. Build Plan & Timeline", "4. Prototype Plan", ] output: list[str] = [] for idx, label in enumerate(labels, start=1): if idx > unlocked_step: output.append(f"{label} LOCKED") else: output.append(label) return output def tab_lock_css(unlocked_step: int) -> str: if unlocked_step <= 1: lock_selector = "button:nth-child(n+2)" elif unlocked_step == 2: lock_selector = "button:nth-child(n+3)" elif unlocked_step == 3: lock_selector = "button:nth-child(4)" else: lock_selector = "" if not lock_selector: return "" return f""" .stTabs [data-baseweb=\"tab-list\"] {lock_selector} {{ opacity: 0.42; pointer-events: none; filter: grayscale(1); border-color: rgba(117, 126, 145, 0.35) !important; }} """ def apply_theme(unlocked_step: int) -> None: st.markdown( f""" """, unsafe_allow_html=True, ) def render_header() -> None: st.markdown( f"""