# Use Limitry with the Vercel AI SDK

> Add one language model middleware, and each of your users gets an AI budget across every model the AI SDK calls, streamed or not.

The AI SDK gives your product one interface for every model provider, and its middleware runs your code around each model call. One Limitry middleware gives each of your users a budget across every model they use. You add it once, and every `generateText` and `streamText` call stays within budget.

## 1. Create the budget

Create the 200-cent monthly budget from [Limit AI spend per user](/docs/guides/limit-ai-spend/#1-create-the-budget). It counts in cents, with the action `ai-call`.

## 2. Add the middleware

The middleware reserves a few cents before each model call, then commits what the call cost. A stream keeps its reservation open until its last part, which carries the usage.

```ts
import { createClient, type ReserveRequest } from "@limitry/sdk";
import type { LanguageModelMiddleware } from "ai";

// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();

type Usage = {
  inputTokens: { total: number | undefined };
  outputTokens: { total: number | undefined };
};

// Your prices, in cents per million tokens.
const priceCents = (usage: Usage) =>
  Math.ceil(
    ((usage.inputTokens.total ?? 0) * 300 +
      (usage.outputTokens.total ?? 0) * 1500) /
      1_000_000,
  );

// Reserves before each model call and commits what the call cost.
export function aiBudget(
  subject: ReserveRequest["subject"],
): LanguageModelMiddleware {
  const request = { subject, action: "ai-call", cost: 5 };
  return {
    specificationVersion: "v4",
    wrapGenerate: ({ doGenerate }) =>
      limitry.reserve(request, async (reservation) => {
        const result = await doGenerate();
        reservation.cost(priceCents(result.usage));
        return result;
      }),
    wrapStream: ({ doStream }) =>
      new Promise((resolve, reject) => {
        limitry
          .reserve(request, async (reservation) => {
            const { stream, ...rest } = await doStream();
            await new Promise<void>((finished) => {
              const counted = stream.pipeThrough(
                new TransformStream({
                  transform(part, controller) {
                    if (part.type === "finish") {
                      reservation.cost(priceCents(part.usage));
                    }
                    controller.enqueue(part);
                  },
                  flush: () => finished(),
                }),
              );
              resolve({ ...rest, stream: counted });
            });
          })
          .catch(reject);
      }),
  };
}
```

## 3. Wrap your model

Wrap the model with the user’s middleware, and call it as you always do:

```ts
import { openai } from "@ai-sdk/openai";
import { LimitReachedError } from "@limitry/sdk";
import { generateText, streamText, wrapLanguageModel } from "ai";

import { aiBudget } from "./ai-budget";

export async function answer(userId: string, prompt: string) {
  const model = wrapLanguageModel({
    model: openai("gpt-6.2-sol"),
    middleware: aiBudget({ kind: "user", id: userId }),
  });
  try {
    const { text } = await generateText({ model, prompt });
    return text;
  } catch (err) {
    if (err instanceof LimitReachedError) {
      return "You've used this month's AI allowance. It resets on the 1st.";
    }
    throw err;
  }
}

export function streamAnswer(userId: string, prompt: string) {
  const model = wrapLanguageModel({
    model: openai("gpt-6.2-sol"),
    middleware: aiBudget({ kind: "user", id: userId }),
  });
  return streamText({
    model,
    prompt,
    onError: ({ error }) => {
      if (error instanceof LimitReachedError) {
        console.log(`${userId} has used this month's AI allowance.`);
      }
    },
  });
}
```

`generateText` throws the `LimitReachedError`. `streamText` hands it to `onError` instead, before any text streams.

The middleware works with every provider the AI SDK supports. Swap `openai("gpt-6.2-sol")` for any other model, and the same budget covers it.

## What you see

* A call that uses 10,000 input tokens and 2,000 output tokens commits 6 cents at these prices, streamed or not.
* On the [Usage](/docs/usage/) page, each user’s AI spend this month.
* A user over budget gets your message straight away. The model call never starts, so it costs you nothing.

Agents built on the AI SDK, such as Mastra’s, take the same wrapped model: see [Agent frameworks](/docs/works-with/agent-frameworks/#mastra).

Related: [Reservations](/docs/reservations/), [Show users where they stand](/docs/guides/show-usage/).
