> ## Documentation Index
> Fetch the complete documentation index at: https://getlago.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Bill per token: replicate OpenAI pricing with contracts

> Rebuild OpenAI's per-token pricing in Lago with a metered product, product filters per model and token type, package rates and a contract.

This template builds token-based billing with Lago: one metered product, priced separately per model and token type through product filters. It suits LLM and generative AI companies whose price depends on the model and on whether tokens are input or output.

Legacy (v1): [Clone OpenAI pricing with subscriptions](https://getlago.com/docs/templates/per-token/openai.md).

## Pricing structure

OpenAI prices tokens per 1,000, with a different price per model and per token type.

| Model | Input | Output |
| - | - | - |
| 8K context | \$0.03 / 1,000 tokens | \$0.06 / 1,000 tokens |
| 32K context | \$0.06 / 1,000 tokens | \$0.12 / 1,000 tokens |

## How it maps to Lago

| Pricing element | Lago object |
| - | - |
| Token usage | Billable metric `openai_tokens` (`sum_agg` on `tokens`) with `model` and `type` dimensions |
| What you sell | Metered product `ai_tokens` |
| Model and token type combinations | Four product filters on `ai_tokens` |
| Price per 1,000 tokens | One rate card per filter, with a `package` rate |
| The offer | Plan `openai_payg` with four applied rate cards |
| The customer agreement | Contract `contract_example` |

## Get started

**1. Set up Lago**

```bash cURL theme={"dark"}
LAGO_URL="https://api.getlago.com"
API_KEY="__YOUR_API_KEY__"
```

Use `https://api.eu.getlago.com` for the EU cluster. API endpoints live under `/api/v2` and require the product catalog to be enabled on your organization.

**2. Create a billable metric**

Create one billable metric that sums tokens. Declare the `model` and `type` dimensions so product filters can use them.

1. Set `aggregation_type` to `sum_agg`
2. Set `field_name` to `tokens`
3. Set `recurring` to `false`
4. Add `filters` for `model` and `type`

```bash cURL highlight={6,8-21} theme={"dark"}
curl --location --request POST "$LAGO_URL/api/v2/billable_metrics" \
  --header "Authorization: Bearer $API_KEY" \
  --header 'Content-Type: application/json' \
  --data-raw '{
    "billable_metric": {
      "name": "AI tokens",
      "code": "openai_tokens",
      "description": "Token usage across models",
      "aggregation_type": "sum_agg",
      "field_name": "tokens",
      "recurring": false,
      "filters": [
        {
          "key": "model",
          "values": ["8k", "32k"]
        },
        {
          "key": "type",
          "values": ["input", "output"]
        }
      ]
    }
  }'
```

Refer to the [API reference](https://getlago.com/docs/v2/api-reference/billable-metrics/create.md) and the [billable metrics guide](https://getlago.com/docs/v2/guide/billable-metrics/create-billable-metrics.md).

**3. Create a metered product**

Create the product you sell. A metered product requires `billable_metric_code`. Neither the type nor the metric can change after creation.

```bash cURL highlight={7-8} theme={"dark"}
curl --location --request POST "$LAGO_URL/api/v2/products" \
  --header "Authorization: Bearer $API_KEY" \
  --header 'Content-Type: application/json' \
  --data-raw '{
    "product": {
      "name": "AI tokens",
      "code": "ai_tokens",
      "product_type": "metered",
      "billable_metric_code": "openai_tokens"
    }
  }'
```

Refer to the [API reference](https://getlago.com/docs/v2/api-reference/products/create.md) and the [metered products guide](https://getlago.com/docs/v2/guide/product-catalog/metered-products.md).

**4. Create product filters**

Create one product filter per model and token type. Each filter value must be a key and a configured value of the billable metric.

```bash cURL highlight={6,8-11} theme={"dark"}
curl --location --request POST "$LAGO_URL/api/v2/products/ai_tokens/filters" \
  --header "Authorization: Bearer $API_KEY" \
  --header 'Content-Type: application/json' \
  --data-raw '{
    "filter": {
      "name": "8K input",
      "code": "tokens_8k_input",
      "invoice_display_name": "8K context, input tokens",
      "values": [
        { "key": "model", "value": "8k" },
        { "key": "type", "value": "input" }
      ]
    }
  }'
```

Repeat for the other three combinations:

| Filter `code` | `model` | `type` |
| - | - | - |
| `tokens_8k_input` | `8k` | `input` |
| `tokens_8k_output` | `8k` | `output` |
| `tokens_32k_input` | `32k` | `input` |
| `tokens_32k_output` | `32k` | `output` |

Refer to the [API reference](https://getlago.com/docs/v2/api-reference/product-filters/create.md) and the [product filters guide](https://getlago.com/docs/v2/guide/product-catalog/product-filters.md).

**5. Create a rate card per filter**

Create one rate card per filter. The rate card targets the filter with `product_filter_code` and holds the currency and billing timing. Its initial rate uses the `package` model: `amount` per `package_size` tokens.

```bash cURL highlight={7-11,14-23} theme={"dark"}
curl --location --request POST "$LAGO_URL/api/v2/rate_cards" \
  --header "Authorization: Bearer $API_KEY" \
  --header 'Content-Type: application/json' \
  --data-raw '{
    "rate_card": {
      "name": "8K input tokens USD",
      "code": "tokens_8k_input_usd",
      "product_code": "ai_tokens",
      "product_filter_code": "tokens_8k_input",
      "currency": "USD",
      "billing_timing": "arrears",
      "proration": false,
      "rates": [
        {
          "code": "tokens_8k_input_standard",
          "effective_from": "2027-01-01T00:00:00Z",
          "rate_model": "package",
          "rate_properties": {
            "amount": "0.03",
            "package_size": 1000,
            "free_units": 0
          },
          "billing_interval_count": 1,
          "billing_interval_unit": "month"
        }
      ]
    }
  }'
```

Repeat for the other filters:

| Rate card `code` | `product_filter_code` | `amount` | `package_size` |
| - | - | - | - |
| `tokens_8k_input_usd` | `tokens_8k_input` | `"0.03"` | `1000` |
| `tokens_8k_output_usd` | `tokens_8k_output` | `"0.06"` | `1000` |
| `tokens_32k_input_usd` | `tokens_32k_input` | `"0.06"` | `1000` |
| `tokens_32k_output_usd` | `tokens_32k_output` | `"0.12"` | `1000` |

Refer to the [API reference](https://getlago.com/docs/v2/api-reference/rate-cards/create.md), the [rate cards guide](https://getlago.com/docs/v2/guide/rate-cards/overview.md) and the [package model](https://getlago.com/docs/v2/guide/rate-cards/pricing-models/package.md).

**6. Create a plan and apply the rate cards**

Create the plan in the same currency as the rate cards.

```bash cURL highlight={6-7} theme={"dark"}
curl --location --request POST "$LAGO_URL/api/v2/plans" \
  --header "Authorization: Bearer $API_KEY" \
  --header 'Content-Type: application/json' \
  --data-raw '{
    "plan": {
      "name": "OpenAI pay as you go",
      "code": "openai_payg",
      "currency": "USD"
    }
  }'
```

Apply each of the four rate cards. Only one rate card can price each product and filter combination.

```bash cURL highlight={6} theme={"dark"}
curl --location --request POST "$LAGO_URL/api/v2/plans/openai_payg/applied_rate_cards" \
  --header "Authorization: Bearer $API_KEY" \
  --header 'Content-Type: application/json' \
  --data-raw '{
    "applied_rate_card": {
      "rate_card_code": "tokens_8k_input_usd"
    }
  }'
```

Refer to the [API reference](https://getlago.com/docs/v2/api-reference/plan-applied-rate-cards/create.md) and the [plans guide](https://getlago.com/docs/v2/guide/plans/overview.md).

**7. Create a customer**

```bash cURL highlight={6} theme={"dark"}
curl --location --request POST "$LAGO_URL/api/v2/customers" \
  --header "Authorization: Bearer $API_KEY" \
  --header 'Content-Type: application/json' \
  --data-raw '{
    "customer": {
      "external_id": "customer_example",
      "name": "Acme Corp",
      "email": "billing@example.com",
      "currency": "USD"
    }
  }'
```

An existing `external_id` returns `422` instead of updating the customer. Refer to the [API reference](https://getlago.com/docs/v2/api-reference/customers/create.md) to create a customer.

**8. Create a contract**

Create a contract for the customer. Replace `__PLAN_CODE__` with `openai_payg`.

```bash cURL highlight={6-10} theme={"dark"}
curl --location --request POST "$LAGO_URL/api/v2/contracts" \
  --header "Authorization: Bearer $API_KEY" \
  --header 'Content-Type: application/json' \
  --data-raw '{
    "contract": {
      "external_id": "contract_example",
      "external_customer_id": "customer_example",
      "plan_code": "__PLAN_CODE__",
      "started_at": "2027-01-01T00:00:00Z",
      "billing_anchor_date": "2027-02-01"
    }
  }'
```

The plan supplies the contract's initial applied rate cards. A future `started_at` creates a `pending` contract that becomes `active` on that date. Only one pending or active contract can use a given `external_id` at a time. Refer to the [API reference](https://getlago.com/docs/v2/api-reference/contracts/create.md) to create a contract.

> [!NOTE]
>
> The example dates are in the future. To test right away, set each rate's `effective_from` to today and omit `started_at`, which defaults to now.

**9. Ingest usage via events**

Send usage events that target the contract.

1. Set `code` to the billable metric code
2. Set `external_contract_id` to the contract's `external_id`
3. Send the token count in `tokens`, plus `model` and `type`

```bash cURL highlight={7-12} theme={"dark"}
curl --location --request POST "$LAGO_URL/api/v2/events" \
  --header "Authorization: Bearer $API_KEY" \
  --header 'Content-Type: application/json' \
  --data-raw '{
    "event": {
      "transaction_id": "__TRANSACTION_ID__",
      "code": "openai_tokens",
      "external_contract_id": "contract_example",
      "properties": {
        "tokens": 5000,
        "model": "8k",
        "type": "input"
      }
    }
  }'
```

`external_subscription_id` is not supported on events and returns `422`. Refer to the [API reference](https://getlago.com/docs/v2/api-reference/events/create.md) and the [usage ingestion guide](https://getlago.com/docs/v2/guide/events/ingesting-usage.md).

**10. Monitor current usage**

Track usage across the contract's open billing periods.

```bash cURL highlight={1} theme={"dark"}
curl --location --request GET "$LAGO_URL/api/v2/contracts/contract_example/current_usage" \
  --header "Authorization: Bearer $API_KEY" \
  --header 'Content-Type: application/json'
```

The response returns `amount_cents`, `taxes_amount_cents`, `total_amount_cents` and a `rate_cards` array with usage per applied rate card. Pending contracts have no usage. Totals can span several invoices, so this is not a preview of one invoice. Filter with `rate_card_code`, `product_code`, `product_filter_code` or `product_type`. Refer to the [API reference](https://getlago.com/docs/v2/api-reference/contracts/retrieve-current-usage.md) to get current usage.

## Worked example

Over one full monthly period, the customer sends 500,000 8K input tokens and 200,000 8K output tokens. Token counts are exact multiples of the package size.

| Invoice line | Quantity | Packages | Price | Amount |
| - | - | - | - | - |
| 8K context, input tokens | 500,000 tokens | 500 | \$0.03 per 1,000 | \$15.00 |
| 8K context, output tokens | 200,000 tokens | 200 | \$0.06 per 1,000 | \$12.00 |
| **Total before tax** | | | | **\$27.00** |

## What changed from v1

* Charge filters on a plan become product filters on a metered product. Each filter gets its own rate card.
* Prices live on rates with an `effective_from` date. A new rate changes the price for every plan and contract that does not override it.
* Events target `external_contract_id` instead of `external_subscription_id`.

> [card] [Product filters](https://getlago.com/docs/v2/guide/product-catalog/product-filters.md)
>
> Price subsets of metered usage separately.

> [card] [Package model](https://getlago.com/docs/v2/guide/rate-cards/pricing-models/package.md)
>
> Charge a fixed amount per bundle of units.

> [card] [Contracts](https://getlago.com/docs/v2/guide/contracts/overview.md)
>
> Apply a plan to a customer.

> [card] [Create a rate card (API)](https://getlago.com/docs/v2/api-reference/rate-cards/create.md)
>
> `POST /api/v2/rate_cards`


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.