---
name: ai-cost-guardrails
description: Finds the places where an app that calls an AI provider (OpenAI, Anthropic, Gemini and others) could run up a large bill. Looks for AI calls made from the browser with a key, AI endpoints with no sign-in check or rate limit in front, and loops or retries with no cap, then lists the spending limits to set in the provider dashboard. Use when the user asks about AI or API costs, a surprise bill, whether someone could abuse their AI feature, rate limiting an AI endpoint, or wants a cost check before launch.
allowed-tools: Read Grep Glob
license: MIT
---

# AI cost guardrails

Find the ways this app could spend money on AI calls without the owner meaning to. Report them ranked, each with its fix. Change nothing.

## Rules

- **Read only.** Use Read, Grep and Glob. Do not edit or create files and do not run commands.
- **Never print a whole key.** If you quote one, show the first 6 characters, `…`, and the last 4.
- Report what the code shows. If a guard might exist somewhere you cannot see (a gateway, a platform setting), say so under "Not checked" instead of assuming either way.
- Write for someone who is not an engineer. Say what could happen in plain words.
- **No dollar amounts or cost estimates.** Provider prices are not in the code, so you cannot work out what anything would cost, and a guessed figure reads as a fact. Do not write prices, per-call costs, "a few cents", "hundreds of dollars" or any other money figure. Describe the risk in words instead: "every call is billed to you", "this can add up quickly", "it keeps going until someone notices or the provider stops it". Numbers that are in the code (a cap of 20 items, 400 output tokens, 30 requests an hour) may be quoted as they are; do not turn them into money.

## Step 1: Find every AI call

Grep for the provider addresses and libraries:

- `api.openai.com`, `api.anthropic.com`, `generativelanguage.googleapis.com`, `api.groq.com`, `api.mistral.ai`, `openrouter.ai`, `api.replicate.com`, `api.together.xyz`, `api.perplexity.ai`, `api.elevenlabs.io`, `fal.run`
- `from "openai"`, `@anthropic-ai/sdk`, `@google/generative-ai`, `@google/genai`, `from "ai"`, `@ai-sdk/`, `langchain`, `replicate`
- `chat.completions`, `messages.create`, `responses.create`, `generateText`, `streamText`, `generateContent`, `images.generate`, `embeddings.create`
- `dangerouslyAllowBrowser`

Build files (`dist/`, `build/`, `.next/`) and `node_modules/` are out of scope: review the source.

For each call, note the file, the line, and whether it runs in the **browser** (`src/`, `app/` client components, `components/`, `pages/` outside `pages/api/`) or on the **server** (`supabase/functions/`, `api/`, `server/`, `app/**/route.ts`, `pages/api/`, `netlify/functions/`, `functions/`).

## Step 2: Check each call

**A. Called from the browser with a key.** A browser file that sends a request to a provider address, or builds a provider client, with an API key (`VITE_…`, `NEXT_PUBLIC_…`, hard-coded, or `dangerouslyAllowBrowser: true`). The key is in the page for anyone to copy, and whoever copies it spends the owner's money from anywhere. No limit in the app can stop that. This is always the top finding.

A browser file that calls the app's **own** server function (`/functions/v1/…`, `/api/…`, `supabase.functions.invoke(…)`), even with the Supabase anon or publishable key in the header, is not this problem. That key is public by design.

**B. A server endpoint anyone can call.** For each server function that makes an AI call, read the whole handler and look for both:

- *A sign-in check before the AI call*: `supabase.auth.getUser(…)` with the result checked, a session check, a verified token, or a returned 401. For Supabase Edge Functions also read `supabase/config.toml`: `verify_jwt = false` under the function means Supabase does not check the token for you. Note that `verify_jwt = true` alone only proves the caller has the public anon key, which everyone has. It is not a sign-in check.
- *A rate limit before the AI call*: a per-user or per-IP counter with a refusal (429) when it is exceeded, using a rate-limit library (`@upstash/ratelimit`), a database counter, or a platform rule you can see in the repo.

If a check lives in a shared helper, read the helper. If the helper calls a database function, Glob for `**/*.sql` and read that too before saying anything about it.

Missing sign-in check: anyone on the internet can call it in a loop. Missing rate limit: any one signed-in user can. Report each that is missing.

**C. No ceiling on one request.** On a server AI call, look for an output limit (`max_tokens`, `max_output_tokens`, `maxOutputTokens`, `max_completion_tokens`) and for a limit on the size of what the user sends (a length check on the prompt, a cap on the number of messages or items). Report a call where the user controls the input size and nothing limits it.

**D. Loops and retries with no cap.** Around each AI call, look for:

