# Pricing & Analytics

> OpenGen expresses all prices and balances in positive integer micro-USD (1 USD equals 1,000,000 micro-USD) sourced strictly from @media-router/catalog, with unknown prices kept null and never zero. Inspect published rates at GET /v1/pricing, run side-effect-free estimates at POST /v1/pricing/estimate, check credit at GET /v1/balance, and query 31-day spend and latency rollups at GET /v1/analytics.

## Agent Prompt

```text
Estimate costs and audit workspace spend cleanly using https://opengen.dev/docs/pricing-and-analytics:
1. Read single-source published rates via GET https://opengen.dev/v1/pricing (or MCP resource opengen://pricing); treat series-page Pricing at a Glance starting rates as catalog list rates only. Remember 1 USD = 1,000,000 micro-USD, and null/Unknown means unknown or unsettled — never treat it as free or $0.
2. Always run stateless POST https://opengen.dev/v1/pricing/estimate (or MCP estimate_cost) with the exact generation payload and check GET https://opengen.dev/v1/balance (or MCP balance) before asking the user to approve a maxCostMicros spend ceiling.
3. Pass maxCostMicros and private metadata ({ project, tags }) on POST https://opengen.dev/v1/generations (with a persisted Idempotency-Key), then monitor settledMicros, heldMicros, byKey, byTag, and p50Ms/p95Ms latency cohorts via GET https://opengen.dev/v1/analytics or MCP analytics.
```

## Single-source micro-USD pricing

OpenGen represents every price, reservation, settlement, and balance as an exact **integer in micro-USD**, where **`1 USD = 1,000,000 micro-USD`** (`$0.01 = 10,000` micro-USD; `$0.00598 = 5,980` micro-USD).

- **Single source of truth**: All per-unit `rates`, `publishedPricing`, and dated credential-free HTTPS `pricingSource` links are defined once in `@media-router/catalog` and projected identically across `GET /v1/pricing`, `GET /v1/routes`, `GET /v1/models/{provider}/{model}`, MCP `get_model` / `opengen://pricing`, `@opengen-dev/cli`, [/pricing](/pricing), and every `/[provider]/[series]` page (plus its `.md` twin).
- **Modality-matched billing units**: `image`, `output-second`, `character-1k`, and `megapixel`.
- **Honest unknowns**: When a provider does not publish a deterministic per-request formula or a route has media-dependent token billing, OpenGen keeps prices `null` or omitted — **never** `$0` or "free".

## Interpreting series-page Pricing at a Glance

Every model series page (`/[provider]/[series]`, such as `/bytedance/seedance-2.5` or `/alibaba/wan-3.0`) and its Markdown twin (`/[provider]/[series].md` / `Accept: text/markdown`) includes an above-the-fold **Pricing at a Glance** prose lead and `Provider | Unit Price | Cost per 1,000 ... | Region` summary table derived strictly from `@media-router/catalog`:

- **Starting list rate per provider**: Each provider row reports that provider's lowest published starting rate across active (non-retired) routes in the series, labeled with the exact variant and default resolution/quality tier it represents. Rates marked with `≈` are approximate or token-derived estimates; providers with unpriced or mixed-unit routes show `Unknown` (`—` for per-1,000 cost) rather than `$0`.
- **Exact-unit per-1,000 column**: The per-1,000 column (`Cost per 1,000 images`, `Cost per 1,000 sec`, `Cost per 1,000 MP`, or `Cost per 1,000 (1M chars)`) is computed only when all priced variants in the series share a common billing unit and the provider row matches that unit; mixed-unit or unpriced rows fall back to `Cost per 1,000` with `—` and are never cross-unit sorted.
- **Exact variant boundaries**: `Lowest` badges and cross-provider savings percentages compare only providers serving the **same exact `modelId` and billing unit** when at least two providers quote different positive rates — never across distinct derivatives (such as `Fast` vs `Standard`).
- **Regional spread and unified review date**: Region cells show disclosed endpoint regions for the provider's lowest rate and distinguish higher-priced regions (`+SG higher`), regions serving other variants (`+... other variants`), and unpriced regions (`+... unpriced`) without implying data residency. The `Checked YYYY-MM-DD` / `Latest catalog source check` date is unified across the HTML summary, Markdown twin, JSON-LD, and sitemap.
- **Not an executable quote or spend cap**: Summary starting rates include `documented` catalog routes and lowest default tiers. Higher resolutions, audio-on tiers, edit operations, or regional pins can cost more, and route executability depends on the target gateway and workspace policy. Always inspect `GET /v1/models/{provider}/{model}?operation=<op>` (or MCP `get_model`) and run stateless `POST /v1/pricing/estimate` (or MCP `estimate_cost`) with the exact canonical request before approving spend or setting `maxCostMicros`.

