---
title: "Meter an AI action"
description: "Wrap a Convex action with ai.meteredAction so every call is rate-limited and paid for in prepaid credits: reserve, run, then settle, and a failed run costs nothing."
canonical_url: "https://nuxt-backend.dev/docs/build/ai/metered-actions"
---
# Meter an AI action

> Wrap a Convex action with ai.meteredAction so every call is rate-limited and paid for in prepaid credits: reserve, run, then settle, and a failed run costs nothing.

Version: nuxt-backend 0.6.x · Tab: Build · Kind: how-to · Status: experimental

Every page: [llms.txt](https://nuxt-backend.dev/llms.txt) · Skill for coding agents: [nuxt-backend](https://nuxt-backend.dev/.well-known/skills/nuxt-backend/SKILL.md)

Commands use npm; use your project's package manager.

- [Try it live in the playground](https://nuxt-backend.dev/playground/strips)
- [API reference](https://nuxt-backend.dev/docs/reference/api/ai)
- [Source](https://github.com/qruto/nuxt-backend/blob/main/src/convex/integrations/ai.ts)

- **You get:** a Convex action your users pay for in credits, rate-limited, refused before it spends when the balance is short, and free when it fails.
- **Powered by:** Convex actions, the AI SDK through the gateway, Convex's rate limiter component, and Polar's credit meters and usage events.
- **The package adds:** reserve, run, settle with a release on failure, the caller and membership checks, budgets and the kill switch, token pricing, and catalog errors the page can read.

`ai.meteredAction` is a drop-in for Convex's `action` that charges each call in credits. It checks the caller and the limits, reserves the call's cost, runs your handler, then settles what the run spent. A handler that throws releases the reservation, so a failed run costs nothing. The spend is recorded as a usage event with the billing provider, so per-customer usage shows in its own dashboard with no tables of yours.

<note>

`nuxt-backend/ai` is in the [experimental tier](https://nuxt-backend.dev/docs/ship/releases/stability): the reserve, run, settle model may change shape in a minor release.

</note>

## Set up the AI capability

The scaffold writes `backend/ai.ts`. `setupAi` composes your billing instance, the rate limiter and Convex's persistent text streaming, and hands back `ai.meteredAction` (this page) and `ai.stream` ([Stream a response](https://nuxt-backend.dev/docs/build/ai/streaming)):

```ts [backend/ai.ts]
import { setupAi } from 'nuxt-backend/ai'
import { v } from 'convex/values'
import { components } from './_generated/api'
import { billing } from './billing'
import { rateLimiter } from './rateLimiter'

export const ai = setupAi(components, { billing, rateLimiter })

// A metered action — swap the echo for your model call. Costs 1 credit
// from the 'credits' meter per call (see billing.catalog.ts).
export const transform = ai.meteredAction({
  meter: 'credits',
  args: { prompt: v.string() },
  handler: async (ctx, { prompt }) => {
    // const completion = await yourModel(prompt)
    return { echo: prompt.toUpperCase(), chargedTo: ctx.usage.entityId }
  },
})
```

The `credits` meter is declared in `backend/billing.catalog.ts`, with the plans and packs that grant its credits: see [Define and sync your catalog](https://nuxt-backend.dev/docs/build/billing/catalog).

`setupAi(components, config)` takes:

<field-group>
<field name="billing" type="Billing" :required="true">

Your `setupBilling(...)` instance: it resolves who pays and spends their credits.

</field>

<field name="model" type="AiModel">

The model `ctx.model()` calls when an action names none: a `provider/model` id (`'openai/gpt-5-mini'`), routed through the Convex AI Gateway or the Vercel AI Gateway, or a model object from any AI SDK provider. Needs the `ai` package. See [Choose a model](https://nuxt-backend.dev/docs/build/ai/models).

</field>

<field name="rateLimiter" type="AiRateLimiter">

Your `setupRateLimiter(...)` instance. Each metered action and stream checks its named limit (default `'ai'`) per billing entity before it reserves. Omit it to leave them unthrottled.

</field>

<field name="budget" type="AiBudget">

A credit cap per billing entity and window, `{ units, period, limit? }`, on top of the call limit. Needs `rateLimiter`. See [Cap spend per window](https://nuxt-backend.dev/docs/build/ai/models#cap-spend-per-window).

</field>

<field name="credits" type="AiCreditsConfig">

Hooks that run when a settle takes the balance under `lowBalanceThreshold`, or to zero. See [React to a low balance](https://nuxt-backend.dev/docs/build/ai/models#react-to-a-low-balance).

</field>

<field name="streamTimeout" type="number | false">

How long a started stream may hold its reservation before it is released, in milliseconds. Default 5 minutes; `false` turns the timer off. See [Stream a response](https://nuxt-backend.dev/docs/build/ai/streaming).

</field>

<field name="cors.origin" type="string">

The origin the stream endpoint allows. Defaults to the `SITE_URL` env var, `*` when it is unset.

</field>
</field-group>

A `model` that is no `provider/model` id, and a `budget` without a `rateLimiter`, throw where `setupAi` runs, so the mistake stops the push rather than the first call.

## Define a metered action

```ts [backend/ai.ts]
import { generateText } from 'ai'

export const generate = ai.meteredAction({
  meter: 'credits',
  cost: args => args.long ? 5 : 1,
  limit: 'ai',
  charge: 'success',
  model: 'openai/gpt-5-mini',
  args: { prompt: v.string(), long: v.optional(v.boolean()) },
  handler: async (ctx, { prompt, long }) => {
    // ctx is the full action ctx, plus ctx.usage and ctx.model()
    const { text } = await generateText({ model: ctx.model(), prompt, maxOutputTokens: long ? 4000 : 800 })
    return text
  },
})
```

<field-group>
<field name="meter" type="string | false" :required="true">

The catalog credit meter to charge, or `false` for an action that is only rate-limited: no reservation and no usage event.

</field>

<field name="cost" type="MeteredCost">

Credits per call. Default `1`. One of:

- a number, or `(args) => number`;
- `{ estimate, finalize }`, to reserve an estimate and settle what the run used: see [Token pricing](#token-pricing);
- `{ estimate, creditsPerUsd }`, to settle at the cost the model calls reported: see [Charge what a call cost](https://nuxt-backend.dev/docs/build/ai/models#charge-what-a-call-cost).

On a `count` meter the cost must be `1`. A metered cost must be a finite number above zero; anything else throws before the limits or the balance count it.

</field>

<field name="limit" type="string | false">

The rate limit checked per billing entity through the configured `rateLimiter`. Default `'ai'`; `false` skips it.

</field>

<field name="charge" type="'success' | 'start'">

When to charge. `'success'`, the default, settles after the handler returns, so a failed run costs nothing. `'start'` settles before the handler runs, for work that is spent upstream the moment it starts, and refunds nothing on failure. A finalized or reported cost needs the run, so under `'start'` the estimate settles.

</field>

<field name="allowOverage" type="boolean">

Let the spend take the balance below zero instead of refusing it, for a pay-as-you-go meter with no credits behind it, whose usage the provider invoices at the end of the cycle. Off by default: credits stay prepaid.

</field>

<field name="model" type="AiModel">

The model `ctx.model()` calls, over `setupAi`'s. Naming one also refuses the call before anything is counted when this deployment cannot reach it.

</field>

<field name="args / handler">

Convex validators, and `(ctx, args) => Promise<Result>`. The handler's `ctx` is the action context plus `ctx.usage` and `ctx.model`.

</field>
</field-group>

In the handler:

- **ctx.usage** holds `entityId` (the workspace or person charged), `userId` (the member who called), `meter`, and `cost` (the estimate, for a cost settled after the run).
- **ctx.model(model?)** returns an AI SDK model, the action's own or another, and records every call made through it for the settle. See [Choose a model](https://nuxt-backend.dev/docs/build/ai/models).

### What happens on each call

1. **Cost.** A metered call whose cost is not a finite number above zero throws before anything counts it.
2. **Caller.** Without a session the call is refused with `unauthenticated`. The billing entity resolves from the session: the active workspace, or the person under `billTo: 'user'`. The caller must be a member of it, read fresh on every call. An administrator impersonating the member is refused (`forbidden`, reason `impersonating`). No workspace at all refuses with `no_workspace`.
3. **Kill switch.** With `pause_ai` on, the call is refused with `unavailable` (reason `ai_paused`). See [Pause AI](https://nuxt-backend.dev/docs/build/ai/models#pause-ai).
4. **Model.** When the action names its model, or settles from its reported cost, a model this deployment cannot reach is refused with `unavailable` (reason `not_configured`).
5. **Rate limit.** The named limit is checked, keyed by the billing entity. Over it, the call is refused with `rate_limited`, the limit's name and `retryAfter`.
6. **Budget.** With a `budget`, the call's cost counts against the entity's window until the call closes. Over it, the call is refused with `rate_limited` and the budget's limit name (`aiBudget` by default).
7. **Reserve.** The cost, or the estimate, comes off the cached balance at once. Too few credits refuses the call with `insufficient_credits`, carrying `balance` and `need`, unless `allowOverage` is set.
8. **Run.** Your handler runs.
9. **Settle or release.** A run that returns settles: the usage event is sent at the final cost with the caller's id, the rest of the estimate goes back to the balance and the `budget` window, and the [low-balance hooks](https://nuxt-backend.dev/docs/build/ai/models#react-to-a-low-balance) run if the balance crossed a line. A run that throws releases the reservation, gives the `budget` its estimate back and rethrows, and so does one whose every model call failed. Under `charge: 'start'`, the settle happens before the run instead.

From the caller check on, each refusal is a [catalog error](https://nuxt-backend.dev/docs/reference/backend/errors) that keeps its code in production, and `getBackendError(error)` reads it in the browser ([Handle errors](https://nuxt-backend.dev/docs/build/data/read-write/errors)). A bad cost is a bug in the action, so it throws a plain error instead.

## Token pricing

A model call's cost is known only once it returns. `cost: { estimate, finalize }` reserves the estimate, runs the handler, then settles what `finalize` computes from the result, and hands the rest back to the balance in the same step. `priceTokens` does the arithmetic: a price table your app owns, applied to the token usage the SDK reports. No provider knows your margin, and rates change often, so the table is yours to keep.

```ts [backend/ai.ts]
import { generateText } from 'ai'
import { priceTokens, type TokenPriceTable, type TokenUsage } from 'nuxt-backend/ai'

// Credits per million tokens, per model id.
const prices: TokenPriceTable = {
  'openai/gpt-5-mini': { input: 3, output: 15, per: 1_000_000 },
  'anthropic/claude-sonnet-4.5': { input: 15, output: 75, cachedInput: 1.5, per: 1_000_000 },
}

export const generate = ai.meteredAction({
  meter: 'credits',
  cost: {
    estimate: 200,   // the ceiling: reserved up front, refunded down to the final cost
    finalize: (result: { usage: TokenUsage }) => priceTokens(result.usage, prices, { round: 'up' }),
  },
  args: { prompt: v.string() },
  handler: async (ctx, { prompt }) => {
    const { text, usage } = await generateText({ model: ctx.model('openai/gpt-5-mini'), prompt })
    // Return the usage: `finalize` prices what the handler returns.
    return { text, usage: { model: 'openai/gpt-5-mini', input: usage.inputTokens ?? 0, output: usage.outputTokens ?? 0 } }
  },
})
```

- **The estimate is the ceiling.** A final amount above it is clamped down and logged (`ai.cost_over_reservation`, "Raise the estimate."). The reservation is what made the spend safe against a concurrent one, so settling past it would be a second, unguarded debit. Estimate high: an over-estimate costs nothing once it settles, though it must fit the balance to reserve, and it holds that much of a `budget` window while the run is in flight.
- **A cost that is not an amount settles at the ceiling too.** When `finalize` returns `NaN`, an infinity or a negative number, the reservation is charged and the bug logged: the run is done and its result reaches the caller, but the bad value never reaches the balance. A `finalize` that returns `0` sends nothing and hands the whole reservation back.
- **Sum meters only.** The final amount rides in the usage event's metadata; a `count` meter counts one per event.
- **charge: 'success' only.** A finalized cost needs the result; under `'start'` the estimate settles.
- `estimate` may also be `(args) => number`, and `finalize(result, usage)` receives `ctx.usage` second. `result` is typed from what `handler` returns: annotate it, as above, or list `handler` before `cost` so inference has seen it.

`priceTokens(usage, table, options?)` takes a `TokenUsage` (`model`, `input`, `output`, `cachedInput?`) and a `TokenPriceTable` (model id → `{ input, output, cachedInput?, per? }`, in credits per `per` tokens, default 1; `options.per` sets a table-wide default). `cachedInput` tokens bill at the entry's own rate when it has one, as ordinary input otherwise. `options.round` (`'up'`, `'nearest'` or `'none'`, the default) and `options.minimum` shape the result. A model missing from the table **throws**: a silent 0 would give the call away, and an unpriced model is a deployment mistake worth surfacing.

```ts
priceTokens({ model: 'openai/gpt-5-mini', input: 12_000, output: 800 }, prices) // → 0.048
```

To settle at what the gateway reports each call cost instead, with no table to keep, see [Charge what a call cost](https://nuxt-backend.dev/docs/build/ai/models#charge-what-a-call-cost).

## Call it from the app

```vue [app/pages/transform.vue]
<script setup lang="ts">
import { api } from '#backend/api'

const credits = useCredits({ meter: 'credits' })
const transform = useAction(api.ai.transform)
const result = ref<string>()

async function run(prompt: string) {
  try {
    result.value = (await transform({ prompt })).echo
  }
  catch (error) {
    // A refusal, or your model's error: either way nothing was charged.
    const refusal = getBackendError(error)
    if (refusal?.code === 'insufficient_credits') navigateTo('/pricing')
  }
}
</script>

<template>
  <p>{{ credits.balance.value }} credits</p>
</template>
```

The balance updates live: the cache is debited at the reservation, and the provider's webhook confirms the units consumed. The codes worth handling in the page:

<table>
<thead>
  <tr>
    <th>
      Code
    </th>
    
    <th>
      What to show
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        insufficient_credits
      </code>
    </td>
    
    <td>
      A top-up. <code>
        refusal.data.need
      </code>
      
       is what the call needed, so offer the smallest pack that covers it: see <a href="https://nuxt-backend.dev/docs/build/billing/credits#out-of-credits">
        Out of credits
      </a>
      
      .
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        rate_limited
      </code>
    </td>
    
    <td>
      Try again in <code>
        retryAfter
      </code>
      
       milliseconds. The limit's name says whether calls or the credit budget ran out.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        unavailable
      </code>
    </td>
    
    <td>
      AI is paused (<code>
        ai_paused
      </code>
      
      ), not set up on this deployment (<code>
        not_configured
      </code>
      
      ), or the model failed (<code>
        provider_refused
      </code>
      
      , worth a retry).
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        forbidden
      </code>
    </td>
    
    <td>
      The caller is not a member of the paying workspace, or is an administrator acting as them.
    </td>
  </tr>
</tbody>
</table>

[Handle errors](https://nuxt-backend.dev/docs/build/data/read-write/errors) shows how to put each one in the person's language. To check what people type before it reaches the model, add `moderate` ([Keep content safe](https://nuxt-backend.dev/docs/build/ai/content-safety#check-prompts)).

## A complete feature

This recipe builds a "draft a reply" feature. A signed-in member pastes a customer's message, and a model streams a draft reply into the page. Each draft is paid for in credits from the workspace's balance, settled at what the model cost, and a draft that fails costs nothing. The page shows the balance, and offers a way to buy credits when a draft is refused for lack of them. A daily budget caps what one workspace can spend, and the activity trail notes when its balance runs low.

It runs on your dev deployment from the first try, against a real model and your billing sandbox. Start from the starter, or any app where `npx nuxt-backend dev` runs, with a model route set up ([Develop and test](https://nuxt-backend.dev/docs/build/ai/models#develop-and-test)).

### The files

<code-tree default-value="backend/ai.ts">

```ts [backend/billing.catalog.ts]
import { defineBillingCatalog } from 'nuxt-backend/billing'

export default defineBillingCatalog({
  // A sum meter: a draft settles at any number of credits.
  meters: { credits: {} },
  plans: {
    starter: {
      name: 'Starter',
      prices: { month: 900, year: 9000 },
      credits: { meter: 'credits', units: 100 },
    },
  },
  packs: {
    credits100: { name: '100 credits', price: 1000, credits: { meter: 'credits', units: 100 } },
    credits500: { name: '500 credits', price: 4000, credits: { meter: 'credits', units: 500 } },
  },
})
```

```ts [backend/ai.ts]
import { streamText } from 'ai'
import { setupAi } from 'nuxt-backend/ai'
import { backendError } from 'nuxt-backend/functions'
import { DAY } from 'nuxt-backend/rate-limit'
import { v } from 'convex/values'
import { components } from './_generated/api'
import { billing } from './billing'
import { rateLimiter } from './rateLimiter'

export const ai = setupAi(components, {
  billing,
  rateLimiter,
  model: 'openai/gpt-5-mini',
  // At most 200 credits a day per workspace, on top of the `ai` call limit.
  budget: { units: 200, period: DAY },
  // Records billing.credits_low in the workspace's activity when a draft takes it under 20.
  credits: { lowBalanceThreshold: 20 },
})

const MAX_MESSAGE = 4000

export const { start: startDraft, body: draftBody } = ai.stream({
  name: 'draft',
  meter: 'credits',
  // Reserve 10, then settle at what the model reported: 1 credit per tenth of a cent, 1 at least.
  cost: { estimate: 10, creditsPerUsd: 1000, round: 'up', minimum: 1 },
  args: { message: v.string() },
  handler: async (ctx, { message }, { append }) => {
    // Checked before the model runs; the refusal releases the reservation.
    if (message.length > MAX_MESSAGE) {
      throw backendError('invalid_input', { field: 'message', message: `Up to ${MAX_MESSAGE} characters.` })
    }
    const result = streamText({
      model: ctx.model(),
      system: 'Draft a short, friendly reply to this customer message, in plain text.',
      prompt: message,
      maxOutputTokens: 400,
    })
    for await (const chunk of result.textStream) await append(chunk)
  },
})
```

```vue [app/pages/draft.vue]
<script setup lang="ts">
import { api } from '#backend/api'

definePageMeta({ auth: true })

const message = ref('')
const credits = useCredits({ meter: 'credits' })
const draft = useAiStream({ start: api.ai.startDraft, body: api.ai.draftBody })

// What a refused draft needed, to say how many credits to buy.
const need = computed(() => {
  const error = draft.error.value
  return error?.code === 'insufficient_credits' ? error.data.need : undefined
})

function write() {
  if (draft.isStreaming.value) return
  // A refusal lands in draft.error, shown below.
  draft.start({ message: message.value }).catch(() => {})
}
</script>

<template>
  <p>{{ credits.balance.value ?? '…' }} credits left</p>
  <textarea v-model="message" maxlength="4000" placeholder="Paste the customer's message" />
  <button :aria-disabled="draft.isStreaming.value || undefined" @click="write">
    Draft a reply
  </button>
  <button v-if="draft.isStreaming.value" @click="draft.stop()">
    Stop
  </button>
  <p v-if="need" role="alert">
    This draft needs {{ need }} credits. <NuxtLink to="/pricing">Buy credits</NuxtLink>
  </p>
  <p v-else-if="draft.error.value" role="alert">
    {{ draft.error.value.message }}
  </p>
  <pre aria-live="polite">{{ draft.text.value }}</pre>
</template>
```

</code-tree>

### How it fits together

#### Price the feature in credits

The catalog declares the `credits` meter, a plan that grants 100 credits a month, and two packs that top it up. `npx nuxt-backend billing sync` creates them in your billing sandbox, and `--env production` in production. See [Define and sync your catalog](https://nuxt-backend.dev/docs/build/billing/catalog).

The meter is a sum meter, the default, because a draft settles at however many credits the model's cost comes to. A count meter could only ever charge one per call.

#### Stream the draft and charge what it cost

`ai.stream` reserves 10 credits before the model runs. When the stream ends, it settles at what the gateway reported the call cost, at 1,000 credits a dollar, rounded up, never under 1, and gives the rest of the 10 back. A stream that fails, or that the person stops, releases all 10. See [Stream a response](https://nuxt-backend.dev/docs/build/ai/streaming) and [Charge what a call cost](https://nuxt-backend.dev/docs/build/ai/models#charge-what-a-call-cost).

The estimate is the ceiling: a draft that cost more settles at 10, and the log says `ai.cost_over_reservation`. `maxOutputTokens: 400` keeps a draft well under it.

#### Cap the spend

The `ai` limit, 30 calls a minute per workspace by default, stops a runaway loop. The `budget` stops a workspace from spending more than 200 credits a day on drafts, whatever its balance. `lowBalanceThreshold` records `billing.credits_low` in the workspace's activity the moment a draft takes the balance under 20. See [Set budgets and track costs](https://nuxt-backend.dev/docs/build/ai/models#budgets-and-costs).

#### Show the balance and the way back

`useCredits` reads the balance live: it drops the moment a draft reserves, and settles when the draft ends. A draft refused for `insufficient_credits` carries `need`, what it would have reserved, so the page says how many credits to buy. Under 20 credits, `<BackendNotices>` in your app's layout shows the low-credit notice on every page, with a button that buys the smallest pack that covers the shortfall. A member who cannot buy for the workspace gets a link to the pricing page instead. See [Credits & top-ups](https://nuxt-backend.dev/docs/build/billing/credits).

### Try it on your dev deployment

1. With `npx nuxt-backend dev` running, sign in and open `/draft`. Under 20 credits, the low-credit notice offers a pack.
2. Buy one with the sandbox's test card, `4242 4242 4242 4242`. The balance updates once the billing provider's webhook arrives.
3. Paste a message and draft a reply. The model's answer streams in word by word, and the balance drops by what it cost, 1 credit at least.
4. As an administrator, turn on **Pause AI** in the admin console's Flags tab (`/admin?tab=flags`), then draft again: the page shows "AI features are paused for now. Try again later." and the balance stays put. Turn it off.

To pick a draft up again after a reload, keep its stream id in the route's query: see [Resume after a reload](https://nuxt-backend.dev/docs/build/ai/streaming#resume-after-a-reload).

### Before launch

- [ ] The catalog is synced to production: `npx nuxt-backend billing sync --env production`.
- [ ] A model route is ready on production: the Convex AI Gateway (a paid Convex plan, `@convex-dev/ai-sdk-provider` installed), or production's own `AI_GATEWAY_API_KEY`, set with `npx convex env set --prod AI_GATEWAY_API_KEY`. Without either, every draft is refused with `unavailable` (reason `not_configured`).
- [ ] The gateway has a spending cap above what your daily budgets add up to across your workspaces: see [Cap what the gateway spends](https://nuxt-backend.dev/docs/build/ai/models#cap-what-the-gateway-spends).
- [ ] `npx nuxt-backend doctor --prod` passes `deployment-ai-gateway-api-key` and `ai-stream-route`.
- [ ] You know where the `pause_ai` switch is: the admin console's Flags tab.

[Prepare for launch](https://nuxt-backend.dev/docs/ship/checklist) has the rest of the list.

## Related

- [AI gateway](https://nuxt-backend.dev/docs/services/ai-gateway): the model route and its spending cap.
- [Stream a response](https://nuxt-backend.dev/docs/build/ai/streaming): the same metering around a token stream.
- [Choose a model](https://nuxt-backend.dev/docs/build/ai/models): `ctx.model()`, reported costs, budgets and the kill switch.
- [Spend credits in your functions](https://nuxt-backend.dev/docs/build/billing/credits/spending): the reservation underneath, for spends that are not model calls.
- [Run generation jobs](https://nuxt-backend.dev/docs/build/ai/jobs): work too long for one action, queued, with credits held until it starts.


## Sitemap

See the full [sitemap](https://nuxt-backend.dev/sitemap.md) for all pages.
