""" AI Project Planner - Agentic Workflow for Technical Project Management A professional Gradio application that transforms product specifications into comprehensive project plans using orchestrated AI agents. Author: AI Workflow Architect License: MIT """ import gradio as gr import json import time from openai import OpenAI from datetime import datetime from typing import Generator, Tuple, Dict, Any, List import os def test_api_connection(api_key: str) -> str: """Test if the API key works.""" if not api_key or len(api_key) < 20: return "❌ No API key provided" try: # Detect provider if api_key.startswith("sk-ant-"): provider = "Anthropic" import anthropic client = anthropic.Anthropic(api_key=api_key) response = client.messages.create( model="claude-3-haiku-20240307", max_tokens=50, messages=[{"role": "user", "content": "Say 'API working' in 2 words"}] ) result = response.content[0].text elif api_key.startswith("voc-"): provider = "Vocareum" client = OpenAI( api_key=api_key, base_url="https://openai.vocareum.com/v1" ) response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Say 'API working' in 2 words"}], max_tokens=50 ) result = response.choices[0].message.content else: provider = "OpenAI" client = OpenAI(api_key=api_key) response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Say 'API working' in 2 words"}], max_tokens=50 ) result = response.choices[0].message.content return f"✅ {provider} API connected successfully! Response: {result}" except Exception as e: return f"❌ Connection failed: {str(e)}" # Import the agent library from base_agents import ( ActionPlanningAgent, KnowledgeAugmentedPromptAgent, EvaluationAgent, RoutingAgent ) # ============================================================================ # CUSTOM CSS FOR PROFESSIONAL STYLING # ============================================================================ CUSTOM_CSS = """ /* Import Google Fonts */ @import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap'); /* Root Variables */ :root { --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%); --secondary-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); --success-gradient: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); --card-border: #2d2d44; --accent-purple: #667eea; --accent-pink: #f093fb; --accent-cyan: #00f2fe; } /* Global Styles */ .gradio-container { font-family: 'Space Grotesk', sans-serif !important; background: #f8f9fa !important; max-width: 1400px !important; } /* Header Styling */ .header-container { background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%); border: 1px solid var(--card-border); border-radius: 20px; padding: 2rem; margin-bottom: 1.5rem; position: relative; overflow: hidden; } .header-container::before { content: ''; position: absolute; top: 0; left: 0; right: 0; height: 3px; background: var(--primary-gradient); } .header-title { font-size: 2.5rem; font-weight: 700; background: var(--primary-gradient); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; margin-bottom: 0.5rem; } .header-subtitle { color: var(--text-secondary); font-size: 1.1rem; font-weight: 400; } /* Card Styling */ .input-card, .output-card, .workflow-card { background: var(--card-bg) !important; border: 1px solid var(--card-border) !important; border-radius: 16px !important; padding: 1.5rem !important; } /* Workflow Progress */ .workflow-step { display: flex; align-items: center; padding: 1rem; margin: 0.5rem 0; border-radius: 12px; background: rgba(255, 255, 255, 0.02); border: 1px solid transparent; transition: all 0.3s ease; } .workflow-step.active { background: rgba(102, 126, 234, 0.1); border-color: var(--accent-purple); } .workflow-step.completed { background: rgba(0, 242, 254, 0.1); border-color: var(--accent-cyan); } .step-icon { width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin-right: 1rem; font-size: 1.2rem; } .step-icon.waiting { background: rgba(255, 255, 255, 0.1); } .step-icon.active { background: var(--primary-gradient); animation: pulse 2s infinite; } .step-icon.completed { background: var(--success-gradient); } @keyframes pulse { 0%, 100% { transform: scale(1); opacity: 1; } 50% { transform: scale(1.05); opacity: 0.8; } } /* Button Styling */ .primary-btn { background: var(--primary-gradient) !important; border: none !important; border-radius: 12px !important; padding: 1rem 2rem !important; font-weight: 600 !important; font-size: 1rem !important; transition: all 0.3s ease !important; box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3) !important; } .primary-btn:hover { transform: translateY(-2px) !important; box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4) !important; } .secondary-btn { background: transparent !important; border: 1px solid var(--card-border) !important; border-radius: 12px !important; color: var(--text-secondary) !important; transition: all 0.3s ease !important; } .secondary-btn:hover { border-color: var(--accent-purple) !important; color: var(--accent-purple) !important; } /* Tab Styling */ .tabs { border: none !important; } .tab-nav { background: transparent !important; border-bottom: 1px solid var(--card-border) !important; gap: 0.5rem !important; } .tab-nav button { background: transparent !important; border: none !important; border-radius: 8px 8px 0 0 !important; color: var(--text-secondary) !important; padding: 0.75rem 1.5rem !important; font-weight: 500 !important; transition: all 0.3s ease !important; } .tab-nav button.selected { background: rgba(102, 126, 234, 0.2) !important; color: var(--accent-purple) !important; border-bottom: 2px solid var(--accent-purple) !important; } /* Textbox Styling */ .textbox textarea { background: rgba(0, 0, 0, 0.3) !important; border: 1px solid var(--card-border) !important; border-radius: 12px !important; color: var(--text-primary) !important; font-family: 'JetBrains Mono', monospace !important; font-size: 0.9rem !important; padding: 1rem !important; } .textbox textarea:focus { border-color: var(--accent-purple) !important; box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2) !important; } /* Markdown Styling */ .markdown-text { color: var(--text-primary) !important; } .markdown-text h1, .markdown-text h2, .markdown-text h3 { color: var(--text-primary) !important; font-weight: 600 !important; } .markdown-text code { background: rgba(102, 126, 234, 0.2) !important; color: var(--accent-cyan) !important; padding: 0.2rem 0.5rem !important; border-radius: 4px !important; font-family: 'JetBrains Mono', monospace !important; } /* Stats Card */ .stats-container { display: grid; grid-template-columns: repeat(4, 1fr); gap: 1rem; margin-top: 1rem; } .stat-card { background: rgba(255, 255, 255, 0.02); border: 1px solid var(--card-border); border-radius: 12px; padding: 1rem; text-align: center; } .stat-value { font-size: 1.5rem; font-weight: 700; background: var(--primary-gradient); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } .stat-label { font-size: 0.85rem; color: var(--text-secondary); margin-top: 0.25rem; } /* Agent Badge */ .agent-badge { display: inline-flex; align-items: center; padding: 0.25rem 0.75rem; border-radius: 20px; font-size: 0.8rem; font-weight: 500; margin-right: 0.5rem; } .agent-badge.product-manager { background: rgba(102, 126, 234, 0.2); color: #667eea; } .agent-badge.program-manager { background: rgba(240, 147, 251, 0.2); color: #f093fb; } .agent-badge.dev-engineer { background: rgba(0, 242, 254, 0.2); color: #00f2fe; } /* Accordion Styling */ .accordion { border: 1px solid var(--card-border) !important; border-radius: 12px !important; background: var(--card-bg) !important; margin-bottom: 0.5rem !important; } /* File Upload */ .file-upload { border: 2px dashed var(--card-border) !important; border-radius: 12px !important; background: rgba(0, 0, 0, 0.2) !important; transition: all 0.3s ease !important; } .file-upload:hover { border-color: var(--accent-purple) !important; background: rgba(102, 126, 234, 0.05) !important; } /* Scrollbar */ ::-webkit-scrollbar { width: 8px; height: 8px; } ::-webkit-scrollbar-track { background: var(--dark-bg); } ::-webkit-scrollbar-thumb { background: var(--card-border); border-radius: 4px; } ::-webkit-scrollbar-thumb:hover { background: var(--accent-purple); } /* Loading Animation */ .loading-dots { display: inline-flex; gap: 4px; } .loading-dots span { width: 8px; height: 8px; border-radius: 50%; background: var(--accent-purple); animation: bounce 1.4s infinite ease-in-out both; } .loading-dots span:nth-child(1) { animation-delay: -0.32s; } .loading-dots span:nth-child(2) { animation-delay: -0.16s; } @keyframes bounce { 0%, 80%, 100% { transform: scale(0); } 40% { transform: scale(1); } } /* Progress Bar */ .progress-bar { height: 4px; background: var(--card-border); border-radius: 2px; overflow: hidden; margin-top: 0.5rem; } .progress-bar-fill { height: 100%; background: var(--primary-gradient); border-radius: 2px; transition: width 0.5s ease; } /* Example Card */ .example-card { background: rgba(255, 255, 255, 0.02); border: 1px solid var(--card-border); border-radius: 12px; padding: 1rem; cursor: pointer; transition: all 0.3s ease; } .example-card:hover { border-color: var(--accent-purple); transform: translateY(-2px); } .example-title { font-weight: 600; color: var(--text-primary); margin-bottom: 0.5rem; } .example-desc { font-size: 0.85rem; color: var(--text-secondary); } """ # ============================================================================ # EXAMPLE PRODUCT SPECIFICATIONS # ============================================================================ EXAMPLE_SPECS = { "Email Router": """# Email Router Product Specification ## Executive Summary The Email Router is an intelligent email management system designed to automatically classify, route, and respond to incoming emails using advanced NLP and machine learning capabilities. ## Target Users - Customer Support Representatives - IT Administrators - Subject Matter Experts (SMEs) - Business Operations Teams ## Core Features ### 1. Intelligent Email Classification - Automatic categorization of incoming emails by intent, urgency, and topic - Support for custom classification rules and machine learning models - Real-time processing with sub-second latency requirements ### 2. Smart Routing Engine - Rule-based routing to appropriate departments or individuals - Load balancing across support teams - Escalation workflows for high-priority items - Integration with existing ticketing systems ### 3. Automated Response System - Template-based auto-replies for common inquiries - AI-generated response suggestions for complex queries - Sentiment analysis to adjust tone appropriately - Multi-language support ### 4. Analytics Dashboard - Real-time metrics on email volume, response times, and resolution rates - Historical trend analysis and forecasting - Agent performance tracking - Customer satisfaction scoring ### 5. Administration Console - User and role management - Routing rule configuration - Knowledge base management - System health monitoring ## Technical Requirements - Process 10,000+ emails per hour - 99.9% uptime SLA - Integration via SMTP, IMAP, and REST APIs - SOC 2 Type II compliance - GDPR and CCPA data handling ## Success Metrics - 70% reduction in manual email triage time - 50% improvement in first-response time - 90% customer satisfaction score - 95% routing accuracy """, "Task Management App": """# Task Management Application Specification ## Product Vision A modern, collaborative task management platform that helps teams organize work, track progress, and meet deadlines efficiently. ## Target Users - Project Managers - Team Members - Executives/Stakeholders - Remote Teams ## Core Features ### 1. Task Creation & Organization - Create tasks with titles, descriptions, due dates, and priorities - Organize tasks into projects and workspaces - Support for subtasks and checklists - File attachments and rich text descriptions ### 2. Collaboration Tools - Assign tasks to team members - Comment threads on tasks - @mentions and notifications - Real-time updates and sync ### 3. Views & Visualization - List view for detailed task management - Kanban board for workflow visualization - Calendar view for deadline tracking - Gantt chart for project timeline ### 4. Automation - Recurring task creation - Due date reminders - Status change triggers - Integration webhooks ### 5. Reporting & Analytics - Project progress dashboards - Team workload distribution - Time tracking and estimates - Custom report generation ## Technical Requirements - Web, iOS, and Android applications - Real-time synchronization - Offline mode support - Third-party integrations (Slack, GitHub, Google Calendar) - Enterprise SSO support ## Success Metrics - 30% improvement in project delivery time - 50% reduction in missed deadlines - 85% daily active user rate - 4.5+ app store rating """, "E-Commerce Platform": """# E-Commerce Platform Specification ## Product Overview A scalable e-commerce platform enabling businesses to create online stores, manage inventory, process payments, and fulfill orders. ## Target Users - Small Business Owners - E-commerce Managers - Warehouse Staff - Customer Service Teams ## Core Features ### 1. Store Management - Customizable storefront templates - Product catalog management - Category and collection organization - SEO optimization tools ### 2. Inventory System - Real-time stock tracking - Multi-warehouse support - Low stock alerts - Supplier management ### 3. Order Processing - Shopping cart functionality - Multiple payment gateways - Order status tracking - Return and refund handling ### 4. Customer Management - Customer accounts and profiles - Order history - Wishlist functionality - Loyalty program support ### 5. Analytics & Reports - Sales dashboards - Customer behavior analytics - Inventory reports - Financial summaries ## Technical Requirements - Support 100,000+ concurrent users - PCI DSS compliance - Mobile-responsive design - API for third-party integrations - Multi-currency and multi-language ## Success Metrics - 99.99% checkout availability - <2 second page load time - 3% conversion rate - <1% cart abandonment from technical issues """ } # ============================================================================ # WORKFLOW KNOWLEDGE DEFINITIONS # ============================================================================ KNOWLEDGE_ACTION_PLANNING = """ Stories are defined from a product spec by identifying a persona, an action, and a desired outcome for each story. Each story represents a specific functionality of the product described in the specification. Features are defined by grouping related user stories into cohesive capabilities. Tasks are defined for each story and represent the engineering work required to develop the product. A development Plan for a product contains all these components organized in a logical structure. """ PERSONA_PRODUCT_MANAGER = "You are a Product Manager responsible for defining user stories for a product." PERSONA_PROGRAM_MANAGER = "You are a Program Manager responsible for defining product features." PERSONA_DEV_ENGINEER = "You are a Development Engineer responsible for defining engineering tasks." EVALUATION_CRITERIA_USER_STORIES = ( "The answer should be stories that follow the following structure: " "As a [type of user], I want [an action or feature] so that [benefit/value]." ) EVALUATION_CRITERIA_FEATURES = ( "The answer should be product features that follow the following structure: " "Feature Name: A clear, concise title that identifies the capability\n" "Description: A brief explanation of what the feature does and its purpose\n" "Key Functionality: The specific capabilities or actions the feature provides\n" "User Benefit: How this feature creates value for the user" ) EVALUATION_CRITERIA_TASKS = ( "The answer should be tasks following this exact structure: " "Task ID: A unique identifier for tracking purposes\n" "Task Title: Brief description of the specific development work\n" "Related User Story: Reference to the parent user story\n" "Description: Detailed explanation of the technical work required\n" "Acceptance Criteria: Specific requirements that must be met for completion\n" "Estimated Effort: Time or complexity estimation\n" "Dependencies: Any tasks that must be completed first" ) # ============================================================================ # WORKFLOW ENGINE # ============================================================================ class ProjectPlannerWorkflow: """ Orchestrates the multi-agent workflow for generating project plans. """ def __init__(self, api_key: str): self.api_key = api_key self.agents_initialized = False self.workflow_log = [] self.stats = { "user_stories": 0, "features": 0, "tasks": 0, "iterations": 0 } def log(self, message: str, level: str = "info"): """Add a message to the workflow log.""" timestamp = datetime.now().strftime("%H:%M:%S") self.workflow_log.append({ "timestamp": timestamp, "level": level, "message": message }) def initialize_agents(self, product_spec: str): """Initialize all agents with the product specification.""" self.log("Initializing AI agents...") # Action Planning Agent self.action_planning_agent = ActionPlanningAgent( self.api_key, KNOWLEDGE_ACTION_PLANNING ) # Product Manager Team knowledge_pm = ( "Stories are defined by writing sentences with a persona, an action, and a desired outcome. " "The sentences always start with: As a " "Write several stories for the product spec below, where the personas are the different users of the product. " f"\n\nProduct Specification:\n{product_spec}" ) self.product_manager_agent = KnowledgeAugmentedPromptAgent( self.api_key, PERSONA_PRODUCT_MANAGER, knowledge_pm ) self.product_manager_evaluator = EvaluationAgent( openai_api_key=self.api_key, persona="You are an evaluation agent that checks the answers of other worker agents", evaluation_criteria=EVALUATION_CRITERIA_USER_STORIES, worker_agent=self.product_manager_agent, max_interactions=5 ) # Program Manager Team knowledge_pgm = ( "Features of a product are defined by organizing similar user stories into cohesive groups. " f"\n\nProduct Specification:\n{product_spec}" ) self.program_manager_agent = KnowledgeAugmentedPromptAgent( self.api_key, PERSONA_PROGRAM_MANAGER, knowledge_pgm ) self.program_manager_evaluator = EvaluationAgent( openai_api_key=self.api_key, persona="You are an evaluation agent that checks the answers of other worker agents", evaluation_criteria=EVALUATION_CRITERIA_FEATURES, worker_agent=self.program_manager_agent, max_interactions=5 ) # Development Engineer Team knowledge_dev = ( "Development tasks are defined by identifying what needs to be built to implement each user story. " f"\n\nProduct Specification:\n{product_spec}" ) self.dev_engineer_agent = KnowledgeAugmentedPromptAgent( self.api_key, PERSONA_DEV_ENGINEER, knowledge_dev ) self.dev_engineer_evaluator = EvaluationAgent( openai_api_key=self.api_key, persona="You are an evaluation agent that checks the answers of other worker agents", evaluation_criteria=EVALUATION_CRITERIA_TASKS, worker_agent=self.dev_engineer_agent, max_interactions=5 ) # Routing Agent routes = [ { "name": "Product Manager", "description": "Responsible for defining product personas and user stories only.", "func": self._product_manager_handler }, { "name": "Program Manager", "description": "Responsible for defining product features by grouping related user stories.", "func": self._program_manager_handler }, { "name": "Development Engineer", "description": "Responsible for defining development tasks and engineering work.", "func": self._dev_engineer_handler } ] self.routing_agent = RoutingAgent(self.api_key, routes) self.agents_initialized = True self.log("All agents initialized successfully", "success") def _product_manager_handler(self, query: str) -> str: """Handle Product Manager routing.""" self.log("Product Manager generating user stories...") response = self.product_manager_agent.respond(query) result = self.product_manager_evaluator.evaluate(response) self.stats["iterations"] += result.get("iterations", 1) return result["final_response"] def _program_manager_handler(self, query: str) -> str: """Handle Program Manager routing.""" self.log("Program Manager defining features...") response = self.program_manager_agent.respond(query) result = self.program_manager_evaluator.evaluate(response) self.stats["iterations"] += result.get("iterations", 1) return result["final_response"] def _dev_engineer_handler(self, query: str) -> str: """Handle Development Engineer routing.""" self.log("Development Engineer creating tasks...") response = self.dev_engineer_agent.respond(query) result = self.dev_engineer_evaluator.evaluate(response) self.stats["iterations"] += result.get("iterations", 1) return result["final_response"] def run_workflow(self, product_spec: str) -> Generator[Tuple[str, str, str, str, str], None, None]: """ Execute the full workflow and yield progress updates. Yields tuples of: (workflow_status, user_stories, features, tasks, full_plan) """ self.workflow_log = [] self.stats = {"user_stories": 0, "features": 0, "tasks": 0, "iterations": 0} # Initialize agents yield ("⏳ Initializing agents...", "", "", "", "") self.initialize_agents(product_spec) # Extract workflow steps yield ("🔍 Planning workflow steps...", "", "", "", "") self.log("Action Planning Agent analyzing product specification...") workflow_prompt = ( "Create a comprehensive project plan including: " "1) User stories for all personas, " "2) Key product features grouped logically, " "3) Development tasks for implementation" ) steps = self.action_planning_agent.extract_steps_from_prompt(workflow_prompt) self.log(f"Identified {len(steps)} workflow steps", "success") # Process each step user_stories = "" features = "" tasks = "" # Generate User Stories yield ("👤 Generating user stories...", "", "", "", "") self.log("Routing to Product Manager team...") user_stories_prompt = "Define comprehensive user stories for all personas in the product specification" user_stories = self._product_manager_handler(user_stories_prompt) self.stats["user_stories"] = user_stories.count("As a") self.log(f"Generated {self.stats['user_stories']} user stories", "success") yield ("✅ User stories complete", user_stories, "", "", "") # Generate Features yield ("📦 Defining product features...", user_stories, "", "", "") self.log("Routing to Program Manager team...") features_prompt = f"Based on these user stories, define the key product features:\n\n{user_stories}" features = self._program_manager_handler(features_prompt) self.stats["features"] = max( features.lower().count("feature name"), features.count("##"), features.count("**") // 2, len([line for line in features.split('\n') if line.strip().startswith(('1.', '2.', '3.', '4.', '5.', '6.', '7.', '8.', '9.'))]) ) self.log(f"Defined {self.stats['features']} product features", "success") yield ("✅ Features complete", user_stories, features, "", "") # Generate Tasks yield ("🔧 Creating engineering tasks...", user_stories, features, "", "") self.log("Routing to Development Engineer team...") tasks_prompt = f"Create detailed engineering tasks to implement these features:\n\n{features}" tasks = self._dev_engineer_handler(tasks_prompt) self.stats["tasks"] = tasks.lower().count("task id") self.log(f"Created {self.stats['tasks']} engineering tasks", "success") yield ("✅ Tasks complete", user_stories, features, tasks, "") # Generate Full Plan yield ("📋 Compiling final plan...", user_stories, features, tasks, "") full_plan = self._compile_full_plan(user_stories, features, tasks) self.log("Project plan compilation complete!", "success") yield ("✅ Project plan ready!", user_stories, features, tasks, full_plan) def _compile_full_plan(self, user_stories: str, features: str, tasks: str) -> str: """Compile all outputs into a formatted project plan.""" # Recalculate stats with better detection self.stats["user_stories"] = max( user_stories.lower().count("as a"), len([line for line in user_stories.split('\n') if line.strip().startswith(('1.', '2.', '3.', '4.', '5.'))]) ) self.stats["features"] = max( features.lower().count("feature name"), features.lower().count("feature:"), len([line for line in features.split('\n') if line.strip() and line.strip()[0].isdigit() and '.' in line[:3]]), features.count("**") // 2 if "**" in features else 0 ) self.stats["tasks"] = max( tasks.lower().count("task id"), tasks.lower().count("task title"), len([line for line in tasks.split('\n') if "task id" in line.lower()]) ) # Build workflow log table rows first log_rows = [] for log_entry in self.workflow_log: message = log_entry['message'].replace('|', '-') log_rows.append(f"| {log_entry['timestamp']} | {log_entry['level']} | {message} |") workflow_log_table = "\n".join(log_rows) # Build the plan document - NO INDENTATION in the string plan = f"""# 📋 Project Plan **Generated:** {datetime.now().strftime("%Y-%m-%d %H:%M")} --- ## 📊 Summary Statistics | Metric | Count | |--------|-------| | User Stories | {self.stats['user_stories']} | | Product Features | {self.stats['features']} | | Engineering Tasks | {self.stats['tasks']} | | Evaluation Iterations | {self.stats['iterations']} | --- ## 👤 User Stories {user_stories} --- ## 📦 Product Features {features} --- ## 🔧 Engineering Tasks {tasks} --- ## 📝 Workflow Log | Time | Level | Message | |------|-------|---------| {workflow_log_table} --- ## ✅ Next Steps 1. Review and prioritize the user stories with stakeholders 2. Validate feature groupings with the product team 3. Estimate engineering tasks with the development team 4. Create sprint plan based on dependencies 5. Set up project tracking in your preferred tool (Jira, Linear, etc.) --- *Generated by AI Project Planner | Powered by GPT-3.5* """ return plan # ============================================================================ # GRADIO INTERFACE # ============================================================================ def create_interface(): """Create the Gradio interface.""" workflow = None # Add these state variables stored_stories = gr.State("") stored_features = gr.State("") stored_tasks = gr.State("") def validate_api_key(api_key: str) -> str: """Validate the API key format.""" if not api_key or len(api_key) < 20: return "❌ Please enter a valid API key" if api_key.startswith("sk-ant-"): return "✅ Anthropic Claude key detected" elif api_key.startswith("voc-"): return "✅ Vocareum key detected (requires Vocareum network)" elif api_key.startswith("sk-"): return "✅ OpenAI key detected" else: return "⚠️ Unknown key format - will try OpenAI" def load_example(example_name: str) -> str: """Load an example product specification.""" return EXAMPLE_SPECS.get(example_name, "") def run_planner( api_key: str, product_spec: str, progress=gr.Progress() ) -> Tuple[str, str, str, str, str]: """Run the project planner workflow.""" if not api_key or len(api_key) < 20: return ( "❌ Error: Please enter a valid OpenAI API key", "", "", "", "" ) if not product_spec or len(product_spec) < 100: return ( "❌ Error: Please provide a product specification (minimum 100 characters)", "", "", "", "" ) try: planner = ProjectPlannerWorkflow(api_key) results = ("", "", "", "", "") progress(0, desc="Starting workflow...") step_progress = [0.1, 0.2, 0.4, 0.6, 0.8, 0.9, 1.0] step_idx = 0 for status, stories, features, tasks, plan in planner.run_workflow(product_spec): if step_idx < len(step_progress): progress(step_progress[step_idx], desc=status) step_idx += 1 results = (status, stories, features, tasks, plan) return results except Exception as e: return ( f"❌ Error: {str(e)}", "", "", "", "" ) def export_markdown(plan: str): """Export full plan as markdown.""" if not plan or len(plan) < 50: return None filename = f"project_plan_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md" with open(filename, "w", encoding="utf-8") as f: f.write(plan) return filename def export_json(stories: str, features: str, tasks: str, plan: str): """Export results as JSON.""" if not plan or len(plan) < 50: return None data = { "generated_at": datetime.now().isoformat(), "user_stories": stories, "features": features, "tasks": tasks, "full_plan": plan } filename = f"project_plan_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json" with open(filename, "w", encoding="utf-8") as f: json.dump(data, f, indent=2, ensure_ascii=False) return filename # Build the interface with gr.Blocks(title="AI Project Planner") as app: # Header gr.HTML("""
Built with ❤️ using Gradio • Powered by OpenAI GPT-3.5 • View on GitHub