---
title: "Choose a model"
description: "Call any provider's model by its provider/model id through the Convex AI Gateway, a Vercel AI Gateway key, or both in the order you choose, pin inference to the EU, cap what the gateway may spend, set budgets per workspace, and charge each call at the cost it reports."
canonical_url: "https://nuxt-backend.dev/docs/build/ai/models"
---
# Choose a model

> Call any provider's model by its provider/model id through the Convex AI Gateway, a Vercel AI Gateway key, or both in the order you choose, pin inference to the EU, cap what the gateway may spend, set budgets per workspace, and charge each call at the cost it reports.

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/models.ts)

- **You get:** any provider's model by one id, the same route in development and production, a dollar cap at the gateway, credit budgets per workspace, and each call charged at what it cost.
- **Powered by:** the AI SDK, the [Convex AI Gateway](https://nuxt-backend.dev/docs/services/ai-gateway) (paid Convex plans, no key, a team spending limit), and the Vercel AI Gateway (one key, budgets, EU inference pinning).
- **The package adds:** a gateway order you choose (`setupAi({ gateway })`) with a fallback, `ctx.model()` that records every call's cost, the EU pin as one option, rate limits and budgets per billing entity, low-balance hooks, and the `pause_ai` kill switch.

A metered action or stream names its model as a `provider/model` id, such as `'openai/gpt-5-mini'` or `'anthropic/claude-sonnet-4.5'`. On a paid Convex plan, the id goes through the Convex AI Gateway: Convex holds the providers' keys and bills your team, so the deployment needs no key. Elsewhere it goes through the Vercel AI Gateway with your key. The handler gets the model from `ctx.model()` and runs it with the AI SDK's own `generateText` or `streamText`. Each call reports what it cost, and the run settles its credits at that cost. Development and production take the same route, so what you try locally is what ships.

<note>

The `ai` capability is in the [experimental tier](https://nuxt-backend.dev/docs/ship/releases/stability): its metering model may change shape in a minor release.

</note>

## Install the AI SDK

```bash
npm install ai @convex-dev/ai-sdk-provider
```

Both are optional peer dependencies. `nuxt-backend` imports them only when a handler calls a model, so an app without AI features never installs them:

- **ai** (version 7) is the AI SDK. It also ships the Vercel AI Gateway's provider.
- **@convex-dev/ai-sdk-provider** is Convex's provider for its own gateway. Without it, model ids skip the Convex AI Gateway.

A call made without `ai` is refused with `unavailable` (reason `not_configured`), and the log says to install it.

## Name a model

Set the default on `setupAi`, override it per action or stream, and call it through `ctx.model()`:

```ts [backend/ai.ts]
import { generateText } from 'ai'
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, model: 'openai/gpt-5-mini' })

export const summarize = ai.meteredAction({
  meter: 'credits',
  cost: { estimate: 20, creditsPerUsd: 100, round: 'up', minimum: 1 },
  args: { text: v.string() },
  handler: async (ctx, { text }) => {
    const { text: summary } = await generateText({ model: ctx.model(), prompt: `Summarize: ${text}` })
    return summary
  },
})
```

- **ctx.model()** returns an AI SDK language model, so every SDK function takes it: tools, structured output and multi-step calls included. `ctx.model('google/gemini-2.5-flash')` calls another model in the same run. Every call made through what it returns counts toward the run's cost.
- **model on an action or stream** wins over the one on `setupAi`. Naming it also checks, before anything is counted, that this deployment can reach it. A model reached only at the call, through `ctx.model('…')`, is checked when it is called: an unreachable one is refused there, and the reservation released.
- **A model object of your own**, from any AI SDK provider package, works anywhere an id does. It is called with that provider's own key and reports no gateway cost, so price it by tokens ([Token pricing](https://nuxt-backend.dev/docs/build/ai/metered-actions#token-pricing)), keyed by the object's own `modelId`.
- **streamText does not throw** when its call fails: it hands the error to its `onError` and ends `textStream` as if the answer were done. A run whose every model call failed is refused all the same, with `unavailable` (reason `provider_refused`), and its reservation released.
- **An id must read provider/model.** A bare `gpt-5` fails where it is configured, so a typo stops the push rather than the first call.

The Convex AI Gateway's [model list](https://docs.convex.dev/ai-gateway/models) names every id it answers: text, embedding, image and voice models from OpenAI, Anthropic, Google, xAI and others.

## Where a model id goes

A `provider/model` id goes through the gateways `setupAi({ gateway })` names, in order. Without the option, the order is the Convex AI Gateway, then the Vercel AI Gateway:

1. **The Convex AI Gateway.** It answers on Convex Cloud (development, preview and production deployments) and on a local deployment linked to a project. The action asks the runtime for a short-lived token (`getServiceToken('ai-gateway')`), and Convex bills the calls to your team. It needs a paid plan and `@convex-dev/ai-sdk-provider`.
2. **The Vercel AI Gateway**, with the deployment's `AI_GATEWAY_API_KEY`. The package falls back to it when the Convex AI Gateway answers `AiGatewayDisabled` (a free plan) or `AiGatewayUnavailable` (an anonymous local deployment), and on a self-hosted deployment, which never has the Convex one. The log notes the fallback once per isolate as `ai.convex_gateway_unavailable`.
3. **A refusal.** With neither route, the call is refused with `unavailable` (reason `not_configured`). The message names why the Convex AI Gateway did not answer.

### Choose the gateway

Name one gateway to use it alone, or a list to set the order:

```ts [backend/ai.ts]
export const ai = setupAi(components, {
  billing,
  model: 'openai/gpt-5-mini',
  gateway: 'vercel',
})
```

<table>
<thead>
  <tr>
    <th>
      <code>
        gateway
      </code>
    </th>
    
    <th>
      Where an id goes
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Omitted, or <code>
        ['convex', 'vercel']
      </code>
    </td>
    
    <td>
      The Convex AI Gateway, then the Vercel AI Gateway with the key
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        'convex'
      </code>
    </td>
    
    <td>
      The Convex AI Gateway alone. <code>
        AI_GATEWAY_API_KEY
      </code>
      
       is never read, so a free plan or a self-hosted deployment refuses every call
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        'vercel'
      </code>
    </td>
    
    <td>
      The Vercel AI Gateway alone, even on a paid Convex plan. Without the key, every call is refused
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        ['vercel', 'convex']
      </code>
    </td>
    
    <td>
      The Vercel AI Gateway where the key is set, else the Convex AI Gateway. A deployment picks by having the key or not
    </td>
  </tr>
</tbody>
</table>

The next gateway answers only when one cannot serve the deployment. A spent limit, a `402` from a budget, a `429` or a provider's error refuses the call: a limit is never routed around. [Choose a gateway](https://nuxt-backend.dev/docs/services/ai-gateway#choose-a-gateway) compares the two.

Model calls run in Convex actions, on Convex's servers rather than on Vercel. So the Vercel AI Gateway's keyless sign-in through Vercel's OIDC token never reaches them, and that route needs an API key:

<steps level="3">

### Create a key

Create one in the [AI Gateway dashboard](https://vercel.com/d?to=%2F%5Bteam%5D%2F~%2Fai-gateway%2Fapi-keys&title=AI+Gateway+API+Keys).

### Add it to `.env.local`

```bash [.env.local]
AI_GATEWAY_API_KEY=your_ai_gateway_api_key
```

It is the gateway's own name, read as it is: there is no `nuxt-backend` alias for it.

### Push it to the deployment

```bash
npx nuxt-backend env push
```

Add `--prod` for production.

</steps>

To call a provider with its own key instead, on any deployment, pass a model object from its AI SDK provider package.

### Route some models elsewhere

`setupAi({ routes })` gives some models their own order, over `gateway`. A key is a model id, or a pattern ending in `*` for a provider (`google/*`) or a family (`google/gemini-3-*`). A value is a gateway or an order, as `gateway` takes them:

```ts [backend/ai.ts]
export const ai = setupAi(components, {
  billing,
  gateway: 'convex',
  routes: {
    'google/*': 'vercel',
    'openai/gpt-image-2': ['vercel', 'convex'],
  },
})
```

Here every model goes through the Convex AI Gateway alone, except Google's, which take the Vercel AI Gateway alone, and `openai/gpt-image-2`, which tries the Vercel one first.

- **The closest key wins.** An id's own key beats a pattern, and a longer pattern beats a shorter one. A model no key matches takes `gateway`'s order.
- **Every kind of model follows it.** Language models, embedding models (`ai.knowledge`), image models (`ctx.image()` in a [job step](https://nuxt-backend.dev/docs/build/ai/jobs#define-a-job)) and the safety classifier, and `ai.modelStatus()` reports the route each one takes.
- **A route to 'convex' alone never reads the key** for those models, even where `gateway` names `'vercel'`.
- **A pinned region needs 'vercel' in every route.** `inferenceRegion` sends every call through the Vercel AI Gateway, so `setupAi` refuses a route that leaves it out, as it refuses such a `gateway`.
- **A route it cannot follow throws a TypeError** where `setupAi` is called: a key that is no model id or pattern, a gateway it does not know, or an empty list.

`npx nuxt-backend doctor` reads the `provider/model` ids your backend names, as strings in a `model` option or a `ctx.model()` call. Its `deployment-ai-gateway-api-key` check reports the route they take:

- **On Convex Cloud with @convex-dev/ai-sdk-provider installed**, it passes and names the Convex AI Gateway, the key a free plan falls back on, and how to cap the spend.
- **Under gateway: 'convex'**, it never asks for the key. It warns without the provider package, on an anonymous local deployment (one linked to a project passes, on that team's plan), and on a self-hosted one.
- **Under gateway: 'vercel'**, it needs the key on every deployment.
- **When no route is ready** for those models, it warns, and fails under `--prod`.
- **When it cannot read the order**, such as `gateway` from a variable, the shorthand `{ gateway }` or two `setupAi` calls that differ, it warns that the route is not checked rather than assume the default.
- **Under routes**, it reports each route beside the order, and checks the models a route names by that route's order. A route to `'convex'` alone says the key is never read for those models.
- **When nothing names a model**, it passes.

An id built at run time is not read, and neither is a `gateway` order built at run time: doctor reads it as the default. `npx nuxt-backend status` shows the `ai` capability as `test` outside production with a route, `live` in production, and `missing` when the backend names a model it has no route for ([Capabilities](https://nuxt-backend.dev/docs/start/concepts/capabilities)).

## Pin inference to the EU

The Vercel AI Gateway can pin a call to providers' endpoints in one region, the US or the EU among them, and `setupAi({ inferenceRegion })` takes `'eu'`, the one region it pins. The Convex AI Gateway documents no inference region (both checked on 2026-11-08). So an app whose prompts must be processed in the EU sends its model calls through the Vercel route, with the pin on every call:

```ts [backend/ai.ts]
export const ai = setupAi(components, {
  billing,
  rateLimiter,
  model: 'anthropic/claude-sonnet-4.5',
  inferenceRegion: 'eu',
})
```

`inferenceRegion: 'eu'` does two things:

1. **It takes the Vercel route.** Every `provider/model` id goes to the Vercel AI Gateway with `AI_GATEWAY_API_KEY`, and the Convex AI Gateway is never tried, whatever the `gateway` order. Without the key, calls are refused with `unavailable` (reason `not_configured`). An order without `'vercel'`, such as `gateway: 'convex'`, is refused where `setupAi` is called.
2. **It pins each call.** The package adds the gateway's own option, `providerOptions.gateway.inferenceRegion: { scope: 'zone', geoRegion: 'eu' }`, to every call made through `ctx.model()`. A model no provider serves in the EU is refused by the gateway, and the run's reservation is released.

The gateway reports where each call ran in `providerMetadata.gateway.routing`, and the package logs `ai.region_mismatch` when a call reports another region. To pin one provider and leave another free, pass Vercel's `providers` overrides in `providerOptions` on that call yourself.

The pin covers inference only. Your deployment's data lives in its Convex region, which you pick when you create it ([Convex](https://nuxt-backend.dev/docs/services/convex)), and Vercel's own logs follow its data policy. [Privacy, GDPR and cookies](https://nuxt-backend.dev/docs/ship/compliance/privacy) lists each processor and where it keeps data.

## Cap what the gateway spends

Credits cap what each workspace spends, in your prices. A cap at the gateway is the last line, in dollars, whatever your prices say. Each gateway has its own:

<table>
<thead>
  <tr>
    <th>
      Gateway
    </th>
    
    <th>
      The cap
    </th>
    
    <th>
      What happens at it
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Convex AI Gateway
    </td>
    
    <td>
      Your team's spending limit, on the team's billing page
    </td>
    
    <td>
      The next token request fails, and calls are refused with <code>
        unavailable
      </code>
      
       (reason <code>
        provider_refused
      </code>
      
      ) until the limit resets or rises. <code>
        AI_GATEWAY_API_KEY
      </code>
      
       is never tried instead: a limit is never routed around
    </td>
  </tr>
  
  <tr>
    <td>
      Convex AI Gateway
    </td>
    
    <td>
      A usage limit on the deployment's <code>
        aiGatewayCostDollars
      </code>
      
       metric, per day or month
    </td>
    
    <td>
      A <code>
        warning
      </code>
      
       limit records an event on the deployment's history page, and emails the team on production and preview. A <code>
        disable
      </code>
      
       limit pauses the whole deployment for the rest of the window, every function included
    </td>
  </tr>
  
  <tr>
    <td>
      Vercel AI Gateway
    </td>
    
    <td>
      A budget on the gateway itself
    </td>
    
    <td>
      The gateway refuses calls past it
    </td>
  </tr>
</tbody>
</table>

Set the warning with the Convex CLI, in dollars:

```bash
npx convex deployment usage-limits set --prod --metric aiGatewayCostDollars --window day --type warning --limit 50
```

Keep `disable` limits for a runaway you would rather stop the whole app for. To stop AI alone, with no deploy, use the [`pause_ai` kill switch](https://nuxt-backend.dev/docs/build/ai/models#pause-ai), or let [a daily `spendLimit`](#cap-the-daily-spend) turn it on.

`npx nuxt-backend doctor --prod` reports [`ai-gateway-budget`](https://nuxt-backend.dev/docs/reference/cli/diagnostics#ai-gateway-budget): the gateways production's calls go through, by `setupAi({ gateway, routes })`'s order, and whether `setupAi` sets a `spendLimit`, warning without one. It reads no Convex team or Vercel account, so each gateway's own cap is named with how to set it, not checked. The Convex [usage limits](https://docs.convex.dev/production/usage-limits) page covers every metric and window.

## Charge what a call cost

`cost: { estimate, creditsPerUsd }` settles from the cost each call reports. Both gateways report it in US dollars: the Convex AI Gateway as `providerMetadata.convexGateway.cost`, the Vercel AI Gateway as `providerMetadata.gateway.cost`. The run goes through the same reserve, run, settle path as any other cost:

1. `estimate` credits are reserved before the handler runs. It is the ceiling: a run that cost more settles at the reservation, and `ai.cost_over_reservation` is logged.
2. Each call through `ctx.model()` records its reported cost and its tokens.
3. When the handler returns, or the stream ends, the costs are summed and multiplied by `creditsPerUsd`, your price per dollar with the margin in it. `round` (`'up'`, `'nearest'`, `'none'`) and `minimum` shape the result, and the rest of the reservation goes back to the balance.

A failed run releases the whole reservation: one whose handler threw, and one whose every model call failed though its handler returned. The gateway still bills the tokens a failed run's calls used, and that cost is yours. It is the price of promising your users that a failed run costs them nothing (`charge: 'success'`). For work that is spent upstream the moment it starts, use `charge: 'start'`, which settles the estimate before the run.

<table>
<thead>
  <tr>
    <th>
      What the run made
    </th>
    
    <th>
      What it settles at
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Calls that each reported a cost
    </td>
    
    <td>
      Their sum at <code>
        creditsPerUsd
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      A call with no reported cost, whose model is in <code>
        prices
      </code>
    </td>
    
    <td>
      That call priced by its tokens with <a href="https://nuxt-backend.dev/docs/build/ai/metered-actions#token-pricing">
        <code>
          priceTokens
        </code>
      </a>
      
      , in credits. The table is keyed by the id the call was made with: the <code>
        provider/model
      </code>
      
       id through a gateway, the model object's own <code>
        modelId
      </code>
      
       for your own provider
    </td>
  </tr>
  
  <tr>
    <td>
      A call with no reported cost and no price
    </td>
    
    <td>
      The whole reservation. The run never settles at a guess, and <code>
        ai.cost_unreported
      </code>
      
       is logged
    </td>
  </tr>
  
  <tr>
    <td>
      A stream the handler stopped reading, or one that broke after it started, beside another call that finished
    </td>
    
    <td>
      The whole reservation, as for an unreported cost: the stream never reported what it cost
    </td>
  </tr>
  
  <tr>
    <td>
      A call that was refused, beside another that finished
    </td>
    
    <td>
      Nothing for the refused one: it never answered
    </td>
  </tr>
  
  <tr>
    <td>
      No model call at all
    </td>
    
    <td>
      <code>
        minimum
      </code>
      
      , zero by default
    </td>
  </tr>
</tbody>
</table>

Settling after the run needs a sum meter, as every finalized cost does. To price by tokens alone, keep `cost: { estimate, finalize }` with `priceTokens` and a price table you own: see [Token pricing](https://nuxt-backend.dev/docs/build/ai/metered-actions#token-pricing). Reported costs follow the provider's prices as they change, while a token table changes only when you edit it.

## Develop and test

Development takes the same route as production, against real models:

- **On a paid Convex plan**, a cloud dev deployment reaches the Convex AI Gateway with no setup. A local deployment reaches it once it is linked to a project: run `npx convex login`, then restart `npx nuxt-backend dev`. An anonymous local deployment cannot.
- **On a free plan, or a self-hosted backend**, set `AI_GATEWAY_API_KEY` in `.env.local` and run `npx nuxt-backend env push`.
- **Credits** come from your billing sandbox, so a metered call spends sandbox credits at the model's real cost ([Develop with real sandboxes](https://nuxt-backend.dev/docs/develop/sandboxes#ai-through-the-convex-ai-gateway)).
- **Tests** under Vitest make no network call. `nuxt-backend/test` answers every `provider/model` id with a mock from the AI SDK's `ai/test`, which repeats the prompt and reports a fixed cost, so a test of a metered action needs no key ([Test your app](https://nuxt-backend.dev/docs/develop/testing)).

Earlier previews answered from a stand-in model on a local deployment without a key. `0.2.0` removes it, with `NUXT_BACKEND_SIMULATE_MODELS`: a call with no route is refused in development as it is in production.

## Show which model answers

`ai.modelStatus(model?)` reads only the env, so a query can show it:

```ts [backend/ai.ts]
import { query } from './_generated/server'

export const modelStatus = query({ args: {}, handler: async () => ai.modelStatus() })
```

It returns `{ model, state, route }`:

- **route** is where calls go first: `convex-gateway`, `vercel-gateway`, `provider` (a model object's own key), or `null`.
- **state** is `live` when there is a route, and `missing` with no route or no model configured.

On Convex Cloud, `state` reads `live` for the Convex AI Gateway. A query cannot ask for its token, so a free plan without the key shows up when a call is refused, and in `doctor`.

## Budgets and costs

Credits already make metered AI prepaid: a call that does not fit the balance is refused. On top of that, two limits run through the rate limiter the scaffold sets up, two hooks tell you when a balance runs low, and one kill switch pauses every metered call. What each call costs, from the cost the model reports or a token price table, is on [Choose a model](https://nuxt-backend.dev/docs/build/ai/models#charge-what-a-call-cost).

### Limit calls

The `ai` limit caps calls per billing entity. Its default, `DEFAULT_LIMITS.ai`, allows 30 calls a minute with a burst of 10. Override it, or add a limit of your own and name it in an action's `limit`, in [`setupRateLimiter`](https://nuxt-backend.dev/docs/ship/security/rate-limits):

```ts [backend/rateLimiter.ts]
export const rateLimiter = setupRateLimiter(components, {
  ai: { kind: 'token bucket', rate: 30, period: 60_000 },
  imageGen: { kind: 'fixed window', rate: 5, period: 60_000 },
})
```

Over the limit, a call is refused with `rate_limited`, the limit's name and `retryAfter`, before any credits are reserved. [Limits](https://nuxt-backend.dev/docs/reference/backend/limits#rate-limits) lists every default.

### Cap spend per window

`setupAi({ budget })` caps credits, not calls. `{ units, period, limit? }` allows `units` credits per `period` milliseconds for each billing entity, so `{ units: 500, period: DAY }` is 500 credits a day per workspace. It needs `rateLimiter`, and records the window under `limit`: `'aiBudget'` by default, or a name of your own to keep a separate budget per feature.

A call counts its whole estimate against the window when it starts, so concurrent calls can't overshoot, and the window gets back what the call did not spend when it closes: the rest of the estimate for a run that settles under it, and all of it for a run that fails or a call refused with `insufficient_credits`. Two things stay counted: an abandoned stream's estimate, whose credits come back on a timer, and what `charge: 'start'` settles. A run that crosses into the next window gives its remainder to that window, up to `units`. A `rateLimiter` of your own needs a `credit` method for any of this; without one, the window keeps everything a call counted. Over the cap, a call is refused with `rate_limited` and the budget's limit name, and the message says when the window resets. A call whose cost exceeds `units` could never fit, so it throws an error that names both numbers; size the budget above your largest estimate. Queued jobs never count here: a job queue's tiers carry a budget of their own, which gives a job's cost back to its window when the job's credits are released or refunded ([Cap what an owner spends per day](https://nuxt-backend.dev/docs/build/ai/jobs/priority#cap-what-an-owner-spends-per-day)).

### React to a low balance

`setupAi({ credits })` runs two hooks after a spend settles:

- **onCreditsLow** when the balance crosses `lowBalanceThreshold` downwards;
- **onCreditsExhausted** when it goes from above zero to zero or below.

Both fire on the crossing only, so a second spend that stays below the line is silent, and they are safe to wire straight to a notification. The event carries `entityId`, `userId`, `meter` and `meterId`, `balance`, `previousBalance`, `spent` and `threshold`. A hook that throws is logged as `ai.balance_hook_failed`, and the spend stays settled. Two spends that settle across the line at the same moment can both report the crossing: dedupe on the receiving side if that matters.

```ts [backend/ai.ts]
// The scaffolded `ai`, plus a budget and the credits hooks.
import { DAY } from 'nuxt-backend/rate-limit'

export const ai = setupAi(components, {
  billing,
  rateLimiter,
  budget: { units: 500, period: DAY },   // 500 credits a day per workspace, on top of the `ai` call limit
  credits: {
    lowBalanceThreshold: 50,
    onCreditsLow: async (ctx, { entityId, balance }) => {
      // record it, or hand it off: the lifecycle emails own the sending
    },
  },
})
```

Each crossing is also recorded on the shared event path, hooks or not: `billing.credits_low` once you set a threshold, and `billing.credits_exhausted`. The workspace's owners and admins read them in its activity trail: see [Events](https://nuxt-backend.dev/docs/reference/backend/events#backend-events).

In the browser, the app shows the same moment to the person, with a way to buy a pack: see [Credits & top-ups](https://nuxt-backend.dev/docs/build/billing/credits).

### Pause AI

The `pause_ai` kill switch stops every metered action and stream at once, with no deploy. While it is on, a call is refused once the caller is checked, before the model, the rate limit, the budget or the credits count anything, with `unavailable` (reason `ai_paused`). The page shows the `backend.errors.unavailable_ai_paused` label, "AI features are paused for now. Try again later." It also refuses new [jobs](https://nuxt-backend.dev/docs/build/ai/jobs), [chat](https://nuxt-backend.dev/docs/build/ai/chat) replies and [safety checks](https://nuxt-backend.dev/docs/build/ai/content-safety), and holds queued jobs until it is off. The [daily spend limit](#cap-the-daily-spend) turns it on by itself. A model call your code makes outside `setupAi` is not paused.

Turn it on from the admin console's Flags tab (`/admin?tab=flags`), or from code with `setFlag`: see [Kill switches](https://nuxt-backend.dev/docs/ship/operate/flags#kill-switches). Every change is recorded in the activity trail.

### Cap the daily spend

`setupAi({ spendLimit: { usdPerDay } })` caps what AI costs the whole app in one UTC day, in US dollars, as the gateway reports each call's cost. Once the day's spend reaches it, the app turns `pause_ai` on by itself. It records `ai.spend_limit_reached` with the day's `usd` and the `limit` on the activity trail, and raises the `ai_spend_limit` alert in the log and in the [monitoring service](https://nuxt-backend.dev/docs/ship/operate/monitoring). When the next UTC day begins, the pause lifts by itself.

```ts [backend/ai.ts]
export const ai = setupAi(components, {
  billing,
  rateLimiter,
  spendLimit: { usdPerDay: 20 }, // pause_ai turns on once a day costs $20
})
```

The lift clears only a pause the limit turned on. An override of `pause_ai` an administrator set is theirs, and the limit never writes over it: a pause, one aimed at some workspaces or people, or a resume (`enabled: false`) holds, with every field they gave it, through the limit and past midnight, until they change it. Clearing the override instead (back to the default) lets calls through until the next cost is recorded, which pauses AI again: resume it, or raise the limit and deploy, to go on. A call already running finishes, so a day can end a little over the limit. The limit covers every run the package records a cost for: metered actions, streams, chat replies, knowledge embeddings, queued jobs and safety checks.

A `sandbox` deployment, such as a public demo, needs one. Without a `spendLimit`, every metered call, stream, job and chat reply there is refused with `not_ready`, reason `no_budget`, and `doctor --prod` reports [`ai-spend-limit`](https://nuxt-backend.dev/docs/reference/cli/diagnostics#ai-spend-limit) ([What a demo refuses](https://nuxt-backend.dev/docs/ship/deploy/staging#what-a-demo-refuses)).

### Track what each call cost

- **Per customer, in the billing provider.** Each settled call is a usage event on the credit meter, with the amount spent and the id of the member who made it. The provider's dashboard shows usage per customer, and the member id lets you group a workspace's usage per person, with no table of yours.
- **Per person, in your app.** Every run records what its calls cost, against the member who made it: metered actions, streams, chat replies, knowledge embeddings and queued jobs alike. The admin console's Costs tab lists it once `backend/ai.ts` re-exports `getCosts` from `ai.api`, and the AI spend alert reads the same days ([AI cost per person](https://nuxt-backend.dev/docs/ship/operate/monitoring#ai-cost-per-person)).
- **For the person.** `<UsageHistory meter="credits" />`, or `useUsage()`, lists the workspace's consumption from the same events: see [Credits & top-ups](https://nuxt-backend.dev/docs/build/billing/credits).
- **In dollars, per model.** The Convex dashboard's team usage page shows the Convex AI Gateway's spend per project, and per function under its **AI** tab. The Vercel AI Gateway's dashboard shows its own. A gateway cap stops the spend in dollars, whatever your prices say: see [Cap what the gateway spends](https://nuxt-backend.dev/docs/build/ai/models#cap-what-the-gateway-spends).
- **In the log.** `ai.cost_over_reservation` means a run cost more than its estimate and settled at the reservation: raise the estimate. `ai.cost_unreported` means a call reported no cost and had no price: add it to `prices`. `ai.model_failed` means every model call of a run failed, and nothing was charged. `ai.cost_unrecorded` means a run's cost could not be recorded for the Costs tab.

A [job](https://nuxt-backend.dev/docs/build/ai/jobs/credits#report-what-each-job-cost-you) also reports its run's model cost to Polar, as a `job.cost` event under its charge in Polar's Cost Insights format, with its model and token counts, never the prompt or the answer. Polar's Costs dashboard then shows the jobs' cost per customer and the margin they leave. Metered actions, streams and chat send no cost event, so Polar's figures leave their costs out: the admin console's Costs tab has them.

## Limits

- **The Convex AI Gateway needs a paid plan.** A free plan answers `AiGatewayDisabled`, and an anonymous local or self-hosted deployment `AiGatewayUnavailable`; the default order falls back to the Vercel key, and `gateway: 'convex'` refuses the call.
- **No limits per app user at either gateway.** The Convex limit is per team; Vercel's budgets are per team member, not per person using your app. Credits, rate limits and budgets are what cap each workspace.
- **A disable usage limit pauses the whole deployment,** every function included. Use `pause_ai` to stop AI alone.
- **Image, video and voice models are alpha** on the Convex AI Gateway: their request formats may change (checked on 2026-10-25).
- **No moderation endpoint** at either gateway: content checks are a classifier model call ([Keep content safe](https://nuxt-backend.dev/docs/build/ai/content-safety)).

## Related

- [AI gateway](https://nuxt-backend.dev/docs/services/ai-gateway): plans, keys, spending caps and the dashboards.
- [Meter an AI action](https://nuxt-backend.dev/docs/build/ai/metered-actions): the reserve, run, settle path, and token pricing.
- [Run generation jobs](https://nuxt-backend.dev/docs/build/ai/jobs): long generations in a queue, with model limits that adapt to the gateway.
- [Environment variables](https://nuxt-backend.dev/docs/reference/configuration/environment-variables): `AI_GATEWAY_API_KEY` beside the rest.
- [`nuxt-backend/ai` reference](https://nuxt-backend.dev/docs/reference/api/ai), and the [demo](https://nuxt-backend.dev/docs/start/playground), whose strips a model draws.


## Sitemap

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