--- title: "AI Detail Records (AIDRs) & Multimodal Margin Ledger" description: "Documentation for AI Detail Records (AIDRs)" --- ## Table of Contents 1. [Module Overview (Technical)](#1-module-overview-technical) 2. [Module Overview (Commercial & Business Value)](#2-module-overview-commercial--business-value) 3. [🎯 User Roles & Key Capabilities](#3--user-roles--key-capabilities) 4. [Visual Interface & Ledger Structure](#4-visual-interface--ledger-structure) 5. [Architectural Flow & Real-Time Rating Pipeline](#5-architectural-flow--real-time-rating-pipeline) 6. [Common Scenarios & Operational Playbooks](#6-common-scenarios--operational-playbooks) 7. [Troubleshooting & Diagnostic Commands](#7-troubleshooting--diagnostic-commands) 8. [Glossary](#8-glossary) --- ## 1. Module Overview (Technical) The **AI Detail Records (AIDRs)** module (`public.ai_detail_records`) serves as the financial ledger and real-time rating engine for all Artificial Intelligence services consumed across the platform. While traditional CDRs rate telephony minutes and MDRs rate SMS dispatches, AIDRs meter and rate multimodal AI workloads: 1. **AI Chat & Copilot Tokens**: Prompt and completion tokens generated by the web portal Copilot, administrative assistants, and extension chatbots. 2. **Interactive Real-Time Voice Agents**: Bidirectional conversational voice sessions conducted between callers and AI voice personas (e.g. OpenAI Realtime, ElevenLabs, Deepgram). 3. **Speech-to-Text (STT) Call Audio Transcription**: Asynchronous post-call audio transcription and executive AI summary generation. ### Dual-Rate Financial Rating Engine For every completed AI interaction, the rating engine evaluates two simultaneous financial dimensions: * **Wholesale Vendor Cost (`vendor_cost`):** The raw API consumption fee charged by the upstream AI provider (OpenAI, Anthropic, ElevenLabs, Deepgram). * **Retail Customer Charge (`billed_cost`):** The amount debited from the customer's prepaid wallet or evaluated against bundled monthly plan quotas. * **Gross Profit Margin (`margin`):** Real-time net margin calculated as `margin = billed_cost - vendor_cost`, with gross margin percentage $\frac{\text{margin}}{\text{billed\_cost}} \times 100$. ### PostgreSQL Schema Architecture (`public.ai_detail_records`) ```sql CREATE TABLE public.ai_detail_records ( id BIGSERIAL PRIMARY KEY, uuid UUID NOT NULL DEFAULT gen_random_uuid(), session_uuid VARCHAR(64) NOT NULL UNIQUE, call_uuid VARCHAR(64), customer_id BIGINT REFERENCES customers(id) ON DELETE SET NULL, domain_id BIGINT, extension_id BIGINT, provider VARCHAR(50) NOT NULL, model_name VARCHAR(100) NOT NULL, service_type VARCHAR(32) NOT NULL, -- 'chat' | 'voice' | 'stt' prompt_tokens INTEGER DEFAULT 0, completion_tokens INTEGER DEFAULT 0, total_tokens INTEGER DEFAULT 0, duration_seconds NUMERIC(10,2) DEFAULT 0.00, vendor_cost NUMERIC(12,6) NOT NULL DEFAULT 0.000000, retail_rate NUMERIC(12,6) NOT NULL DEFAULT 0.000000, billed_cost NUMERIC(12,6) NOT NULL DEFAULT 0.000000, margin NUMERIC(12,6) NOT NULL DEFAULT 0.000000, billing_source VARCHAR(32) NOT NULL DEFAULT 'prepaid_wallet', -- 'bundle_deduction' | 'prepaid_wallet' | 'postpaid' currency VARCHAR(3) NOT NULL DEFAULT 'USD', created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); ``` --- ## 2. Module Overview (Commercial & Business Value) * **Multimodal AI Monetization:** Enables telecom operators and ITSPs to offer AI chatbots, interactive voice agents, and automated call transcription with guaranteed profitability. * **Atomic Plan Allowance Deductions:** Seamlessly depletes customer subscription bundles (e.g., 500,000 monthly tokens, 100 voice minutes, 60 transcription minutes) before transparently falling back to pay-as-you-go wallet billing. * **Negative Margin Prevention:** Instant visibility into wholesale provider fees ensures operators price custom enterprise models with sustainable markups. * **Full Audit Trail:** Every AI session links to an exact call UUID, customer ID, model name, and token counter, preventing billing disputes. --- ## 3. 🎯 User Roles & Key Capabilities | User Role | Key Permissions | Core Responsibilities & Workflows | | :--- | :--- | :--- | | **Super Administrator** | Full Financial Visibility | Audits macro AI revenue, monitors wholesale provider disbursements, and configures default margin thresholds. | | **Billing Analyst** | Read & Ledger Reconciliation | Audits itemized AIDRs, validates quota deductions, and inspects high-volume AI voice sessions. | | **Product Manager** | Tariff & Bundle Sizing | Analyzes average token and duration consumption across customer segments to optimize commercial catalog plans. | | **Support Specialist** | Read & Call ID Lookup | Queries specific session UUIDs or call UUIDs to confirm whether an AI agent answered a customer call. | --- ## 4. Visual Interface & Ledger Structure ### 4.1 Summary Metric KPI Cards The top toolbar renders dynamic metric KPI cards providing immediate visibility across the selected filter window: * **Total AI Sessions:** Aggregate count of rated AI chat, voice, and transcription events. * **Gross Retail Billed:** Total monetary spend charged to customers. * **Net Margin Profit:** Gross profit generated above wholesale provider costs. * **Realtime Voice AI:** Total interactive voice agent minutes delivered. ### 4.2 DataGrid Ledger Columns | Column | Data Field | Description | Example | | :--- | :--- | :--- | :--- | | **Timestamp** | `created_at` | Date and time the AI session was finalized and rated. | `2026-09-22 14:32:05` | | **AI Service & Model** | `service_type` + `model_name` | Modality tag (`chat`, `voice`, `stt`) alongside provider and model. | `voice (openai:gpt-4o-realtime)` | | **Session / Call ID** | `session_uuid` / `call_uuid` | Unique platform session identifier and associated PBX call UUID. | `sess-8f3a91... / call-01a4...` | | **Tokens Breakdown** | `prompt_tokens` / `completion_tokens` | Granular breakdown of prompt input vs completion output tokens. | `In: 1,420 / Out: 840 (Total: 2,260)` | | **Duration** | `duration_seconds` | Elapsed interactive voice or audio transcription duration. | `02m 45s (165 sec)` | | **Billed Spend** | `billed_cost` | Total charge assessed to the customer account. | `$0.4125 USD` | | **Wholesale Cost** | `vendor_cost` | Raw API expense assessed by upstream AI provider. | `$0.2750 USD` | | **Gross Margin** | `margin` + `margin_percent` | Net profit and margin percentage achieved on the transaction. | `+$0.1375 (+33.3%)` | | **Billing Source** | `billing_source` | Ledger source: `bundle_deduction` (Plan quota) or `prepaid_wallet`. | `bundle_deduction` | --- ## 5. Architectural Flow & Real-Time Rating Pipeline ``` PBX Call / Web Chat Event Completes │ ▼ ┌───────────────────────────────────────────────┐ │ AIDR Rating Engine (aidrService) │ ├───────────────────────────────────────────────┤ │ 1. Parse token counters & audio duration │ │ 2. Identify active Customer Subscription: │ │ • Check Service Type allowance balance │ │ 3. Evaluation: │ │ ├─ IF balance >= usage: │ │ │ Deduct from subscription quota balance │ │ │ Set billed_cost = $0.00 │ │ │ Set billing_source = 'bundle_deduction'│ │ └─ IF balance < usage: │ │ Calculate overage at plan rate │ │ Debit customer prepaid wallet │ │ Set billing_source = 'prepaid_wallet' │ │ 4. Calculate vendor cost from AI Rate Card │ │ 5. Compute gross margin = billed - vendor │ └───────────────────────┬───────────────────────┘ │ ▼ ┌───────────────────────────────────────────────┐ │ Insert into public.ai_detail_records │ └───────────────────────────────────────────────┘ ``` --- ## 6. Common Scenarios & Operational Playbooks ### Scenario A: Real-Time Interactive Voice Inbound Call A customer dials into an AI Receptionist powered by OpenAI Realtime voice: 1. The call lasts 3 minutes 20 seconds (200 seconds). 2. The customer's plan includes 100 pooled voice minutes with 45 minutes remaining. 3. The OCS rating engine deducts 3.33 minutes from `subscriptions.ai_voice_minutes_balance`. 4. The transaction is recorded in AIDRs with `billed_cost = $0.00`, `billing_source = bundle_deduction`, and the wholesale vendor cost recorded for provider disbursement reconciliation. ### Scenario B: Voicemail Speech-to-Text Transcription Overage An enterprise customer with an exhausted transcription bundle receives a 90-second voicemail: 1. Speech-to-text audio transcription is executed via Deepgram Nova-2. 2. The customer subscription balance is 0 minutes. 3. The plan overage rate of `$0.0300/min` is applied ($0.0450 total). 4. `$0.0450` is atomically debited from the customer's prepaid balance, yielding an auditable AIDR with positive gross margin. --- ## 7. Troubleshooting & Diagnostic Commands ### Verifying Unbilled AI Detail Records via PostgreSQL ```sql SELECT service_type, provider, model_name, COUNT(*) AS session_count, SUM(total_tokens) AS total_tokens, ROUND(SUM(billed_cost), 4) AS gross_revenue, ROUND(SUM(vendor_cost), 4) AS raw_cogs, ROUND(SUM(margin), 4) AS net_profit FROM public.ai_detail_records WHERE created_at >= NOW() - INTERVAL '24 hours' GROUP BY service_type, provider, model_name ORDER BY gross_revenue DESC; ``` --- ## 8. Glossary * **AIDR (AI Detail Record):** A standardized, itemized financial record capturing token counts, session durations, wholesale vendor costs, and retail charges for an AI service. * **OCS (Online Charging System):** The real-time convergent rating engine that validates credit balances and deducts subscription quotas concurrently with active services. * **Prompt Tokens:** Text or multimodal inputs provided to the LLM context window. * **Completion Tokens:** Generated response tokens produced by the AI model. * **Blended Minute:** Combined input and output audio streaming rate assessed for real-time interactive voice agents.