## Pricing and account endpoints (4 routes)

| Endpoint                    | Operation ID       | Auth                                | Purpose                                                                                                                                                                                                                                                                                            |
| --------------------------- | ------------------ | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /v1/pricing`           | `pricing.list`     | Public (`max-age=60, s-maxage=300`) | Lists published per-unit route rates, `publishedPricing`, `pricingSource`, `operationPricing`, and `status` / `liveVerification`. Filters: `modelId`, `routeId`, `providerId`, `endpointRegion`, `modality`, `operation`                                                                           |
| `POST /v1/pricing/estimate` | `pricing.estimate` | Public or `read` (CORS `*`)         | Stateless, side-effect-free dry-run estimator. Validates the exact generation request, returns per-route `estimatedCostMicros`, `recommendedMaxCostMicros`, `reservationMicros`, `estimateOnly: true`, and `workspaceEligibility` when authenticated. Never reserves credits or creates a quote ID |
| `GET /v1/balance`           | `balance.get`      | `read` (`no-store`)                 | Returns `{ availableMicros, reservedMicros, currency: "USD" }`. Supports optional `X-OpenGen-Expected-Workspace` header (`409 workspace_changed` on mismatch). MCP `balance` adds `workspaceId`, plus `billingUrl` and `minTopUpUsd` (`5`) when hosted top-ups are enabled                         |
| `GET /v1/analytics`         | `analytics.get`    | `read` (`no-store`)                 | Bounded private workspace spend (`settledMicros`, `heldMicros`, `unknownAccountingCount`, `byKey`, `byTag`) and per-model/route reliability & latency `cohorts` (`p50Ms`, `p95Ms`) over a date window up to **31 days** (default last 7 days)                                                      |

### Querying published tariffs and running dry-run estimates

```bash tab="cURL"
# Inspect published pricing across all serving providers for one exact variant
curl --fail-with-body \
  "$OPENGEN_API_URL/v1/pricing?modelId=openai%2Fgpt-image-2&operation=text-to-image"

# Stateless dry-run cost and route-eligibility estimate (no credit hold)
curl --fail-with-body -X POST "$OPENGEN_API_URL/v1/pricing/estimate" \
  -H "Authorization: Bearer $OPENGEN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "modelId": "openai/gpt-image-2",
    "operation": "text-to-image",
    "input": {
      "prompt": "Technical isometric diagram of a copper espresso boiler",
      "resolution": "1K",
      "quality": "low"
    },
    "billing": "managed"
  }'
```

```ts tab="TypeScript"
const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev';

const tariffs = await fetch(
  `${baseUrl}/v1/pricing?modelId=${encodeURIComponent('openai/gpt-image-2')}`,
).then((r) => r.json());

const estimate = await fetch(`${baseUrl}/v1/pricing/estimate`, {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    modelId: 'openai/gpt-image-2',
    operation: 'text-to-image',
    input: {
      prompt: 'Technical isometric diagram of a copper espresso boiler',
      resolution: '1K',
      quality: 'low',
    },
    billing: 'managed',
  }),
}).then((r) => r.json());

console.log(
  tariffs.data.length,
  estimate.lowestEstimatedCostMicros,
  estimate.recommendedMaxCostMicros,
);
```

```python tab="Python"
import os
import httpx

base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev")
headers = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"}

with httpx.Client(base_url=base_url, timeout=30.0) as client:
    tariffs = client.get(
        "/v1/pricing",
        params={"modelId": "openai/gpt-image-2", "operation": "text-to-image"},
    ).raise_for_status().json()

    estimate = client.post(
        "/v1/pricing/estimate",
        headers=headers,
        json={
            "modelId": "openai/gpt-image-2",
            "operation": "text-to-image",
            "input": {
                "prompt": "Technical isometric diagram of a copper espresso boiler",
                "resolution": "1K",
                "quality": "low",
            },
            "billing": "managed",
        },
    ).raise_for_status().json()

