AI Detail Records (AIDRs) & Multimodal Margin Ledger
Table of Contents
Section titled βTable of Contentsβ- Module Overview (Technical)
- Module Overview (Commercial & Business Value)
- π― User Roles & Key Capabilities
- Visual Interface & Ledger Structure
- Architectural Flow & Real-Time Rating Pipeline
- Common Scenarios & Operational Playbooks
- Troubleshooting & Diagnostic Commands
- Glossary
1. Module Overview (Technical)
Section titled β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:
- AI Chat & Copilot Tokens: Prompt and completion tokens generated by the web portal Copilot, administrative assistants, and extension chatbots.
- Interactive Real-Time Voice Agents: Bidirectional conversational voice sessions conducted between callers and AI voice personas (e.g. OpenAI Realtime, ElevenLabs, Deepgram).
- Speech-to-Text (STT) Call Audio Transcription: Asynchronous post-call audio transcription and executive AI summary generation.
Dual-Rate Financial Rating Engine
Section titled β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 asmargin = billed_cost - vendor_cost, with gross margin percentage $\frac{\text{margin}}{\text{billed_cost}} \times 100$.
PostgreSQL Schema Architecture (public.ai_detail_records)
Section titled βPostgreSQL Schema Architecture (public.ai_detail_records)β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)
Section titled β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
Section titled β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
Section titled β4. Visual Interface & Ledger Structureβ4.1 Summary Metric KPI Cards
Section titled β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
Section titled β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
Section titled β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
Section titled β6. Common Scenarios & Operational PlaybooksβScenario A: Real-Time Interactive Voice Inbound Call
Section titled βScenario A: Real-Time Interactive Voice Inbound CallβA customer dials into an AI Receptionist powered by OpenAI Realtime voice:
- The call lasts 3 minutes 20 seconds (200 seconds).
- The customerβs plan includes 100 pooled voice minutes with 45 minutes remaining.
- The OCS rating engine deducts 3.33 minutes from
subscriptions.ai_voice_minutes_balance. - 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
Section titled βScenario B: Voicemail Speech-to-Text Transcription OverageβAn enterprise customer with an exhausted transcription bundle receives a 90-second voicemail:
- Speech-to-text audio transcription is executed via Deepgram Nova-2.
- The customer subscription balance is 0 minutes.
- The plan overage rate of
$0.0300/minis applied ($0.0450 total). $0.0450is atomically debited from the customerβs prepaid balance, yielding an auditable AIDR with positive gross margin.
7. Troubleshooting & Diagnostic Commands
Section titled β7. Troubleshooting & Diagnostic CommandsβVerifying Unbilled AI Detail Records via PostgreSQL
Section titled βVerifying Unbilled AI Detail Records via PostgreSQLβ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_profitFROM public.ai_detail_recordsWHERE created_at >= NOW() - INTERVAL '24 hours'GROUP BY service_type, provider, model_nameORDER BY gross_revenue DESC;8. Glossary
Section titled β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.