- `while (true)` or `for (;;)` that calls the provider again on failure with no attempt counter;
- a `catch` that calls the same function again (recursion) with no counter;
- a loop over a list the user supplies (`for (const item of items)`, `.map(…)` with `Promise.all`) that makes one AI call per item with no cap on the list length;
- a timer or effect (`setInterval`, a React effect with no dependency list, a call on every keystroke with no delay) that calls the AI repeatedly while a page is open;
- an agent or tool loop with no maximum number of steps.

Each of these is a problem of its own, with its own numbered entry, even when the endpoint has a sign-in check and a rate limit. A rate limit counts requests, not the AI calls one request makes, so one allowed request with a very long list, or one that never stops retrying, still makes as many calls as it likes. An uncapped list is as much a D problem as an uncapped retry.

Do **not** report:

- A retry with a clear cap (`attempt < 3`, `maxRetries: 2`) and a wait between attempts.
- A `while (true)` that only reads a streamed response (`reader.read()` until `done`). It ends when the response ends and makes no new calls.
- A loop over a list whose length is checked and capped before the loop.
- The SDK's own default retries (the OpenAI and Anthropic libraries retry twice by default).

**E. Model choice.** Mention it only when a clearly expensive model (the provider's top tier) is used for a small job such as a title or a classification, and only as a note. It is not a finding on its own.

## Step 3: The dashboard limits

Code cannot show whether these are set, so list them every time under "Set these in the provider dashboard", only for the providers this app uses. Dashboards change, so give each path as "at the time of writing" and always end the section with the fallback line below.

- **Anthropic** (Claude Console): at the time of writing, the "Spend limits" page in the Console settings (`platform.claude.com/settings/spend-limits`) sets a "Monthly spend limit" for the whole organisation. Put this app's key in its own workspace (the "Workspaces" page in the settings), then, on the same "Spend limits" page under "Workspace limits", pick that workspace and set its monthly limit, so this app has a ceiling of its own. Add an email notification below the limit where the page offers one. Do not rely on a limit on the Default workspace: Anthropic says it might not count or stop some of the usage there.
- **OpenAI** (platform dashboard): look for the "Limits" page in the organisation settings, and the "Limits" page in the settings of the project this app's key belongs to. Set a monthly spend limit and an email alert below it, and switch on the hard limit if one is offered, so calls stop at the limit instead of only warning. Use a separate project and key for this app so its limit is its own. Do not present these page names as certain: say they could not be checked against the dashboard.
- **Google Gemini**: look in Google AI Studio and in Google Cloud Billing for a spend cap or budget on the project this key belongs to, and set alerts. Do not give a menu path for Google.
- **Any other provider**: look for "limits", "budget" or "usage" in its dashboard.
- **Any provider**: prefer prepaid credit with auto-reload switched off while the app is new, where the provider offers it. The balance is then the most you can lose.

End the section with this line, word for word: "Dashboard menus move. If a page is not where described, look for "limits", "budget" or "usage" in the provider's settings."

## Output

Reply with this and nothing before it. Write it as plain text with these headings. Do not wrap the whole reply in a code fence.

```
AI cost check: <N> problem(s) found

AI calls found: <count>, in <files>

## Problems, worst first

1. <The problem in one plain sentence> — `<file>:<line>`
   What could happen: <one or two sentences on who could trigger it and how fast it could add up, in words, with no dollar figures>
   Fix: <the change to make, in short steps; a few lines of code if that is clearer>

## Set these in the provider dashboard

- <provider>: <the limit to set and where>

## Looks right

- `<file>:<line>` <what is guarded and how, one line>

## Not checked

- <what the code cannot show>
```

- Rank by how much money could go and how easily: A first, then B without a sign-in check, then uncapped loops and retries (D), then B without a rate limit, then C.
- One numbered problem per fault per place. An endpoint that has neither a sign-in check nor a rate limit gets one entry that names both gaps and fixes both.
- Every fault you found in the code under A to D goes in the numbered Problems, and nowhere else. "Not checked" is only for what the code cannot show: dashboard settings, a gateway or platform rule outside the repository, what is deployed, what is in git history. If you can point to the line and you would tell the user to change it, it is a numbered problem. Never describe a fault, or give its fix, under "Not checked" or "Looks right".
- Before you write the reply, go through every AI call from Step 1 against A, B, C and D once more and check each fault has its entry. Then count the numbered entries: `<N>` is that number, exactly.
- The fix for A is always: replace the key in the provider dashboard, move the call into a server function that reads the key from the environment, and have the browser call that function. Then the function needs its own sign-in check and rate limit.
- The dashboard list is advice, not a finding. Do not count it in `<N>`.
- If there are no problems, write `AI cost check: 0 problems found`, write "None." under Problems, and keep the other sections. Do not invent a problem.

<!--
MIT License

Copyright (c) 2026 PT Maverick Rintis Karya

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-->
