1. phases
Itinera API
  • ✈ Itinera API Documentation
  • Docs
    • legacy
      • Itinera — System Overview
      • Technology Stack & Architecture
      • Getting Started Guide
      • Infrastructure
      • Frontend Application
      • Architecture Overview
      • API Reference
      • Backend Services
      • Development Guidelines
    • phases
      • 01. Architecture Overview & Checkout Idempotency
      • Phase 2: Commerce & Checkout Engine
      • Phase 3: Webhooks & Asynchronous Fulfillment
      • Phase 4: Security Perimeter & Authentication
      • Phase 5: Database Schema & Entity Relationships
      • Phase 6: AI Quota & Telemetry Subsystems
      • Phase 7: API Route Matrix & FormRequests
      • Phase 8: Global Exception & Error Handling
      • Phase 9: Frontend Ecosystem & State Management
      • Phase 10: Design System & Component Library
      • Phase 11: Interactive GSAP Animations
      • Phase 12: Deployment & CI/CD Pipeline
      • Phase 13: Testing Strategies
      • Phase 14: Performance & Optimization
      • Phase 15: Developer Onboarding & Runbooks
      • 15-Phase Comprehensive Wiki & Documentation Plan
  • APIs
    • Auth
      • Register a new user
      • Log in a user
      • Log out user
      • Refresh JWT token
      • Forgot password request
      • Reset password verification
      • Get current user profile
      • Update user profile
      • Redirect to Google OAuth
      • Google OAuth Callback
      • Verify email via signed URL
    • Catalog
      • List all countries
      • Get country details
      • List all cities
      • List all regions
      • List all destinations
      • Get destination details
      • Get hotels by destination
      • List all hotels
      • Get hotel details
      • Get reviews for a hotel
      • List all flights
      • Get flight details
      • List all restaurants
      • Get restaurant details
      • List all attractions
      • Get current weather
      • Submit review for an entity
      • Delete review
      • Toggle favourite status for entity
      • List my submitted reviews
    • Bookings
      • Book a tour destination
    • V1 Aliases
      • V1 List all countries
      • V1 Get country details
      • V1 List all cities
      • V1 List all destinations
      • V1 Get destination details
      • V1 Get hotels by destination
      • V1 List all hotels
      • V1 Get hotel details
      • V1 Get reviews for a hotel
      • V1 List all flights
      • V1 Get flight details
      • V1 List all restaurants
      • V1 Get restaurant details
      • V1 List all attractions
      • V1 Get attraction details
      • V1 List all regions
      • V1 Get weather details
    • Trips
      • List user trips
      • Create a new trip
      • Get trip details
      • Update trip details
      • Delete a trip
      • Get creation metadata
      • Attach items to a trip
      • Update trip item
      • Detach items from a trip
      • Fork a trip
    • Conversations
      • List user conversations
      • Start a new conversation
      • Get conversation details
      • List messages in conversation
      • Send message to conversation
      • Mark conversation as read
    • Commerce Plans
      • List public plans
      • Get public plan details
    • Commerce Subscriptions
      • Subscribe to a plan
      • Upgrade active plan
      • Get active subscription info
      • Cancel active subscription
    • Commerce Checkout
      • Initiate Paymob payment checkout
    • Integrations
      • Paymob status webhook callback
      • Paymob redirect return callback
    • System Settings & Support
      • Submit public contact message
      • Subscribe to system newsletter
      • Get list of my reports
      • List all notifications
      • Mark single notification as read
      • List available surveys
      • Submit answers for survey
      • Get survey details
      • Update survey details
      • Delete survey response
    • AI Tools
      • Enhance itinerary details using AI
      • Request AI review of itinerary
      • Plan route using AI assistance
      • Get AI quota remaining details
      • Chat with AI Concierge assistant
      • Get AI Review progress by ID
    • Agency Integration
      • Request agency assignment
      • List agency active tasks
      • List agency managed trips
      • Get agency total earnings
      • Get agency profile details
      • Update agency profile details
    • Admin User Management
      • List users inside admin dashboard
      • Get user profile
      • Set user active status
      • Block user profile
    • Admin Catalog Moderation
      • Create new catalog category
      • Create new catalog destination
      • Create new hotel catalog record
      • Create new flight catalog record
      • Create new restaurant catalog record
      • Create new attraction catalog record
  • Schemas
    • User
    • ErrorResponse
    • Trip
    • Destination
    • Hotel
    • Flight
    • Restaurant
    • Attraction
    • Booking
    • Review
    • Agency
    • Survey
  1. phases

Phase 6: AI Quota & Telemetry Subsystems

This document dissects the economics and observability of the AI inference engine. The system relies on a strict quota-based throttle governed by the active subscription tier and a dedicated telemetry layer that audits every generation for live dashboards.

1. The Quota Context: Service Resolution#

The AiUsageService is responsible for gatekeeping access to Groq/Llama 70b based on subscription entitlements.
Resolution Chain: The service queries PlanService::resolveQuotaPlan($user) to find the monthly quota. It handles three states elegantly:
1.
The user has no subscriptions: It falls back to the Free tier quota.
2.
The user has expired subscriptions: It throws a descriptive Exception.
3.
The user has an active subscription: It uses that plan's ai_quota_monthly.
Monthly Reset: Before consumption, it evaluates user->ai_reset_at. If the timestamp is in the past, it automatically resets the generation counter and extends the window by one month.

2. The Atomic Consumption Guard#

To prevent race conditions when a user spams the generation endpoint, the quota write is not a naive PHP ++. It uses a raw UPDATE WHERE query that only succeeds if the condition holds:
Atomicity: If two requests hit simultaneously and only one quota remains, only the first UPDATE will affect 1 row. The second will affect 0 rows.
Handling: If zero rows were updated, the service throws "You have exhausted your monthly AI quota."

3. MD5 Caching & Fallback Architecture#

The most economically vital code is in GroqService.php. It implements Markdown-stripped caching to prevent repeated LLM inference from consuming quota or incurring cost.
As seen in GroqService::review, the generation is strictly wrapped in Cache::remember():

The Lifecycle#

1.
Hit: The controller generates a deterministic md5 hash of the requested prompt/trip data and asks the Cache.
2.
Consume: On a Cache Miss, the quota is consumed atomically inside the remember closure. If quota is exhausted, the request fails.
3.
Inference: Groq (Llama 3.3 70b) is called.
4.
Success: The response is cached for 60 minutes.
5.
Cache Hit: On the next identical request, the closure is never executed. The result is served instantly by Redis, and no quota is consumed.

The Graceful Fallback#

If quota is exhausted, or if the external API throws an exception, the outer AiController::generate catches it cleanly and falls back to a deterministic procedural generator. It perfectly synthesizes an N-day itinerary using templates and calculated offsets, ensuring the endpoint is always available.

4. Telemetry Auditing (AiGeneration)#

Regardless of whether the response came from Cache, LLM, or the Fallback, the AiController::logGeneration method writes a strict telemetry event to the AiGeneration database table.
This data never throws exceptions (try/catch swallowed with a Log::warning), ensuring the user's actual itinerary is saved even if the telemetry database is temporarily unavailable. This dataset directly powers the Live Command Center monitoring shell.

5. Data Flow: Quota & Caching#

Modified at 2026-08-25 22:41:45
Previous
Phase 5: Database Schema & Entity Relationships
Next
Phase 7: API Route Matrix & FormRequests
Built with