print(len(tariffs["data"]), estimate["recommendedMaxCostMicros"])
```

```json tab="MCP"
{
  "tool": "estimate_cost",
  "arguments": {
    "modelId": "openai/gpt-image-2",
    "operation": "text-to-image",
    "input": {
      "prompt": "Technical isometric diagram of a copper espresso boiler",
      "resolution": "1K",
      "quality": "low"
    },
    "billing": "managed"
  }
}
```

```bash tab="CLI"
opengen pricing --model openai/gpt-image-2 --operation text-to-image
opengen pricing estimate --input request.json
```

## Managed credit vs BYOK (Bring Your Own Key)

| Dimension             | Managed Credit (`"billing": "managed"`)                                                                                                      | Bring Your Own Key (`"billing": "byok"`)                                                          |
| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| Provider credentials  | OpenGen-operated supplier accounts                                                                                                           | Your own encrypted provider keys stored per deployment in `/app/providers`                        |
| Funding & billing     | Prepaid USD workspace balance via `/billing` (new workspaces start at `$0`; `$5` USD minimum top-up)                                         | Provider bills your supplier account directly; OpenGen reserves `$0` managed credit               |
| Reservation & ceiling | Reserves a bounded `reservedMicros` ceiling at admission, settles actual `settledMicros`, and releases unused hold back to `availableMicros` | No managed credit reservation; still enforces governance routing policies and workspace isolation |
| Spend guards          | Request `maxCostMicros`, key `monthlyCapMicros`, and policy `maxCostMicros`                                                                  | Governance routing policy (`modelIds`, `providerIds`, `endpointRegions`)                          |

> [!IMPORTANT]
> **`settledMicros: null` never means free.** On an in-flight, `submission-unknown`, or awaiting-reconciliation managed job, `settledMicros` remains `null` while `reservedMicros` stays held until verified provider cost or confirmed non-billable failure/cancellation is recorded.

## Workspace balance and 31-day analytics (`GET /v1/analytics`)

`GET /v1/analytics` (and MCP `analytics`) provides private operational visibility across a bounded window of at most **31 days** (defaulting to the last 7 days when `since`/`until` are omitted). Filter by `since` (inclusive ISO-8601 UTC), `until` (exclusive ISO-8601 UTC), `modelId`, `providerId`, `deploymentId`, `endpointRegion`, `operation`, `keyId`, `status`, or `project`.

Each response returns:

- **Top-level accounting**: `sampleCount`, `settledMicros`, `heldMicros`, `unknownAccountingCount` (jobs whose accounting is unsettled/unknown rather than silently treated as zero), plus truncation indicators (`truncated`, `attributionTruncated`, `tagsTruncated`).
- **Spend attribution**: `byKey[]` (per API key ID) and `byTag[]` (per `metadata.tags` key/value pair).
- **Per-route cohorts (`cohorts[]`)**: grouped by `modelId`, `operation`, `routeId`, `deploymentId`, and `configurationFingerprint`, reporting `succeeded`, `failed`, `cancelled`, `unresolved`, `delivered`, `unverifiedDelivery`, and observed `p50Ms` / `p95Ms` across `providerOutcomeLatency`, `queueLatency`, `executionLatency`, `deliveryLatency`, and `endToEndLatency`.

```bash tab="cURL"
# Check workspace balance
curl --fail-with-body "$OPENGEN_API_URL/v1/balance" \
  -H "Authorization: Bearer $OPENGEN_API_KEY"

# Query 7-day workspace spend and latency analytics for a project
curl --fail-with-body \
  "$OPENGEN_API_URL/v1/analytics?project=catalog-hero&since=2026-11-25T00:00:00Z&until=2026-12-02T00:00:00Z" \
  -H "Authorization: Bearer $OPENGEN_API_KEY"
```

```ts tab="TypeScript"
const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev';
const headers = { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}` };

const analytics = await fetch(
  `${baseUrl}/v1/analytics?project=catalog-hero&since=2026-11-25T00:00:00Z&until=2026-12-02T00:00:00Z`,
  { headers },
).then((r) => r.json());

console.log({
  samples: analytics.sampleCount,
  settledMicros: analytics.settledMicros,
  heldMicros: analytics.heldMicros,
  cohorts: analytics.cohorts.length,
});
```

```python tab="Python"
import os
import httpx

base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev")
headers = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"}

response = httpx.get(
    f"{base_url}/v1/analytics",
    headers=headers,
    params={
        "project": "catalog-hero",
        "since": "2026-11-25T00:00:00Z",
        "until": "2026-12-02T00:00:00Z",
    },
    timeout=30.0,
)
response.raise_for_status()
data = response.json()
print(data["sampleCount"], data["settledMicros"], data["heldMicros"])
```

```json tab="MCP"
{
  "tool": "analytics",
  "arguments": {
    "project": "catalog-hero",
    "since": "2026-11-25T00:00:00Z",
    "until": "2026-12-02T00:00:00Z"
  }
}
```

```bash tab="CLI"
opengen balance
opengen call analytics.get --input - <<< '{"project":"catalog-hero","since":"2026-11-25T00:00:00Z","until":"2026-12-02T00:00:00Z"}'
```

> [!TIP]
> Tag every production generation with `metadata: { project, tags }` on `POST /v1/generations` so `byTag` rollups in `GET /v1/analytics` break down spend by tenant, feature, or environment without leaking customer identifiers into public logs.
