Skip to content

Use Limitry with OpenRouter

OpenRouter gives your product one API for many models, and tells you what each request cost. Limitry charges that exact cost to the user’s budget, so each of your users stays within their allowance on every model. There’s no price table to keep.

Create the 200-cent monthly budget from Limit AI spend per user. It counts in cents, with the action ai-call.

OpenRouter answers the OpenAI API, so the OpenAI SDK talks to it. Reserve a few cents before the request. Then commit the cost OpenRouter returns, in whole cents:

import { createClient, LimitReachedError } from "@limitry/sdk";
import OpenAI from "openai";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
// OpenRouter answers the OpenAI API, so the OpenAI SDK talks to it.
const openrouter = new OpenAI({
baseURL: "https://openrouter.ai/api/v1",
apiKey: process.env.OPENROUTER_API_KEY,
});
// OpenRouter adds what the request cost to its usage, in US dollars.
type OpenRouterUsage = OpenAI.CompletionUsage & { cost?: number };
export async function answer(userId: string, prompt: string) {
try {
return await limitry.reserve(
{ subject: { kind: "user", id: userId }, action: "ai-call", cost: 5 },
async (reservation) => {
const completion = await openrouter.chat.completions.create({
model: "anthropic/claude-sonnet-5.5",
messages: [{ role: "user", content: prompt }],
user: userId,
});
const usage = completion.usage as OpenRouterUsage | undefined;
if (usage?.cost !== undefined) {
reservation.cost(Math.ceil(usage.cost * 100));
}
return completion.choices[0]?.message.content ?? "";
},
);
} catch (err) {
if (err instanceof LimitReachedError) {
return "You've used this month's AI allowance. It resets on the 1st.";
}
throw err;
}
}

The user field sends your user’s id to OpenRouter too, so both tools name the same person.

To count small requests more finely, count the budget in hundredths of a cent. A $2 budget is then 20,000, and the commit is Math.ceil(usage.cost * 10_000).

  • A request that costs $0.0123 commits 2 cents, and the user’s budget shows 198 cents left.
  • On the Usage page, each user’s spend this month, in the cents OpenRouter charged.
  • A user over budget gets your message straight away. The request never reaches OpenRouter, so it costs you nothing.

Related: Reservations, Warn your users before they hit a limit.