Use Limitry with the OpenAI and Anthropic SDKs
The OpenAI and Anthropic SDKs report the tokens each reply used. Limitry
turns those tokens into cents at your prices, and charges them to the
user’s budget. Your code calls the model exactly as before, inside one
reserve block.
1. Create the budget
Section titled “1. Create the budget”Create the 200-cent monthly budget from
Limit AI spend per user.
It counts in cents, with the action ai-call.
2. OpenAI
Section titled “2. OpenAI”Reserve a few cents, call the model, then commit what the tokens cost:
import { createClient } from "@limitry/sdk";import OpenAI from "openai";
// Uses the LIMITRY_API_KEY environment variable.const limitry = createClient();// Uses the OPENAI_API_KEY environment variable.const openai = new OpenAI();
// Your prices, in cents per million tokens.const priceCents = (usage: OpenAI.CompletionUsage) => Math.ceil( (usage.prompt_tokens * 300 + usage.completion_tokens * 1500) / 1_000_000, );
export async function answer(userId: string, prompt: string) { return limitry.reserve( { subject: { kind: "user", id: userId }, action: "ai-call", cost: 5 }, async (reservation) => { const completion = await openai.chat.completions.create({ model: "gpt-6.2-sol", messages: [{ role: "user", content: prompt }], }); if (completion.usage) reservation.cost(priceCents(completion.usage)); return completion.choices[0]?.message.content ?? ""; }, );}import math
from limitry import Limitryfrom openai import OpenAIfrom openai.types import CompletionUsage
# Uses the LIMITRY_API_KEY environment variable.limitry = Limitry()# Uses the OPENAI_API_KEY environment variable.openai = OpenAI()
# Your prices, in cents per million tokens.def price_cents(usage: CompletionUsage) -> int: return math.ceil((usage.prompt_tokens * 300 + usage.completion_tokens * 1500) / 1_000_000)
def answer(user_id: str, prompt: str) -> str: with limitry.reserve( subject={"kind": "user", "id": user_id}, action="ai-call", cost=5 ) as reservation: completion = openai.chat.completions.create( model="gpt-6.2-sol", messages=[{"role": "user", "content": prompt}], ) if completion.usage: reservation.cost = price_cents(completion.usage) return completion.choices[0].message.content or ""Streaming
Section titled “Streaming”Ask for the usage with stream_options. OpenAI then sends it in the
stream’s last chunk:
import { createClient } from "@limitry/sdk";import OpenAI from "openai";
// Uses the LIMITRY_API_KEY environment variable.const limitry = createClient();// Uses the OPENAI_API_KEY environment variable.const openai = new OpenAI();
// Your prices, in cents per million tokens.const priceCents = (usage: OpenAI.CompletionUsage) => Math.ceil( (usage.prompt_tokens * 300 + usage.completion_tokens * 1500) / 1_000_000, );
export async function streamAnswer(userId: string, prompt: string) { return limitry.reserve( { subject: { kind: "user", id: userId }, action: "ai-call", cost: 5 }, async (reservation) => { const stream = await openai.chat.completions.create({ model: "gpt-6.2-sol", messages: [{ role: "user", content: prompt }], stream: true, stream_options: { include_usage: true }, }); let text = ""; for await (const chunk of stream) { text += chunk.choices[0]?.delta.content ?? ""; if (chunk.usage) reservation.cost(priceCents(chunk.usage)); } return text; }, );}import math
from limitry import Limitryfrom openai import OpenAIfrom openai.types import CompletionUsage
# Uses the LIMITRY_API_KEY environment variable.limitry = Limitry()# Uses the OPENAI_API_KEY environment variable.openai = OpenAI()
# Your prices, in cents per million tokens.def price_cents(usage: CompletionUsage) -> int: return math.ceil((usage.prompt_tokens * 300 + usage.completion_tokens * 1500) / 1_000_000)
def stream_answer(user_id: str, prompt: str) -> str: with limitry.reserve( subject={"kind": "user", "id": user_id}, action="ai-call", cost=5 ) as reservation: stream = openai.chat.completions.create( model="gpt-6.2-sol", messages=[{"role": "user", "content": prompt}], stream=True, stream_options={"include_usage": True}, ) text = "" for chunk in stream: if chunk.choices: text += chunk.choices[0].delta.content or "" if chunk.usage: reservation.cost = price_cents(chunk.usage) return text3. Anthropic
Section titled “3. Anthropic”The same block works with Claude. The reply’s usage has the token
counts:
import Anthropic from "@anthropic-ai/sdk";import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.const limitry = createClient();// Uses the ANTHROPIC_API_KEY environment variable.const anthropic = new Anthropic();
// Your prices, in cents per million tokens.const priceCents = (usage: Anthropic.Usage) => Math.ceil( (usage.input_tokens * 300 + usage.output_tokens * 1500) / 1_000_000, );
export async function answer(userId: string, prompt: string) { return limitry.reserve( { subject: { kind: "user", id: userId }, action: "ai-call", cost: 5 }, async (reservation) => { const message = await anthropic.messages.create({ model: "claude-sonnet-5-5", max_tokens: 1024, messages: [{ role: "user", content: prompt }], }); reservation.cost(priceCents(message.usage)); return message.content .map((block) => (block.type === "text" ? block.text : "")) .join(""); }, );}import math
from anthropic import Anthropicfrom anthropic.types import Usagefrom limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.limitry = Limitry()# Uses the ANTHROPIC_API_KEY environment variable.anthropic = Anthropic()
# Your prices, in cents per million tokens.def price_cents(usage: Usage) -> int: return math.ceil((usage.input_tokens * 300 + usage.output_tokens * 1500) / 1_000_000)
def answer(user_id: str, prompt: str) -> str: with limitry.reserve( subject={"kind": "user", "id": user_id}, action="ai-call", cost=5 ) as reservation: message = anthropic.messages.create( model="claude-sonnet-5-5", max_tokens=1024, messages=[{"role": "user", "content": prompt}], ) reservation.cost = price_cents(message.usage) return "".join(block.text for block in message.content if block.type == "text")Streaming
Section titled “Streaming”A stream’s final message carries the usage for the whole reply:
import Anthropic from "@anthropic-ai/sdk";import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.const limitry = createClient();// Uses the ANTHROPIC_API_KEY environment variable.const anthropic = new Anthropic();
// Your prices, in cents per million tokens.const priceCents = (usage: Anthropic.Usage) => Math.ceil( (usage.input_tokens * 300 + usage.output_tokens * 1500) / 1_000_000, );
export async function streamAnswer(userId: string, prompt: string) { return limitry.reserve( { subject: { kind: "user", id: userId }, action: "ai-call", cost: 5 }, async (reservation) => { const stream = anthropic.messages.stream({ model: "claude-sonnet-5-5", max_tokens: 1024, messages: [{ role: "user", content: prompt }], }); stream.on("text", (text) => process.stdout.write(text)); const message = await stream.finalMessage(); reservation.cost(priceCents(message.usage)); return message; }, );}import math
from anthropic import Anthropicfrom anthropic.types import Usagefrom limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.limitry = Limitry()# Uses the ANTHROPIC_API_KEY environment variable.anthropic = Anthropic()
# Your prices, in cents per million tokens.def price_cents(usage: Usage) -> int: return math.ceil((usage.input_tokens * 300 + usage.output_tokens * 1500) / 1_000_000)
def stream_answer(user_id: str, prompt: str) -> str: with limitry.reserve( subject={"kind": "user", "id": user_id}, action="ai-call", cost=5 ) as reservation: with anthropic.messages.stream( model="claude-sonnet-5-5", max_tokens=1024, messages=[{"role": "user", "content": prompt}], ) as stream: text = "".join(stream.text_stream) reservation.cost = price_cents(stream.get_final_message().usage) return textWhat you see
Section titled “What you see”- A reply that uses 10,000 input tokens and 2,000 output tokens commits 6 cents at these prices.
- On the Usage page, each user’s AI spend this month, across both providers.
- A user over budget gets a
LimitReachedErrorfromreservebefore the call, so the model is never called and it costs you nothing. Limit AI spend per user shows the message to send them.
To cap each model on its own as well, name the model in the action: One budget, or a budget per model.
Related: Reservations.