# Shamra Academia AI Playground — Usage, Consumption & Pricing

> Internal documentation — last updated: February 2026

---

## Table of Contents

1. [Overview](#overview)
2. [Available Operations](#available-operations)
3. [Credit System & Consumption Control](#credit-system--consumption-control)
4. [Subscription Tiers & Pricing](#subscription-tiers--pricing)
5. [AI Model Costs (Azure OpenAI)](#ai-model-costs-azure-openai)
6. [Gross Margin Analysis](#gross-margin-analysis)
7. [Platform Budget Safeguards](#platform-budget-safeguards)
8. [Credit Reset Mechanisms](#credit-reset-mechanisms)
9. [Admin Dashboard](#admin-dashboard)

---

## Overview

The **Shamra Academia AI Playground** (`/playground`) is a research-focused AI workspace for Arabic-speaking academics. It combines:

- **Intelligent Writing Canvas** — AI-powered academic writing environment
- **Multi-source RAG** — Retrieval-Augmented Generation from Shamra library, arXiv, and web
- **Academic Translation Suite** — Arabic/English translation with academic context
- **Reference Management** — Save, organize, and cite sources
- **Research Planning** — AI-assisted research plan generation (single-agent and multi-agent orchestrator)

### External Services

| Service | Purpose |
|---------|---------|
| Azure OpenAI | LLM inference (GPT-5.2, GPT-4o, GPT-4o-mini, GPT-4.5) |
| ElasticSearch | Shamra reference library search |
| arXiv API | Global pre-print search |
| Stripe | Subscription billing |
| SerpAPI | Web search for RAG |
| Mistral Document AI | OCR / PDF text extraction |

---

## Available Operations

### API Endpoints (`PlaygroundAPIController`)

| Endpoint | Operation | Description |
|----------|-----------|-------------|
| `POST /api/playground/chat` | Chat | Streaming AI chat with RAG context |
| `POST /api/playground/keywords` | Keywords | Generate keywords from project title |
| `POST /api/playground/selection` | Selection | Answer questions about selected text |
| `POST /api/playground/search` | Search | Multi-source search (Shamra, arXiv, Web) |
| `POST /api/playground/tashkeel` | Tashkeel | Arabic text vowelization |
| `POST /api/playground/citation` | Citation | Generate APA/MLA/Chicago citations |
| `POST /api/playground/summarize` | Summarize | Summarize documents |
| `POST /api/playground/process-text` | Process Text | Rephrase, proofread, criticize, ask, translate |
| `POST /api/playground/generate/search` | Generate Search | Search sources for content generation |
| `POST /api/playground/generate/check-relevance` | Relevance Check | LLM-based relevance scoring |
| `POST /api/playground/generate` | Generate | RAG-powered content generation with citations |
| `POST /api/playground/references/save` | Save Reference | Save a source to user's library |
| `POST /api/playground/references/save-bulk` | Bulk Save | Bulk save references |
| `POST /api/playground/research-plan/initiate` | Research Plan Init | Start a research plan (clarification) |
| `POST /api/playground/research-plan/generate` | Research Plan Gen | Generate full research plan |

### Project Management (`PlaygroundController`)

| Endpoint | Action |
|----------|--------|
| `GET /playground` | Main playground page (subscription-gated) |
| `POST /playground/project/new` | Create project |
| `POST /playground/project/upload` | Upload file & create project |
| `GET /playground/project/{id}` | Load project |
| `POST /playground/project/{id}/save` | Save project |
| `DELETE /playground/project/{id}/delete` | Delete project |
| `GET /playground/projects` | List user's projects |
| `POST /playground/project/{id}/download/{format}` | Download as DOCX/PDF |
| `GET /playground/activate-demo` | Activate free 14-day trial |

---

## Credit System & Consumption Control

Every AI operation consumes **credits** from the user's monthly allowance. Credits are the primary mechanism to control user consumption and manage platform costs.

### Credit Cost per Operation

Defined in `UsageMonitorService::OPERATION_CREDITS`:

| Operation | Credits | Description |
|-----------|---------|-------------|
| `suggest_keywords` | 1 | AI keyword suggestions |
| `check_relevance` | 1 | Relevance scoring of search results |
| `generate_short` | 2 | Generate a short paragraph |
| `rephrase` | 2 | Rephrase selected text |
| `proofread` | 2 | Check grammar and style |
| `translate` | 2 | Translate text |
| `verify_reference` | 2 | Verify reference with AI |
| `extract_metadata` | 2 | Extract PDF metadata via AI |
| `chat` | 2 | AI chat message |
| `completion` | 2 | Text completion |
| `ask_ai` | 3 | Ask a custom question |
| `summarize` | 3 | Summarize document or section |
| `arxiv_search` | 3 | Search arXiv with AI extraction |
| `generate_long` | 4 | Generate a long paragraph or section |
| `criticize` | 4 | Get AI feedback on text |
| `ocr_extract` | 5 | OCR text extraction (Mistral Document AI) |

### Usage Tracking

Every API call is logged in the `PlaygroundUsageLog` entity with:
- Operation type and model used
- Input tokens, output tokens, total tokens
- Calculated cost in USD
- Latency in milliseconds
- Success/failure status and error messages
- Request metadata

### Pre-request Validation Flow (`canUserMakeRequest`)

Before every AI operation, the system performs these checks in order:

1. **Lazy credit reset** — If a new billing month has started, credits are automatically reset
2. **Subscription active check** — Verify the subscription exists and is not expired
3. **Credit sufficiency check** — Verify `remaining_credits >= credits_needed` for the operation
4. **Emergency mode check** — If daily platform budget is exceeded, Starter-tier users are temporarily blocked

If any check fails, the request is rejected with a specific error reason (`subscription_inactive`, `insufficient_credits`, or `high_demand`).

---

## Subscription Tiers & Pricing

### Tier Comparison

| Feature | Trial | Basic | Starter | Researcher | Professional | Institution |
|---------|-------|-------|---------|------------|--------------|-------------|
| **Monthly Price** | Free | $4.99 | $9.00 | $19.00 | $39.00 | $99.00 |
| **Yearly Price** | — | $49.99 | $90.00 | $190.00 | $390.00 | $990.00 |
| **Yearly Savings** | — | ~17% | ~17% | ~17% | ~17% | ~17% |
| **Monthly Credits** | 100 (one-time) | 0 | 500 | 1,500 | 4,000 | 15,000 |
| **Daily Request Limit** | — | 0 | 50 | 150 | 500 | 2,000 |
| **Max Projects** | — | — | 5 | 15 | Unlimited | Unlimited |
| **Storage** | — | — | 200 MB | 500 MB | 2 GB | 10 GB |
| **Allowed Models** | All | — | GPT-4o-mini | GPT-4o-mini, GPT-4o | GPT-4o-mini, GPT-4o, GPT-4.5 | GPT-4o-mini, GPT-4o, GPT-4.5 |

### Feature Availability by Tier

| Feature | Basic | Starter | Researcher | Professional | Institution |
|---------|-------|---------|------------|--------------|-------------|
| arXiv Search | — | ✅ | ✅ | ✅ | ✅ |
| Reference Library | — | ✅ | ✅ | ✅ | ✅ |
| PDF Export | ✅ | ✅ | ✅ | ✅ | ✅ |
| DOCX Export | — | — | ✅ | ✅ | ✅ |
| LaTeX Export | — | — | — | ✅ | ✅ |
| Priority Support | — | — | ✅ | ✅ | ✅ |
| API Access | — | — | — | ✅ | ✅ |
| Team Management | — | — | — | — | ✅ |
| SSO | — | — | — | — | ✅ |

### Trial Details

- **Duration:** 14 days, one-time per user
- **Credits:** 100 (non-renewable)
- **Models:** Access to all models
- **Activation:** `GET /playground/activate-demo`

### Billing

Handled via **Stripe**. Webhook events:
- `invoice.payment_succeeded` → Activate/renew subscription + reset credits
- `invoice.payment_failed` → Deactivate subscription
- `customer.subscription.deleted` → Cancel subscription

---

## AI Model Costs (Azure OpenAI)

Pricing as of February 2026, defined in `UsageMonitorService::MODEL_PRICING`:

| Model | Input Cost (per 1M tokens) | Output Cost (per 1M tokens) | Deployment | Typical Use |
|-------|---------------------------|----------------------------|------------|-------------|
| **GPT-5.2** | $1.75 | $14.00 | `gpt-5.2-academiaplayground` | General-purpose (main model) |
| **GPT-4o-mini** | $0.15 | $0.60 | `shamraacademiaslm` | Lightweight ops (keywords, citations, tashkeel) |
| **GPT-4o** | $2.50 | $10.00 | — | Standard ops (chat, generate) |
| **GPT-4.5 Preview** | $5.00 | $15.00 | — | Complex ops (research plans, deep analysis) |
| **Mistral Document AI** | $5.00 per 1K pages | — | — | OCR / PDF extraction |

### Cost Calculation Formula

```
cost = (input_tokens / 1000) × input_rate + (output_tokens / 1000) × output_rate
```

All costs are calculated per-request and stored with 6-decimal precision in `PlaygroundUsageLog.costUsd`.

---

## Gross Margin Analysis

### Estimated Cost per Credit

The platform estimates **$0.003 per credit** based on the following assumptions:
- Average ~1.5 credits per API call
- Weighted average API cost ~$0.002/call (heavily weighted toward GPT-4o-mini)
- Formula: `estimated_cost = monthly_credits × $0.003`

### Gross Margin per Subscription Tier (Monthly)

| Tier | Monthly Price | Credits/mo | Est. Azure Cost | Gross Margin ($) | Gross Margin (%) |
|------|--------------|------------|-----------------|------------------|------------------|
| **Basic** | $4.99 | 0 | $0.00 | $4.99 | ~100% |
| **Starter** | $9.00 | 500 | $1.50 | $7.50 | ~83% |
| **Researcher** | $19.00 | 1,500 | $4.50 | $14.50 | ~76% |
| **Professional** | $39.00 | 4,000 | $12.00 | $27.00 | ~69% |
| **Institution** | $99.00 | 15,000 | $45.00 | $54.00 | ~55% |

> **Note:** These are *estimated* margins assuming 100% credit utilization. In practice, most users don't exhaust their full credit allowance, so actual margins are higher.

### Gross Margin per Subscription Tier (Yearly)

| Tier | Yearly Price | Est. Annual Azure Cost (12 months) | Gross Margin ($) | Gross Margin (%) |
|------|-------------|-----------------------------------|------------------|------------------|
| **Basic** | $49.99 | $0.00 | $49.99 | ~100% |
| **Starter** | $90.00 | $18.00 | $72.00 | ~80% |
| **Researcher** | $190.00 | $54.00 | $136.00 | ~72% |
| **Professional** | $390.00 | $144.00 | $246.00 | ~63% |
| **Institution** | $990.00 | $540.00 | $450.00 | ~45% |

### Real-world Margin Factors

- **Lower actual utilization:** Most users consume 40–70% of their credits → higher actual margins
- **Model mix:** Starter/Researcher users are restricted to cheaper models (GPT-4o-mini) → lower real cost
- **Higher-tier complexity:** Professional/Institution users access GPT-4.5 which is ~33× more expensive than GPT-4o-mini
- **Profitability calculator** (`/jim19ud83/playground/profitability`) uses historical 6-month data with tier multipliers:
  - Starter: × 0.5
  - Researcher: × 1.5
  - Professional: × 4.0
  - Institution: × 10.0

### Monthly Platform Profit

```
Monthly Profit = Total MRR − Total Monthly Azure API Cost
```

Tracked in real-time on the admin dashboard.

---

## Platform Budget Safeguards

Three layers of budget protection defined in `UsageMonitorService`:

| Budget | Threshold | Alert at 80% | Action on Exceed |
|--------|-----------|--------------|------------------|
| **Daily** | $100 | Warning log | Emergency mode: block Starter users |
| **Weekly** | $500 | Warning log | Warning only |
| **Monthly** | $1,500 | Warning log | Warning only |

### Emergency Mode

When the daily budget ($100) is exceeded:
- **Starter-tier** users are blocked with "high demand" message
- **Researcher / Professional / Institution** users continue unaffected
- Automatically resolves at the start of the next day

---

## Credit Reset Mechanisms

Credits reset monthly through three redundant mechanisms:

| Mechanism | Trigger | Implementation |
|-----------|---------|----------------|
| **Lazy reset** | First API call of the new month | `PlaygroundSubscription::checkAndResetCredits()` |
| **Login reset** | User logs in | `PlaygroundCreditsLoginListener` |
| **Cron job** | Daily scheduled task | `app:reset-playground-credits` command |

This ensures credits are reset even for users who don't log in or make API calls immediately at month start.

---

## Admin Dashboard

Available at `/jim19ud83/playground/dashboard` (requires `ROLE_ADMIN`).

### Dashboard Features

- **Real-time budget monitoring** — Daily/weekly/monthly spend vs. limits
- **Usage statistics** — By operation, by model, by user
- **Daily/hourly trends** — 30-day daily chart + hourly breakdown for today
- **Top users** — Highest consumers this month
- **MRR tracking** — Monthly Recurring Revenue from all active subscriptions
- **Subscription breakdown** — Active subscribers per tier
- **Trial users analytics** — Dedicated tab with trial user list, usage stats, conversion rates, operation breakdown, and 30-day trend chart (`/api/trial-users` endpoint)
- **Error monitoring** — Recent failed API calls
- **Profitability calculator** — Historical cost-per-user analysis at `/jim19ud83/playground/profitability`

### Key Admin Metrics

```
Profit         = MRR − Monthly Azure Cost
Margin %       = (Profit / MRR) × 100
Budget Usage % = (Period Cost / Period Budget) × 100
```
