""" COGNEXA ML Service - Endpoint Integration Checklist This document tracks which endpoints need API patches to fix 422 validation errors. Last Updated: March 28, 2026 Status: Ready for Integration SUMMARY: - Total endpoints: 30+ - Need fixing: 3 (currently return 422) - Implementation guide: API_INTEGRATION_GUIDE.py - Test file: test_api_endpoints.py """ # ============================================================================ # ENDPOINTS REQUIRING FIXES (422 Errors) # ============================================================================ ENDPOINTS_TO_FIX = { # ✅ PRIORITY 1: HIGH - User-Facing Endpoints "/api/personality/analyze-responses": { "method": "POST", "priority": "HIGH", "current_issue": "422 - Strict Pydantic validation", "problem": "Fails on type mismatches: '4' vs 4, '3.5' vs 3.5", "solution": "Apply DynamicRequestValidator.validate_personality_responses()", "fix_status": "⏳ NOT APPLIED", "test_payload": { "responses": {"q1": 4, "q2": "3.5", "q3": 5}, "response_scale_max": 5 }, "expected_response": { "status": 200, "body": {"analysis": {...}} } }, "/api/productivity/forecast": { "method": "POST", "priority": "HIGH", "current_issue": "422 - Rigid field validation", "problem": "Fails on missing optional fields or type coercion", "solution": "Apply DynamicRequestValidator.validate_productivity_forecast()", "fix_status": "⏳ NOT APPLIED", "test_payload": { "user_id": "user123", "forecast_days": "7", "historical_data": [ {"date": "2026-03-20", "completed_tasks": "5"} ] }, "expected_response": { "status": 200, "body": {"forecast": {...}} } }, "/api/personalization/predict-engagement": { "method": "POST", "priority": "HIGH", "current_issue": "422 - Strict schema validation", "problem": "Doesn't handle flexible input formats or type variations", "solution": "Apply DynamicRequestValidator.validate_engagement_prediction()", "fix_status": "⏳ NOT APPLIED", "test_payload": { "user_id": "user123", "task_id": "task456", "task": { "title": "Review notes", "category": "WORK", "priority": "MEDIUM" } }, "expected_response": { "status": 200, "body": {"engagement_prediction": 0.78} } } } # ============================================================================ # ENDPOINTS ALREADY WORKING (No Fixes Needed) # ============================================================================ ENDPOINTS_WORKING = { # ✅ Health & Status "/health": { "method": "GET", "status": "✅ WORKING" }, "/api/status": { "method": "GET", "status": "✅ WORKING" }, # ✅ Task & Completion "/api/tasks/predict": { "method": "POST", "status": "✅ WORKING", "uses": "dynamic_trainers (models correctly set up)" }, "/api/v1/tasks": { "method": "GET", "status": "✅ WORKING" }, "/api/v1/tasks/analytics": { "method": "GET", "status": "✅ WORKING" }, "/api/tasks/batch-predict": { "method": "POST", "status": "✅ WORKING" }, # ✅ Behavioral & Personality "/api/v1/behavioral-personality/blended": { "method": "POST", "status": "✅ WORKING" }, "/api/v1/behavioral-personality/sync/overview": { "method": "POST", "status": "✅ WORKING" }, "/api/behavior/cross-device/analyze": { "method": "POST", "status": "✅ WORKING" }, # ✅ Wellbeing "/api/wellbeing/summary": { "method": "GET", "status": "✅ WORKING" }, "/api/wellbeing/recommendations": { "method": "GET", "status": "✅ WORKING" }, "/api/wellbeing/trends": { "method": "GET", "status": "✅ WORKING" }, # ✅ Gamification "/api/v1/gamification/stats": { "method": "GET", "status": "✅ WORKING" }, "/api/v1/gamification/achievements/user": { "method": "GET", "status": "✅ WORKING" }, # ✅ Notifications "/api/notifications/unread-count": { "method": "GET", "status": "✅ WORKING" }, # ✅ Cognitive Theory "/ml/cognitive/analyze": { "method": "POST", "status": "✅ WORKING", "uses": "dynamic_trainers + cognitive theory" }, "/ml/cognitive/cognitive-load": { "method": "POST", "status": "✅ WORKING" }, "/ml/cognitive/personality-fit": { "method": "POST", "status": "✅ WORKING" }, "/ml/cognitive/flow-state": { "method": "POST", "status": "✅ WORKING" }, "/ml/cognitive/motivation": { "method": "POST", "status": "✅ WORKING" }, # ✅ Prediction & Explanation "/api/predict/explain": { "method": "POST", "status": "✅ WORKING" } } # ============================================================================ # IMPLEMENTATION STEPS # ============================================================================ IMPLEMENTATION_STEPS = [ { "step": 1, "title": "Import Required Modules", "location": "main.py (top of file)", "code": """ from fastapi import Body from fastapi.responses import JSONResponse from ML.dynamic_api_handler import DynamicRequestValidator """, "status": "⏳ PENDING" }, { "step": 2, "title": "Update /api/personality/analyze-responses", "location": "main.py (personality endpoint)", "change": """ # BEFORE: @app.post("/api/personality/analyze-responses") async def analyze_responses(request: PersonalityResponse): ... # AFTER: @app.post("/api/personality/analyze-responses") async def analyze_responses(request: dict = Body(...)): try: validated = DynamicRequestValidator.validate_personality_responses(request) result = analyze_personality_scores( responses=validated['responses'], response_scale_max=validated['response_scale_max'] ) return JSONResponse(status_code=200, content={"status": "success", "analysis": result}) except ValueError as e: return JSONResponse(status_code=400, content={"error": str(e)}) """, "status": "⏳ PENDING" }, { "step": 3, "title": "Update /api/productivity/forecast", "location": "main.py (productivity endpoint)", "change": """ # BEFORE: @app.post("/api/productivity/forecast") async def forecast_productivity(request: ProductivityForecast): ... # AFTER: @app.post("/api/productivity/forecast") async def forecast_productivity(request: dict = Body(...)): try: validated = DynamicRequestValidator.validate_productivity_forecast(request) forecast = generate_forecast( user_id=validated['user_id'], historical_data=validated['historical_data'], forecast_days=validated['forecast_days'], personality=validated.get('personality') ) return JSONResponse(status_code=200, content={"status": "success", "forecast": forecast}) except ValueError as e: return JSONResponse(status_code=400, content={"error": str(e)}) """, "status": "⏳ PENDING" }, { "step": 4, "title": "Update /api/personalization/predict-engagement", "location": "main.py (personalization endpoint)", "change": """ # BEFORE: @app.post("/api/personalization/predict-engagement") async def predict_engagement(request: EngagementPrediction): ... # AFTER: @app.post("/api/personalization/predict-engagement") async def predict_engagement(request: dict = Body(...)): try: validated = DynamicRequestValidator.validate_engagement_prediction(request) engagement_score = predict_user_engagement( user_id=validated['user_id'], task_id=validated['task_id'], task=validated['task'], user_profile=validated.get('user_profile', {}) ) return JSONResponse(status_code=200, content={"engagement_prediction": engagement_score}) except ValueError as e: return JSONResponse(status_code=400, content={"error": str(e)}) """, "status": "⏳ PENDING" }, { "step": 5, "title": "Test Fixes", "location": "Command line", "command": "python test_api_endpoints.py", "expected": "20+ endpoints tested, success rate > 95%", "status": "⏳ PENDING" } ] # ============================================================================ # VALIDATION RULES (From dynamic_api_handler.py) # ============================================================================ VALIDATION_RULES = { "personality_responses": { "Field": "responses", "Type": "dict", "Coercion": "Each value coerced to float (handles '4.5' → 4.5, '5' → 5.0)", "Required": True, "Default": None }, "personality_responses_scale": { "Field": "response_scale_max", "Type": "int", "Coercion": "Coerces to int ('5' → 5)", "Required": False, "Default": 5 }, "productivity_user_id": { "Field": "user_id", "Type": "str", "Required": True }, "productivity_forecast_days": { "Field": "forecast_days", "Type": "int", "Coercion": "Coerces to int ('7' → 7)", "Required": False, "Default": 7 }, "productivity_historical_data": { "Field": "historical_data", "Type": "list", "Required": True }, "engagement_user_id": { "Field": "user_id", "Type": "str", "Required": True }, "engagement_task_id": { "Field": "task_id", "Type": "str", "Required": True }, "engagement_task": { "Field": "task", "Type": "dict", "Required": True } } # ============================================================================ # QUICK FIX SCRIPT # ============================================================================ """ To quickly apply all patches at once, run: python -c " import sys from pathlib import Path # This demonstrates automated patching (manual application recommended for safety) print('🔧 ENDPOINT PATCH APPLICATION') print('='*70) print() print('⚠️ RECOMMENDED: Apply patches manually to main.py') print() print('Steps:') print('1. Open main.py in your editor') print('2. Find the 3 problematic endpoints') print('3. Follow the changes in IMPLEMENTATION_STEPS above') print('4. Test with: python test_api_endpoints.py') print() print('This ensures you have full control and understand the changes.') print() " """ # ============================================================================ # ROLLBACK INSTRUCTIONS # ============================================================================ ROLLBACK_INSTRUCTIONS = """ If you need to rollback changes: 1. Revert endpoint signatures: From: def endpoint(request: dict = Body(...)): To: def endpoint(request: EndpointModel): 2. Revert validation: Remove: DynamicRequestValidator.validate_*() Add: Original validation logic 3. Restore error handling: Remove: JSONResponse with custom errors Add: Original Pydantic 422 responses Or use git: git checkout main.py """ # ============================================================================ # DOCUMENTATION REFERENCES # ============================================================================ DOCUMENTATION = { "API_INTEGRATION_GUIDE.py": "Step-by-step integration guide with examples", "dynamic_api_handler.py": "Validator implementation (500+ lines)", "QUICK_REFERENCE.md": "Quick reference for commands and troubleshooting", "test_api_endpoints.py": "Comprehensive API test suite", "test_ml_service.py": "Model loading and validation tests" } # ============================================================================ # COMPLETION CHECKLIST # ============================================================================ CHECKLIST = """ PRE-IMPLEMENTATION: [ ] Read API_INTEGRATION_GUIDE.py [ ] Backup main.py: cp main.py main.py.backup [ ] Verify test_api_endpoints.py ready: ls test_api_endpoints.py IMPLEMENTATION: [ ] Step 1: Add imports to main.py [ ] Step 2: Update /api/personality/analyze-responses [ ] Step 3: Update /api/productivity/forecast [ ] Step 4: Update /api/personalization/predict-engagement [ ] Verify no syntax errors: python -m py_compile main.py TESTING: [ ] Restart ML service: python main.py [ ] Run endpoint tests: python test_api_endpoints.py [ ] Verify 422 errors → 400 errors (or 200 success) [ ] Test with cURL: curl -X POST http://localhost:8000/api/personality/analyze-responses [ ] Monitor logs for errors POST-IMPLEMENTATION: [ ] All 3 endpoints returning success (not 422) [ ] Update team documentation [ ] Deploy to production [ ] Monitor error rates """ # ============================================================================ # PRINT SUMMARY # ============================================================================ if __name__ == "__main__": print("="*70) print("COGNEXA ML SERVICE - ENDPOINT INTEGRATION CHECKLIST") print("="*70) print("\n📋 ENDPOINTS REQUIRING FIXES:") for endpoint, details in ENDPOINTS_TO_FIX.items(): print(f"\n {endpoint}") print(f" Priority: {details['priority']}") print(f" Status: {details['fix_status']}") print(f" Issue: {details['current_issue']}") print(f"\n✅ ENDPOINTS ALREADY WORKING: {len(ENDPOINTS_WORKING)}") print("\n📚 DOCUMENTATION:") for file, desc in DOCUMENTATION.items(): print(f" - {file}: {desc}") print("\n" + "="*70) print("NEXT STEPS:") print("="*70) print("1. Read: API_INTEGRATION_GUIDE.py") print("2. Apply: 4 implementation steps (update 3 endpoints + imports)") print("3. Test: python test_api_endpoints.py") print("4. Verify: All endpoints return success (not 422)") print("="*70)