ADR-0004: Consolidate AI Services (AiService, JorvisAiService, OptimizedAiService)
ADR-0004: Consolidate AI Services (AiService, JorvisAiService, OptimizedAiService)
Status
Proposed (2025-12-23)
Context
Currently, the Jorvis backend has three fragmented AI services:
AiService(Legacy): Used by most system flows, lacks structured JSON output support.JorvisAiService(Modern): Gemini-focused, implements ADR-0001 (Structured JSON).OptimizedAiService: Specialized for cost/speed optimizations.
This fragmentation leads to:
- Duplicate prompt logic.
- Inconsistent SQL generation quality.
- Maintenance overhead.
- Circular dependencies when attempting to inject one into another.
Proposed Changes
- Consolidation: Merge
AiServicelogic intoJorvisAiServiceor vice versa. - Abstract AI Interface: Define a single
AiProviderinterface to decouple business logic from specific LLM implementations. - Circular Dependency Resolution:
- Move shared interfaces (
SqlGenerationResult,ConversationHistoryEntry) to a dedicated filesrc/types/ai.types.ts. - Use NestJS
forwardRef()only as a last resort; prefer extracting shared logic into standalone utility classes or services.
- Move shared interfaces (
Phased Migration
- Phase A (Foundation): Extract shared types and interfaces to
ai.types.ts. - Phase B (Unified Interface): Implement
UnifiedAiServicethat wrapsJorvisAiService. - Phase C (Feature Flag): Enable migration for specific callers using
JORVIS_USE_UNIFIED_AI_SERVICE. - Phase D (Decommissioning): Gradually remove old
AiServicemethods after verification.
Feature Flag
JORVIS_USE_UNIFIED_AI_SERVICE: (Default:false). Whentrue, system uses the consolidated logic for all SQL generation.
Verification Plan
- Unit Testing: 100% test coverage for new
UnifiedAiService. - Regression Testing: Run existing
text2sql.eval.spec.tsto ensure no quality drop. - E2E Testing: Run
pack.sh smokefor both AdventureWorks and Olist. - Manual Verification: Cross-verify logs for correct SQL hashing and structured JSON parsing.
Rollback Strategy
- Immediate rollback by setting
JORVIS_USE_UNIFIED_AI_SERVICE=false. - If critical failure persists, revert to the last stable tag (
v37).
Security Non-Negotiables
- Maintain SQL sanitization in logs (no raw SQL).
- Ensure
SqlGuardremains the final validator for all generated SQL.
Expected Outcome
- Single source of truth for AI interactions.
- Structured JSON output enabled for all system flows.
- Clean, lint-free architecture without circular dependencies.