14A.4 Requesting Model Access and Budget
You have built LLM features in a sandbox. At work, the next step is different: you cannot just paste a personal API key into a script and start calling a model. Someone has to agree that this use case may use this model on this data, with a cost that the organization expects and can afford, with a key that can be switched off without hurting anyone else. That agreement happens through a request. This lesson teaches you how to write a good request, how approvals usually work, how to handle API keys safely, how budgets and quotas protect everyone, how spend is attributed to teams, and what to do on the day the quota runs out. Every organization runs this process a little differently, so the lesson teaches the general practice and marks each place where your organization's own rules go with a placeholder you can fill in.
What you'll learn
- What a model-access and budget request contains, and why each field exists: use case, data class, expected volume, cost estimate, eval plan, risk tier and owner
- How to estimate the monthly cost of a feature from token counts and a price list, with a safety factor, using the tokenomics ideas from 03.7 and 11B.2
- How a typical approval workflow routes a request, and how to write one that gets approved the first time
- API key hygiene: one key per project, scoped, stored in a secret store, rotated, never in code or chat
- Budgets, quotas, rate limits and caps, and how they relate to the machinery in 11B.1 and the governance view in 11C.4
- Cost attribution tags, so every dollar belongs to a team and a feature
- What to do when you hit a quota: triage, degrade gracefully, request more with evidence
- How to run a small keyless request validator and cost estimator, and how to eval it
What you don't need
- API keys. Everything here runs offline with
python3and the standard library. Nothing calls a model. - Docker or any local service.
- Finance or procurement background. The lesson defines each term the first time it appears.
- To know your organization's real process yet. each placeholder in the lesson tells you what to ask.
Setup
Python 3.11 or newer is enough. There is nothing to install: the two scripts use only the standard library. As of 1 December 2026 no package is required.
python3 --version
python3 request_check.py # the validator and estimator from Part 6
python3 request_eval.py # the golden-set eval from Part 8Save each script from this lesson under the file name in its first comment, in one folder. The outputs shown below are real runs of exactly this code.
What you must be able to do after this lesson#
- Write a model-access request with use case, data class, volume, cost estimate and eval plan
- Estimate monthly cost from token counts and a price list with a safety factor
- Follow the approval workflow and write a request that gets approved first time
- Apply API key hygiene with one scoped key per project kept in a secret store
- Respond to a hit quota by triaging, degrading gracefully and requesting more with evidence
Why this matters for an AI engineer#
Access and budget are the first gate between an idea and a running feature. Engineers who write a clear request get approved in days. Engineers who write "need GPT access for an experiment" wait weeks, get questions they could have answered up front, and sometimes find out later that their data class was never allowed on that model. Cost surprises are also among the most common production incidents in LLM systems, because a retry storm or an agent loop bills by the token. A request with a cost estimate, an owner and a cap turns that risk into a number everyone has agreed to.
| You'll hear... | You'll understand it after... |
|---|---|
| "File an access request with a cost estimate." | Part 1 and Part 2 |
| "What is the data class and the risk tier?" | 1.3 Data class and risk tier |
| "Your request was bounced: no eval plan." | 1.5 The eval plan |
| "Who approves this, and how long will it take?" | Part 3: The approval workflow |
| "Never share a key. Ask for a project key." | Part 4: API key hygiene |
| "You hit 80 percent of the budget." | Part 5: Budgets, quotas and caps |
| "Add the cost-center tag to every call." | 5.4 Cost attribution tags |
| "We are out of quota and users are waiting." | Part 7: When the quota is hit |
Part 1: What a request must say#
A request is a short document that lets a reviewer say yes without a meeting. Reviewers are busy and each one looks for one thing: finance wants the cost, security wants the data class, the platform team wants the volume and the key, the engineering lead wants the eval plan. If one of those is missing, the request goes back to you. So write all of them at once.
1.1 The seven fields#
| Field | What to write | Why a reviewer needs it |
|---|---|---|
| Owner | One named person and the team, with a cost center | Someone must answer for the spend and the incidents |
| Use case | One or two sentences: who uses the feature, what it does, what decision it supports | Lets the reviewer judge value and risk |
| Data class | The most sensitive class of data that will ever reach the model (see 1.3) | Decides which models, regions and logging rules are allowed |
| Expected volume | Requests per day, tokens in and out per request, peak rate | Drives cost and rate limits |
| Cost estimate | A monthly figure from a formula, plus a safety factor | Becomes the budget cap |
| Eval plan | What you will measure, on what data, and the pass rule | Shows the feature will be tested before and after launch |
| Risk tier | Low, medium or high, with a reason | Decides how many approvers are needed |
A good request fits on one page. If you need more, link to the feature brief from 13A.1, which is where most of this thinking starts.
1.2 Use case and expected volume#
Write the use case as a sentence a stranger could judge: "Summarize inbound support tickets for human agents; the agent reads and edits the summary before it is used." Notice what the sentence tells the reviewer: a human is in the loop, the output is a draft, the user is an employee. Those three facts lower the risk. Compare "an assistant for customers" which tells the reviewer almost nothing.
For volume, give four numbers: requests per day, input tokens per request, output tokens per request, and peak requests per minute. Get them from something real. If the feature does not exist yet, take a sample of 50 real inputs, count their tokens with the counting tools in 03.7, and multiply. If you are guessing, say so and give a range. A reviewer prefers an honest range ("1,000 to 3,000 requests per day, measured on 50 sample tickets") over a confident number with no source.
1.3 Data class and risk tier#
The data class is the most sensitive kind of data that can reach the model, including data that arrives by retrieval or tool calls, not only what the user types. Most organizations use three to five classes. A common ladder is public, internal, confidential and restricted. Your lesson on data handling (12.4) explains what counts as personal, secret or regulated data, and the companion lesson in this module, 14A.3, gives the organization's own classes and rules.
Pick the highest class that can plausibly appear. A support-ticket summarizer sees names, emails and sometimes payment complaints, so its class is at least confidential even though most tickets are boring. If you are unsure, ask the data owner before you file, because a wrong class is one of the most common reasons for a rejection after weeks of waiting.
The risk tier says how much harm the feature could do if it fails. A simple three-tier scheme looks like this:
| Tier | Typical feature | What a failure looks like |
|---|---|---|
| Low | Internal drafting aid, human edits before use | A bad draft, caught by the human |
| Medium | Customer-facing answers with citations, or internal automation with review | A wrong answer reaches a person or a record |
| High | Automated decisions about people, money or safety; agents with write tools | Real harm that is hard to undo |
The tier you choose sets how many approvers see the request. It is tempting to pick "low" to go faster. Do not: reviewers will re-tier your request and you will lose the time anyway, and an incident on a feature that was tiered too low is a bad conversation. The autonomy tiers in 13A.1 and the threat model in 12.1 help you place your feature honestly.
1.4 Owner, cost center and escalation#
Every request names one owner and a cost center. One owner, not a team alias, because "the team" cannot be asked to explain a bill. Also name a backup, because owners go on holiday while keys are live. The cost center is the budget line the spend will be charged to. If you do not know yours, ask your manager before filing, since finance will reject a request with no cost center.
1.5 The eval plan#
The eval plan is the field engineers most often leave empty, and it is the one that most separates serious requests from experiments. It does not have to be big. It has to say four things: the data (how many cases and where they come from), the metric (what is scored and how), the pass rule (the number that decides go or no-go) and the moment (before launch, and again after any prompt or model change). For example: "60 labelled tickets sampled from last quarter; a judge scores faithfulness to the ticket text; pass rule 0.85 or higher and zero invented order numbers; rerun on every prompt or model change in CI."
If you have never written one, the dataset ideas are in 10A.2 and the CI side is in 10A.8. Part 8 of this lesson turns the request validator itself into a tiny eval so you can see the pattern at work.
Part 2: Estimating the cost#
2.1 The formula#
Cost is tokens times price. Providers bill input tokens, output tokens, and usually a cheaper rate for cached input. 03.7 shows how to read the real usage numbers from each provider, and 11B.2 explains the price map and why output costs more than input. For a request estimate you only need this:
cost per request =
( fresh_input_tokens x price_in
+ cached_input_tokens x price_cache_read
+ output_tokens x price_out ) / 1,000,000
monthly cost = cost per request x requests per day x 30
requested budget = monthly cost x safety factorPrices are quoted per million tokens, so divide by one million. The safety factor covers retries, growth, a second prompt version in testing and the occasional long input. A factor of 1.5 is a common starting point for a stable feature. Use 2 or more for a new feature with uncertain volume, and say why.
A worked example, with invented prices: input costs 3.00 USD per million tokens, cached input 0.30, output 15.00. A call has 3,000 input tokens, of which 60 percent are served from the cache, and 300 output tokens. Fresh input is 1,200 tokens, which costs 1,200 times 3.00 over a million, or 0.0036 USD. Cached input is 1,800 tokens at 0.30, which is 0.00054 USD. Output is 300 at 15.00, which is 0.0045 USD. The call costs 0.00864 USD. At 2,000 requests a day for 30 days, that is 518.40 USD a month, and with a safety factor of 1.5 the requested budget is 777.60 USD.
2.2 What the formula leaves out#
Four things make real bills larger than the formula says, and a reviewer will ask about them:
- Retries and failures. A failed call that is retried is billed twice if the first one reached the model. See 03.8.
- Reasoning tokens. Reasoning models produce hidden thinking tokens that are billed as output (11B.2, 1.3). If you use one, measure the output tokens, do not guess from the visible answer.
- Agent loops. The quadratic growth from Part 1's tip. Estimate the average and the worst case.
- Evaluation and testing. Running your eval suite on every pull request costs real money. Budget for it, usually as a separate line. 10A.8 covers the tiered suites that keep this affordable.
A reviewer's favorite question is "what is the worst case?" Answer it before they ask: "If a loop bug makes traffic ten times higher, the 80 percent alert fires on day 3.6, and the hard cap stops spend on day 4.5." The script in Part 6 prints exactly this projection.
2.3 Cheaper before you ask#
If the estimate is larger than expected, apply the levers in 11B.1 and 11B.5 before you file: a smaller model for easy cases, prompt caching, shorter prompts, batching for non-urgent work. Showing in the request that you tried them is persuasive. A request for the most expensive model with no reason given is not.
Part 3: The approval workflow#
3.1 A typical shape#
Most organizations converge on the same shape. A request is filed, an automatic check rejects incomplete forms, the owner's manager approves the spend, security reviews anything above a threshold, and a platform or finance owner creates the key, the quota and the tags. Higher data classes and risk tiers add reviewers. The sample policy in the Part 6 script routes like this:
| Data class and tier | Approvers (Example Co) |
|---|---|
| Public or internal data, low risk | Team lead |
| Confidential data, or medium risk | Team lead and security review |
| Restricted data, or high risk | Team lead, security review and data protection officer |
This table is a sample. Use it as a model for what to look for in your own process, not as a rule.
3.2 Writing a request that is approved the first time#
Reviewers say yes quickly when four things are true:
- The request answers the questions before they are asked. Data class, worst case and eval plan are in the first screen.
- The numbers have a source. "Measured on 50 sample tickets" beats "about 3,000 tokens".
- The ask is sized to the stage. A pilot asks for a small budget and a short end date. A launch asks for a larger one with the pilot's measured numbers attached.
- The risk is named, with a control. "The model may invent order numbers; a validator rejects any number not found in the ticket" shows the reviewer you have thought about it.
A short, specific request also stays reviewable when you come back to it six months later to ask for more money.
3.3 Pilot, launch and renewal#
Think of access as three steps. A pilot grant is small and time-limited: enough to run your eval set and a limited trial. A launch grant follows the readiness review (13B.6) and is sized from measured pilot numbers. A renewal is a short review each quarter or year: is the feature still used, is the spend in line with the estimate, are the keys still rotated, is the owner still the owner? Treat renewal as a chance to turn off what nobody uses.
3.4 Exceptions and emergencies#
Sometimes you need access faster than the normal process allows, for example during an incident. A good process has a named fast path: a short-lived grant, a lower cap, an extra approver and a mandatory follow-up review. If your organization has no fast path, ask for one to be written before you need it. Do not work around the process with a personal key: that is the quickest way to turn a small problem into a security incident.
Part 4: API key hygiene and per-project keys#
An API key is a password that spends money. Whoever holds it can run calls on your bill and, depending on the key, read data you stored with the provider. Most key incidents are boring: a key pasted into a chat, committed to a repository, left in a notebook, or shared across five projects so nobody dares rotate it.
4.1 One key per project#
Give every project (and ideally every environment: development, staging, production) its own key. The reasons are practical:
- Blast radius. If one key leaks, you revoke one key and one project is affected, not everything.
- Attribution. Usage and cost are reported per key and per project, so the bill tells you who spent what.
- Limits. Quotas and rate limits attach to a project or workspace, so one noisy project cannot starve another.
- Rotation. You can rotate one key without a coordinated change across teams.
Providers support this directly. As verified on 2 December 2026 from official documentation: OpenAI lets an organization create projects with their own API keys and says you can set custom rate and spend limits per project, with project limits that cannot exceed the organization's; keys can be created with an expiration date. Anthropic's Admin API manages workspaces and their API keys, offers keys scoped to a workspace or to the organization, and exposes a Rate Limits API for workspace limits; the Spend Limits API is listed as available to Claude Enterprise organizations. Names and plans change, so check the current pages: OpenAI production best practices and the Anthropic Admin API.
Many organizations put a gateway between applications and providers. The gateway holds the real provider keys, hands out its own virtual keys per project, enforces budgets and writes the usage records. 11C.3 explains gateways. If your organization has one, your request is usually for a virtual key and a budget on the gateway, not for a provider key.
4.2 Where keys live#
The rules are short and strict:
- Never in code, notebooks, tickets, chat messages, screenshots or logs. Anything pasted into those places is public to everyone who can read them, including future readers.
- Not in the repository. Files such as
.envgo in.gitignore. A pre-commit scanner for secrets catches mistakes before they leave your laptop, and 12.7 covers secret scanning. - In a secret store for anything that is not your own laptop. The application reads the key at start-up from the platform's secret manager, not from a file in the image.
- Server side only. A key must never ship to a browser or a mobile app. Call your own backend, which holds the key.
- Never printed. Log the key's name or last four characters, never the value. Be careful with debug output and error reports that dump the environment.
4.3 Scope, expiry and rotation#
Ask for the narrowest key that works: only the models the project needs, only the endpoints it calls, the lowest rate limit that serves the peak, an expiry date if the platform supports one. Rotation means replacing a key on a schedule and whenever someone with access leaves the project. Practice it: a rotation you have never done is a rotation that will fail on the worst day. A good rotation procedure issues the new key, deploys it, watches for errors, then revokes the old key.
4.4 When a key leaks#
Treat any suspected leak as an incident (14A.5). The first step is always to revoke the key, not to investigate. Revoking is cheap: you will issue a new one in minutes. Then check the provider's usage records for calls you did not make, look at what the key could access, and write the postmortem. Do not hide it. A fast, honest report is treated far better than a leak that is discovered by the bill.
Part 5: Budgets, quotas and caps#
Deep-dive
Four words are used loosely, so fix them now.
| Term | Meaning | Who sets it |
|---|---|---|
| Budget | How much money a team, feature or project is expected to spend in a period | Finance with the owner |
| Quota | A limit on usage (tokens, requests or dollars) in a period, enforced by a system | Platform team or provider |
| Rate limit | A limit on speed (requests or tokens per minute) | Provider, and your gateway |
| Hard cap | A limit that stops spend when reached, as opposed to an alert that only warns | Platform team |
The machinery for these is in 11B.1, Part 7: token-denominated tenant quotas, agent budgets and a FinOps routine. The governance side (who owns the review and how often) is in 11C.4, Part 4. A later lesson on organization-level budgets in the cost and FinOps module will cover multi-team budgets in depth; until it is published, this lesson and 11B.1 are your reference.
5.1 Alerts, soft limits and hard caps#
A healthy budget has layers. At 50 percent of the monthly budget, a notice goes to the owner. At 80 percent, the owner and the team lead are alerted and the owner must decide: expected growth, or something wrong? At 100 percent, a hard cap stops non-critical spend, or the gateway switches the feature to a cheaper model. The layers matter because the cheapest moment to catch a problem is at 50 percent, and the most expensive is the invoice.
The example in Part 6 shows why caps beat alerts. If a bug makes traffic ten times higher, the 80 percent alert fires on day 3.6, a Friday evening might pass before anyone acts, and the hard cap on day 4.5 is the only thing that stops the rest of the month's overspend.
5.2 Per-feature and per-user limits#
Budgets work at several levels, and the smaller ones catch what the large ones miss: a per-project budget, a per-feature budget inside the project, per-user or per-tenant quotas so one heavy user cannot drain the pool, and per-request caps (maximum input tokens, maximum output tokens, maximum agent steps, a timeout). Per-request caps are the ones you control in code and they stop the runaway before it reaches the budget.
5.3 Provider limits versus your limits#
Providers enforce their own rate limits and spend limits, and those are a last line of defense. They are not a substitute for yours. A provider limit set at the organization level protects the organization, not your team's allocation. Set limits at the project level (the provider's projects or workspaces, or the gateway's virtual keys), and use the provider's alerts as a backstop. See 03.8 for how rate-limit errors look to your code.
5.4 Cost attribution tags#
Attribution means every call carries labels that say who it belongs to, so spend can be reported by team and feature. Without tags, the bill is one number. With them, you can answer "which feature caused the step in March?" The minimum useful tag set is small:
| Tag | Example | Answers |
|---|---|---|
cost_center |
CC-1234 |
Whose budget is this? |
project |
ticket-summary |
Which project? |
feature |
summary-draft |
Which feature inside the project? |
env |
prod |
Production or test? |
owner |
ada |
Who gets the alert? |
Tags travel in different ways depending on the setup: provider projects or workspaces give you attribution by key for free, a gateway can add tags to every request, and your own traces and logs can carry the tags as attributes (11A.1). Use the same names everywhere, define them once, and validate them: an untagged call should be rejected or flagged, because "unknown" spend is how a bill turns into a mystery. Never put personal data in a tag.
5.5 Reviewing spend#
Spend is reviewed on a cadence: weekly during a pilot, monthly in steady state. The review asks four questions. Is spend growing faster than usage? Which feature drives it? Did a price, a routing or a prompt change cause a step? Is the expensive model earning its premium on your eval results? Unit economics (cost per request, per resolved ticket, per user) are better than totals, as 13A.6 explains, because they tell you whether the feature is worth running.
Part 6: A request validator and cost estimator#
Deep-dive
The script below checks a request before it reaches a human, estimates the monthly cost, routes it to approvers using the sample policy, and projects when the budget runs out if traffic misbehaves. It is a toy, and that is the point: a validator you can read in five minutes is one your team will actually keep in sync with the policy. It uses only the standard library and calls no model. The model names, prices, thresholds and approvers in it are invented for Example Co.
# request_check.py: validate a model-access and budget request and estimate its cost.
# Standard library only. No keys, no network. Usage: python3 request_check.py [request.json]
# All prices and thresholds below are EXAMPLE numbers for a fictional company.
# Replace them with your organization's approved price list and policy.
import json
import sys
# Example price list, USD per 1M tokens (input, cached input read, output). Not real prices.
PRICES = {
"example-small": {"in": 0.50, "cache_read": 0.05, "out": 2.00},
"example-large": {"in": 3.00, "cache_read": 0.30, "out": 15.00},
}
APPROVED_MODELS = {"example-small", "example-large"} # placeholder: approved model list
REQUIRED = ["title", "owner", "cost_center", "use_case", "data_class", "model",
"requests_per_day", "input_tokens", "output_tokens", "eval_plan", "risk_tier"]
DATA_CLASSES = ["public", "internal", "confidential", "restricted"]
RISK_TIERS = ["low", "medium", "high"]
SAFETY_FACTOR = 1.5 # headroom for retries, growth and agent loops
DAYS = 30
def estimate(req):
"""Monthly cost = requests * (fresh_in*p_in + cached_in*p_cache + out*p_out) / 1e6 * days."""
p = PRICES[req["model"]]
cached = req.get("cached_fraction", 0.0)
fresh = req["input_tokens"] * (1 - cached)
per_request = (fresh * p["in"] + req["input_tokens"] * cached * p["cache_read"]
+ req["output_tokens"] * p["out"]) / 1_000_000
monthly = per_request * req["requests_per_day"] * DAYS
return per_request, monthly, monthly * SAFETY_FACTOR
def validate(req):
"""Return (errors, warnings). Errors block submission; warnings go to the reviewer."""
errors, warnings = [], []
for field in REQUIRED:
if req.get(field) in (None, "", 0):
errors.append(f"missing field: {field}")
if errors:
return errors, warnings
if req["model"] not in APPROVED_MODELS:
errors.append(f"model {req['model']!r} is not on the approved list")
if req["data_class"] not in DATA_CLASSES:
errors.append(f"unknown data_class {req['data_class']!r}")
if req["risk_tier"] not in RISK_TIERS:
errors.append(f"unknown risk_tier {req['risk_tier']!r}")
if len(req["eval_plan"].split()) < 8:
errors.append("eval_plan is too thin: say what is measured and the pass rule")
if req.get("api_key_scope") == "shared":
errors.append("shared API keys are not allowed: request one key per project")
if req.get("key_in_code"):
errors.append("keys must live in the secret store, never in code or chat")
if not errors:
if req["data_class"] in ("confidential", "restricted") and req["risk_tier"] == "low":
warnings.append("confidential data with a low risk tier: reviewer will question the tier")
if req.get("cached_fraction", 0) > 0.9:
warnings.append("cached_fraction above 0.9 is optimistic: show a measured hit rate")
return errors, warnings
def route(req):
"""Who must approve? Example policy: higher class and tier add approvers."""
approvers = ["team lead"]
if req["data_class"] in ("confidential", "restricted") or req["risk_tier"] != "low":
approvers.append("security review")
if req["data_class"] == "restricted" or req["risk_tier"] == "high":
approvers.append("data protection officer")
return approvers
def report(req):
errors, warnings = validate(req)
lines = [f"Request: {req.get('title', '(untitled)')}"]
if errors:
lines.append("STATUS: REJECTED BEFORE REVIEW")
lines += [f" error: {e}" for e in errors]
return "\n".join(lines)
per_req, monthly, requested = estimate(req)
lines.append("STATUS: READY FOR REVIEW")
lines.append(f" cost per request: ${per_req:.5f}")
lines.append(f" expected monthly cost: ${monthly:,.2f}")
lines.append(f" requested budget: ${requested:,.2f} (expected x {SAFETY_FACTOR})")
lines.append(f" approvers: {', '.join(route(req))}")
lines += [f" warning: {w}" for w in warnings]
return "\n".join(lines)
EXAMPLE = {
"title": "Ticket-summary assistant (EXAMPLE)", "owner": "ada@example.test",
"cost_center": "CC-1234", "use_case": "Summarize support tickets for agents",
"data_class": "confidential", "model": "example-large",
"requests_per_day": 2000, "input_tokens": 3000, "output_tokens": 300,
"cached_fraction": 0.6,
"eval_plan": "60 labelled tickets; faithfulness judge score at least 0.85; no invented order numbers",
"risk_tier": "medium", "api_key_scope": "per-project",
}
if __name__ == "__main__":
if len(sys.argv) > 1:
print(report(json.load(open(sys.argv[1]))))
else:
print(report(EXAMPLE))
print()
bad = dict(EXAMPLE, title="Quick experiment (EXAMPLE, flawed)", model="example-xl",
eval_plan="we will test it", api_key_scope="shared")
print(report(bad))
print()
# Quota check: when is 80 and 100 percent of the budget reached?
_, monthly, budget = estimate(EXAMPLE)
expected_daily = monthly / DAYS
print("Quota projection for the first request (budget = expected x 1.5):")
for label, factor in (("as planned", 1.0), ("a loop bug makes traffic 10x", 10.0)):
for pct in (0.8, 1.0):
day = budget * pct / (expected_daily * factor)
print(f" {label:30s} {int(pct * 100):3d}% of budget on day {day:5.1f}")Real output:
Request: Ticket-summary assistant (EXAMPLE)
STATUS: READY FOR REVIEW
cost per request: $0.00864
expected monthly cost: $518.40
requested budget: $777.60 (expected x 1.5)
approvers: team lead, security review
Request: Quick experiment (EXAMPLE, flawed)
STATUS: REJECTED BEFORE REVIEW
error: model 'example-xl' is not on the approved list
error: eval_plan is too thin: say what is measured and the pass rule
error: shared API keys are not allowed: request one key per project
Quota projection for the first request (budget = expected x 1.5):
as planned 80% of budget on day 36.0
as planned 100% of budget on day 45.0
a loop bug makes traffic 10x 80% of budget on day 3.6
a loop bug makes traffic 10x 100% of budget on day 4.5Read the output with a reviewer's eyes. The first request is ready: it names a measurable eval plan, a per-project key and a source for its volume. The second is rejected by a machine in a second, with three reasons, so no human spent time on it. And the projection shows the point of a hard cap: "as planned" the budget lasts longer than the month, but a ten-times bug exhausts it in under five days.
6.1 A filled-in sample request#
Here is the first example as the text a reviewer would read. It is fictional.
REQUEST (EXAMPLE, fictional company "Example Co")
Title: Ticket-summary assistant, pilot
Owner: Ada Example (backup: Grace Example), cost center CC-1234
Use case: Summarize inbound support tickets for human agents. The agent
reads and edits the summary before it is used.
Data class: Confidential (names, emails, order numbers). No payment card data.
Model: example-large, region as per the approved list
Volume: 2,000 requests/day (measured: 50 sample tickets, 3,000 input
tokens and 300 output tokens on average), peak 10 requests/minute
Cost: 0.00864 USD/request, 518.40 USD/month expected, 777.60 USD budget
(factor 1.5). Cache hit rate 60 percent assumed; will measure.
Worst case: 10x traffic bug: 80 percent alert on day 3.6, hard cap on day 4.5.
Code caps input at 6,000 tokens and output at 600 tokens.
Eval plan: 60 labelled tickets, faithfulness judge at least 0.85, zero
invented order numbers, rerun in CI on every prompt or model change.
Risk tier: Medium. Human edits every summary. Control: validator rejects any
order number not present in the ticket.
Keys: One production key and one development key, both project-scoped,
stored in the secret store, rotated every 90 days (Example Co rule).
Tags: cost_center, project, feature, env, owner on every call.
Ask: Pilot for 6 weeks, then a launch review with measured numbers.Part 7: When the quota is hit#
It will happen. A launch goes better than planned, a loop misbehaves, or a provider rate limit bites at peak. Plan the response before the day.
8.1 First ten minutes: triage#
Ask three questions in order. Is this a limit or a bug? Compare current spend or request rate with the baseline. A rate ten times higher than usual points to a loop, a retry storm or an abuse case, and the right response is to contain it, not to ask for more money: kill switch, lower per-request caps, revoke a leaked key (14A.5 and 11C.4 have the playbook). Which limit is it? Your budget cap, the gateway's quota, or the provider's rate limit? The error message and your traces will say (03.8). Who is affected? All users, one tenant, or only background jobs?
8.2 Degrade gracefully#
Users should not see a stack trace. Decide the degraded mode in advance (11C.4, 1.6): switch to a cheaper model for easy requests (11B.5), serve cached answers, queue non-urgent work for the batch API (03.9), shed low-priority traffic (11C.3), or hand off to a human with a clear message. Rate-limit errors are different from budget errors: a rate limit is solved by backoff and queueing, a budget cap needs a decision from a person.
8.3 Asking for more#
If the spend is real and valuable, ask for an increase with evidence, using the same request format. Attach measured volume since launch, cost per request against the estimate, why they differ, the levers you have already pulled, and the new number with its safety factor. Never raise a cap yourself, and never use someone else's key. A short, honest increase request is usually approved quickly; a surprise overspend explained afterward is not.
8.4 After the day#
Write down what happened. If it was a bug, treat it as an incident and write the postmortem. If it was growth, update the estimate and the safety factor. Either way, add an eval case or a test so the cap behavior is checked next time, and review whether the alert at 80 percent reached the right person soon enough.
Part 8: Evaluate it#
Deep-dive
A request process is a system, and systems get evals. The thing under test here is the validator in Part 6: if its rules drift from the written policy, reviewers lose trust in it. The test is tiny, deterministic and free.
Design
- Inputs: eight requests with a known right answer, decided by a human before running the code: a clean request, a public-data low-risk request, a restricted-data request, an unapproved model, a shared key, a key pasted in code, a missing eval plan, a missing owner. Add one numeric case: one million input and one million output tokens at the example prices must cost exactly 18.00 USD.
- Metric: routing accuracy (exact match on "reject" or the approver list), plus an exact-match check on the arithmetic.
- Pass rule: 100 percent on the eight cases and an exact estimator match. Anything less is a bug in the validator or the policy, not noise, because there is no model in the loop.
# request_eval.py: a tiny golden-set eval for the request checker. Save next to request_check.py.
from request_check import EXAMPLE, validate, route, estimate
# (name, changes to EXAMPLE, expected: "reject" or the expected approver list)
CASES = [
("clean request", {}, ["team lead", "security review"]),
("public data, low risk", {"data_class": "public", "risk_tier": "low"}, ["team lead"]),
("restricted data", {"data_class": "restricted"}, ["team lead", "security review", "data protection officer"]),
("unapproved model", {"model": "example-xl"}, "reject"),
("shared key", {"api_key_scope": "shared"}, "reject"),
("key pasted in code", {"key_in_code": True}, "reject"),
("no eval plan", {"eval_plan": "later"}, "reject"),
("missing owner", {"owner": ""}, "reject"),
]
passed = 0
for name, change, expected in CASES:
req = dict(EXAMPLE, **change)
errors, _ = validate(req)
actual = "reject" if errors else route(req)
ok = actual == expected
passed += ok
print(f"{'PASS' if ok else 'FAIL'} {name}")
# Metric 2: the estimator against a hand-computed value (3.00 + 15.00 USD per 1M tokens, no caching).
req = dict(EXAMPLE, input_tokens=1_000_000, output_tokens=1_000_000, requests_per_day=1, cached_fraction=0.0)
per_request, _, _ = estimate(req)
math_ok = abs(per_request - 18.00) < 1e-9
print(f"{'PASS' if math_ok else 'FAIL'} estimator matches hand calculation ($18.00)")
rate = passed / len(CASES)
print(f"\nrouting accuracy: {rate:.0%} ({passed}/{len(CASES)}); pass rule: 100% and the estimator check")
raise SystemExit(0 if rate == 1.0 and math_ok else 1)Real output:
PASS clean request
PASS public data, low risk
PASS restricted data
PASS unapproved model
PASS shared key
PASS key pasted in code
PASS no eval plan
PASS missing owner
PASS estimator matches hand calculation ($18.00)
routing accuracy: 100% (8/8); pass rule: 100% and the estimator checkThe script exits non-zero on a failure, so it can be a CI step on the repository that holds the policy file. When someone changes the approved list or the thresholds, they update the golden cases in the same change.
This is a code-grader eval, the simplest kind in 10A.3. If your request process later adds a model-written check (for example, "is this eval plan specific enough?"), the judge needs calibration first (10A.4 and 10A.5). Wire the golden set into the regression flow from 10A.8, and keep an eye on the online side too, such as budget alerts that fired against what was actually spent (10A.9).
If your team writes evals in DeepEval (the required framework track), the same cases become test cases with a custom metric that returns a pass or fail: see 10B.2 for test cases and the runner, 10B.3 for custom metrics, 10B.6 for datasets and 10B.7 for running them in CI. The metrics in 10B.4 and the tracing view in 10B.5 matter once the feature behind the request is live. (optional) If your organization uses Inspect, the equivalent building blocks are in 10B.8 to 10B.10, and 10B.17 helps you choose. The design above does not depend on either framework.
Common misconceptions#
- "A personal key is fine for a quick test." Personal keys bypass attribution, data policy and approvals, and they leak into screenshots and repositories. Use a sandbox key issued under the process.
- "The provider will stop me if I overspend." Provider limits are a backstop set at the organization level. Your project can burn the whole organization's allowance before they trigger.
- "One shared key is simpler." It is simpler until it leaks, when you must rotate it for everyone at once, and until the bill arrives and nobody can say whose it is.
- "An alert at 80 percent is the same as a cap." An alert needs a person to act. A cap acts by itself.
- "The cost estimate is just paperwork." It is the number the cap is set from, and the number you will be asked to explain.
- "If I pick a low risk tier, it will go faster." Reviewers re-tier. A wrong tier costs time now and trust later.
- "The estimate is the product of tokens and price, so it is exact." It is a model of usage. Retries, reasoning tokens, agent loops and evals add to it, which is why you apply a safety factor and measure after launch.
Key takeaways#
- A request has seven fields: owner, use case, data class, expected volume, cost estimate, eval plan and risk tier. Write all of them with sources.
- Estimate cost with the formula: tokens times price per million, times requests per day and 30, times a safety factor. Take prices from the approved price list and date them.
- Answer "what is the worst case?" before the reviewer asks, and size the hard cap from the answer.
- One key per project and environment, narrow scope, a secret store, rotation, never in code or chat. A suspected leak is an incident: revoke first.
- Budgets have layers: alerts at thresholds, per-feature and per-user quotas, per-request caps and hard caps. Alerts warn, caps act.
- Tag every call with cost center, project, feature, environment and owner, and reject untagged calls.
- At quota: decide whether it is a bug or growth, degrade gracefully, and ask for more with measured evidence.
- Test your own process: a golden set for the validator with a 100 percent pass rule keeps the policy and the code in sync.
Terms introduced in this lesson#
| Term | Meaning |
|---|---|
| Model-access request | A short document asking an organization to allow a use case to call a model, with a budget |
| Data class | The most sensitive category of data that can reach a model (for example public, internal, confidential, restricted) |
| Risk tier | A rating of how much harm a feature could do if it fails, which sets how many approvers are needed |
| Safety factor | A multiplier on the expected cost that covers retries, growth and uncertainty |
| Budget | The money a team or feature is expected to spend in a period |
| Quota | A usage limit (tokens, requests or dollars) enforced by a system |
| Rate limit | A cap on speed, such as requests or tokens per minute |
| Hard cap | A limit that stops spend when reached, rather than only sending an alert |
| Per-project key | An API key issued for one project and environment, so it can be limited, attributed and revoked on its own |
| Virtual key | A key issued by an internal gateway that maps to a budget and hides the real provider key |
| Cost attribution tag | A label on each call (cost center, project, feature) that lets spend be reported by owner |
| Key rotation | Replacing an API key with a new one on a schedule or after exposure, then revoking the old one |
Exercises#
- Write a request. Pick a feature from your own work or from the capstone (13B.2). Fill the seven fields from Part 1 and run the numbers through
request_check.pywith your own sample counts. Hint: count tokens on 20 real inputs first; a range with a source beats a guess. - Break the validator. Add a new rule (for example "output tokens above 2,000 need a written reason") and add two golden cases for it to
request_eval.py: one that passes and one that is rejected. Hint: change the rule and the cases in the same step, so the pass rule stays at 100 percent. - Find the worst case. For your request in exercise 1, compute the day on which 80 percent and 100 percent of the budget are reached if traffic is five times higher. Then name the per-request cap in code that would stop a loop sooner. Hint: the projection in Part 6 divides the budget by the daily spend times the multiplier.
- Design the tags. Write the tag set for a team with three features and two environments. Say how each tag is attached (key, gateway or trace attribute) and what happens to an untagged call. Hint: aim for five tags or fewer, none containing personal data.
- Plan a rotation. Write the step-by-step procedure for rotating a production key with no downtime, and the step that revokes the old key. Hint: issue, deploy, watch, then revoke, never revoke first unless the key leaked.
- Draft the quota-hit runbook. For a feature you know, write the degraded mode for each of three causes: provider rate limit, budget cap, runaway loop. Hint: backoff and queue for rate limits, a decision for budgets, containment for loops.
Check yourself#
- Name the seven fields of a model-access request.Owner, use case, data class, expected volume, cost estimate, eval plan, risk tier.
- What is the monthly cost formula, and what does the safety factor cover?Cost per request is (fresh input x input price + cached input x cache price + output x output price) divided by one million; monthly cost is that times requests per day times 30; the requested budget is monthly cost times the safety factor. The factor covers retries, growth, a second prompt version in testing and long inputs.
- Why should the data class be the highest class that can plausibly reach the model?Because the class decides which models, regions and logging rules are allowed. A request that understates it can be rejected late, or worse, approved on false grounds.
- Why is one key per project better than one shared key? Give three reasons.A leak affects one project and one revocation, usage and cost are attributed per key, quotas and rate limits attach per project, and rotation does not need cross-team coordination.
- Where must an API key never appear, and where should it live instead?Never in code, notebooks, tickets, chat, screenshots, logs or the repository, and never in a browser or mobile app. It lives in the approved secret store and is read by the server side at start-up.
- What is the difference between an alert at 80 percent and a hard cap?An alert warns a person who must act. A hard cap acts automatically and stops (or degrades) the spend when reached.
- A key is suspected to have leaked. What is the first action, and why not investigate first?Revoke the key. Revoking is cheap and stops further misuse; investigation (usage records, what the key could reach, postmortem) follows.
- What do cost attribution tags answer, and which tag should never contain personal data?They answer whose budget a call belongs to and which feature caused a change. Personal data must never go in any tag.
- Your feature hits its quota at midday. What three questions do you ask first?Is it a limit or a bug (compare with baseline)? Which limit is it (budget, gateway or provider)? Who is affected (everyone, one tenant, background jobs)?
- Why does the Part 8 eval require 100 percent rather than, say, 90 percent?There is no model in the loop, so the checker is deterministic. Any failure is a bug in the code or the policy, not noise.
Further resources#
- Within this path: 03.7 Token Counting, Cost Tracking and Prompt Caching, 11B.1 Cost and Latency Optimization (Part 7 on budgets and quotas), 11B.2 Tokenomics, 11C.4 Operating LLM Systems (Part 4 on cost governance), 12.4 PII, Privacy and Data Leakage and 12.7 Securing Data and the Supply Chain.
- Provider documentation (checked 2 December 2026): OpenAI production best practices for projects, keys and per-project limits; Anthropic Admin API for workspaces and keys.
- Standards: the OWASP GenAI Security Project for unbounded consumption and credential risks.
- Organization-specific pages: your own request form, price list, approved provider list and cost dashboard. If any of these do not exist yet, that is your first contribution.
← 14A.3 — Security, Data and Compliance Policy | Module 14A overview | 14A.5 — The Incident Process for AI Systems →