Skip to content
Back to skills

Llm Cost Allocation

ASecurity

Allocate Anthropic (Claude API) and OpenAI API spend to teams, features, API keys, workspaces and projects, in money, with read-only Admin API calls. Use this whenever someone asks how much each team, product feature, service or API key spends on Claude or GPT models, wants an LLM chargeback or showback, finds the cost report only splits by workspace or project, has token counts but no dollars, asks how to price cache writes, cache reads, batch or priority tiers, or sees a gap between their o...

  • 5 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 1, 2026
ai-agentspythongoshellbashsqlawsazuregitapi

Works with

  • claude code
  • cursor
  • api

Security analysis

A100/100

Pro scans all 3 files and shows the line behind each finding

Scanned December 1, 2026

npx -y skills add costory-io/finops-skills --skill llm-cost-allocation --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Llm Cost Allocation?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Llm Cost Allocation
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/costory-io-llm-cost-allocation/badge)](https://www.skillsdirectory.com/skills/costory-io-llm-cost-allocation)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: llm-cost-allocation
description: Allocate Anthropic (Claude API) and OpenAI API spend to teams, features, API keys, workspaces and projects, in money, with read-only Admin API calls. Use this whenever someone asks how much each team, product feature, service or API key spends on Claude or GPT models, wants an LLM chargeback or showback, finds the cost report only splits by workspace or project, has token counts but no dollars, asks how to price cache writes, cache reads, batch or priority tiers, or sees a gap between their own token math and the invoice. Also use it when they paste usage_report, cost_report, analytics, /organization/usage or /organization/costs output and ask what it means, even if they never say "allocation".
---

# LLM cost allocation (Anthropic and OpenAI APIs)

The invoice says what the provider cost. Finance wants it per team. Between the two sit two kinds of data the providers expose separately:

| Provider | Usage data (tokens) | Cost data (money) |
|----------|---------------------|-------------------|
| Anthropic, legacy | `GET /v1/organizations/usage_report/messages`: 1m/1h/1d buckets, group by `api_key_id`, `workspace_id`, `model`, `service_tier`, `context_window`, `inference_geo`, `speed`, `account_id`, `service_account_id` | `GET /v1/organizations/cost_report`: daily only, group by `workspace_id` and `description` only, USD, excludes Priority Tier |
| Anthropic, Usage and Cost Analytics API (beta, header `anthropic-beta: analytics-usage-cost-2026-08-24`) | `GET /v1/organizations/analytics/usage` | `GET /v1/organizations/analytics/cost`: same dimensions as usage, including `api_key_id`, `workspace_id`, `model`, `actor` (the user or service account behind each request), `product` (for example `claude_code`), plus `cost_type` and `token_type` |
| OpenAI | `GET /v1/organization/usage/completions`: 1m/1h/1d, group by `project_id`, `user_id`, `api_key_id`, `model`, `batch`, `service_tier`, `api_source` | `GET /v1/organization/costs`: daily only, group by `project_id`, `user_id`, `line_item`, `api_key_id`, `api_source` |

The old rule "usage is granular, cost is coarse, so you must rebuild money from tokens" is only half true in late 2026. Both providers now return cost grouped by API key: Anthropic in the beta analytics endpoint (data from 2026-01-01, last 365 days, 31 days per request), OpenAI in `/organization/costs`. So:

1. **Per key / per workspace / per project money: take it from the provider cost endpoint** when it can group the way you need. It is what you are billed (post-discount, pre-credit on Anthropic).
2. **Rebuild cost from usage x a price book** when the cost endpoint cannot answer: the legacy Anthropic cost report (workspace only), history outside the analytics window, a split the cost endpoint does not offer in one request (Anthropic: at most 5 `group_by` dimensions; OpenAI: some `group_by` combinations return HTTP 400), per-feature splits from your own request logs, or a "what would this cost on model X" estimate.
3. **Always reconcile**: computed total vs provider total for the same period, gap in %, causes named. Never hide the gap, never scale it away silently.

Per person, not just per key: on Anthropic, `group_by[]=actor` returns cost per user or service account, and `products[]=claude_code&group_by[]=actor` gives Claude Code cost per user. For AI coding tools as a whole (seats, Cursor, Copilot), use the `ai-coding-spend-per-developer` skill.

Everything here is read-only: GET requests on reporting endpoints.

## 1. Set up

**Plan.** The Anthropic Admin API is not available to organizations on the claude.ai Team plan, nor to individual Console accounts. A company on Team that also has a Claude Console organization can use the API with that organization. Claude Enterprise uses the Analytics API key described below.

**Keys (sensitive).**
- Anthropic: an Admin API key (`sk-ant-admin01-...`), created by an organization admin on the Claude Console Admin keys page. Console admin keys have no scopes: every key has full access to the Admin API, not just reports. So give this job its own key with an expiration date, keep it in a secrets manager, rotate it, and where possible use Workload Identity Federation with the `org:admin` scope for short-lived tokens. Claude Enterprise organizations use a key with only the `read:analytics` scope, which is the read-only option. Workspace API keys do not work.
- OpenAI: an organization Admin key from the platform admin keys page. Admin keys only work on administration endpoints. A read-only or usage-only admin key for the API Platform is not documented (verify in the key creation dialog). Treat it as a full admin credential.
- Rules: env vars only (`ANTHROPIC_ADMIN_KEY`, `OPENAI_ADMIN_KEY`). Never paste a key into the chat, never echo it, never write it to a file or a command line argument, never put it in a URL. If the user pastes one, tell them to rotate it.

**Price book.** Default: LiteLLM's `model_prices_and_context_window.json` (MIT, about 7,000 model entries, per-token USD). It has no effective dating: a price change overwrites the old value. So for each month you allocate, pin the file to a git commit and archive the SHA with the output:

```
https://raw.githubusercontent.com/BerriAI/litellm/<commit_sha>/model_prices_and_context_window.json
```

Use the commit in force during the month you price, not today's. Layer an overrides JSON (same schema, later file wins) for negotiated rates, models LiteLLM lacks, and modes it does not price (Anthropic fast mode has no field in it as of commit `8981323`, 2026-11-28).

**Mapping.** A small CSV the user maintains, the only place team ownership lives:

```csv
kind,id,team
api_key,apikey_01Rj2N8SVvo6BePZj99NhmiT,search
workspace,wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ,support-bot
project,proj_abc123,growth
```

Key first, then workspace/project. Anything else lands in an explicit `UNMAPPED` row. IDs come from the List API Keys / List Workspaces endpoints (Anthropic) or the projects page (OpenAI). Per-feature allocation needs one key (or workspace/project) per feature; if several features share a key, the APIs cannot split them and you need your own request logs.

## 2. Pull and compute

```bash
export ANTHROPIC_ADMIN_KEY=...   # typed in the shell, not pasted into the agent
python3 scripts/llm_costs.py --provider anthropic --start 2026-10-01 --end 2026-11-01 \
  --prices https://raw.githubusercontent.com/BerriAI/litellm/<sha>/model_prices_and_context_window.json \
  --prices overrides.json --mapping teams.csv --out anthropic_2026-10.csv
python3 scripts/llm_costs.py --provider openai --start 2026-10-01 --end 2026-11-01 --prices prices.json --out openai_2026-10.csv
```

The script (stdlib only) pages through usage, prices each token class, applies the mapping, then fetches the provider total and prints one `RECONCILIATION` line plus the price book sha256. CSV columns include `computed_usd` (estimate) and, where the provider can group by key, `provider_usd_for_key` (provider-reported). Every row carries `flags` for anything priced by fallback.

If the user only needs provider-reported money per key on Anthropic, one request answers it:

```bash
curl -sS --globoff "https://api.anthropic.com/v1/organizations/analytics/cost?starting_at=2026-10-01T00:00:00Z&ending_at=2026-11-01T00:00:00Z&group_by[]=api_key_id&group_by[]=workspace_id&limit=1000" \
  -H "x-api-key: $ANTHROPIC_ADMIN_KEY" -H "anthropic-version: 2026-10-21" \
  -H "anthropic-beta: analytics-usage-cost-2026-08-24"
```

`anthropic-version: 2026-10-21` is the current API version (released 2026-10-21); `2023-06-01` is still accepted. The beta header is what enables this endpoint. `cost.amount` is a decimal string in cents (`"41280.000000"` = $412.80), `list_amount` is the pre-discount amount. Rows are ranked by `amount`; page with `next_page` (a cursor can expire after a data refresh: HTTP 410, restart). OpenAI equivalent: `GET /v1/organization/costs?start_time=<unix>&end_time=<unix>&group_by=api_key_id` with `Authorization: Bearer $OPENAI_ADMIN_KEY`; `amount.value` is treated as dollars in `amount.currency`, as in the OpenAI cookbook examples (verify on one row against the dashboard). On `/organization/costs`, combining `user_id` with `project_id` grouping or the `project_ids` filter depends on the organization and time range; unsupported combinations return HTTP 400.

## 3. Pricing traps

These decide whether a computed number is right. Each is a place where "tokens x input price" is wrong.

**Anthropic**
- **Cache writes are two classes.** `cache_creation.ephemeral_5m_input_tokens` costs 1.25x base input, `ephemeral_1h_input_tokens` 2x. LiteLLM fields: `cache_creation_input_token_cost` and `cache_creation_input_token_cost_above_1hr`.
- **Cache reads are not always 0.1x.** 0.1x on most models, 0.05x on Opus 5.5 and Sonnet 5.5, 0.025x on Fable/Mythos 5.1 and 5.2. Use the per-model `cache_read_input_token_cost`, never a hardcoded ratio.
- **`uncached_input_tokens` excludes cache tokens.** Do not add cache tokens to it and price everything at input rate.
- **Batch**: 50% off input and output; stacks with caching and data residency. `service_tier=batch` in usage. LiteLLM `*_batches` fields. Mind the arithmetic when explaining a gap: if batch rows were priced at full rate, the overstatement equals the batch-priced amount (full rate is 2x), not the full-rate amount.
- **Long context**: Claude 4.6+ models (except Haiku 5.5) bill the full 1M window at standard rates. Haiku 5.5 charges higher prices for prompts over 100,000 tokens, cache tokens included in the count. Usage reports it as `context_window=200k-1M` (a label: it means "above the model's own boundary"). LiteLLM `*_above_100k_tokens` / `*_above_200k_tokens`.
- **Data residency**: `inference_geo=us` costs 1.1x on every token class (input, output, cache writes, cache reads) for Claude 4.6+ models. Earlier models report `not_available`.
- **Fast mode** (`speed=fast`): premium prices per model (Opus 5.5: $8 / $40 per MTok vs $4 / $20). Not in LiteLLM: add an override or the rows stay flagged.
- **Priority Tier**: requests under a commitment show `service_tier=priority` in usage but zero token cost in the analytics cost data; the commitment fee is billed separately and is not in this data. The legacy cost report excludes Priority entirely. Computing them at list price creates a gap that is not an error.
- **Flex tiers** (`flex`, `flex_discount`) appear as service tier values; their prices are not on the pricing page (verify with your account team). The script prices them at standard and flags them.
- **Web search**: $10 per 1,000 searches, from `server_tool_use.web_search_requests`. Web fetch: no fee beyond tokens.
- **Not in the usage report at all**: code execution (billed by container hour beyond 1,550 free hours per month), Claude Managed Agents session runtime ($0.08 per session-hour). They are in the cost data, so they show up as a positive gap.

**OpenAI**
- **`input_tokens` includes cached and cache-write tokens.** Uncached = `input_tokens - input_cached_tokens - input_cache_write_tokens`.
- **Cached input ratio is per model**, from about 5% to 50% of input. Use `cache_read_input_token_cost`.
- **Cache writes**: newer models list separate 30m and 12h cache-write prices, and the completions usage result reports them: `input_cache_write_30m_tokens`, `input_cache_write_12h_tokens` (older rows may only carry the total `input_cache_write_tokens`). They are included in `input_tokens`, so uncached = `input_tokens - input_cached_tokens - input_cache_write_tokens`. LiteLLM fields: `cache_creation_input_token_cost` (30m) and `cache_creation_input_token_cost_above_12hr` (12h). A write with no price in the book is priced at input rate and flagged.
- **Batch** (`batch=true`) about 50% off; **Flex** about 50% off (in beta wind-down); **Priority was renamed Fast on 2026-07-30**, about 2x standard; Ultrafast exists on some models. The exact `service_tier` strings returned by the usage API are not listed in the reference (verify on real output); unknown tiers are priced at standard and flagged.
- **Long context**: above 272K input tokens some flagship models charge 2x input and 1.5x output. Usage is aggregated per bucket, not per request, so this cannot be applied from usage data: computed cost is low for long-prompt workloads.
- **Regional processing / data residency**: +10% for models released on or after 2026-03-05 (LiteLLM `regional_processing_uplift_multiplier_*`). The usage API does not expose the region (verify), so map residency projects and apply it by project.
- **Tool and other fees**: web search $10 or $25 per 1,000 calls depending on model and tool version, file search $2.50 per 1,000 calls plus $0.10/GB/day storage. Embeddings, images, audio, moderations, vector stores and code interpreter have their own usage endpoints; the script prices completions only, so these show up as a gap.
- **Fine-tuned models**: usage reports `ft:<base>:<org>::<id>`; price under the `ft:<base>` entry. Training cost is a cost line, not usage.

## 4. Reconcile

Print it every time, next to the allocation:

```
computed (estimate, list price)  $38,750   price book: litellm@8981323
provider-reported                $38,900   analytics/cost, 2026-10-01..2026-11-01
gap                              -$150 (-0.4%)
```

Gap = (computed - provider) / provider. Rules of thumb, not provider thresholds: within about 2% is pricing noise; above 5% means a trap above was missed. Likely causes, by sign:
- **Computed higher**: Priority Tier commitment usage priced at list (provider shows zero), negotiated discounts (Anthropic `amount` vs `list_amount` shows how much), a price book newer or older than the month, OpenAI Scale Tier usage covered by the bundle.
- **Computed lower**: costs with no usage rows (code execution, session runtime, non-completions OpenAI endpoints, tool call fees), unpriced models or modes (fast mode, fine-tunes), long-context surcharges invisible in OpenAI usage, cache writes with no price in the book.
- **Timing**: Anthropic analytics data refreshes about every 4 hours (up to 24), and values can be revised until about 7 days after month end. Close a month after the 8th. The legacy endpoints update within minutes and may disagree with analytics for recent days. Credits are not subtracted in either.
- **Scope**: Claude Enterprise organizations: the legacy usage endpoint leaves out Claude Code, Cowork and chat usage that the cost endpoint includes, so they cannot be reconciled against each other.

For chargeback, bill the provider-reported amount. When you only have computed per-key costs, allocate the provider total pro rata to computed shares and show the residual (gap) as its own line. Never present an estimate as billed money.

## 5. Report

```
# LLM spend by team: <provider(s)>, <period>

## Summary
<total billed, top 3 teams with share, unmapped share, reconciliation gap>

## By team
| Team | Provider-reported $ | Computed $ (estimate) | Share | Top model | Notes |
| UNMAPPED | ... |   (always shown, even when zero)

## By key / workspace / project (top 20)

## Reconciliation
<computed vs provider, gap %, named causes, price book commit, flags count>

## Before you act
<unmapped keys to assign, shared keys to split, unpriced rows, period still open for revision>
```

Rules for the numbers:
- Label every figure: provider-reported (billed, from a cost endpoint), computed estimate (usage x price book, list price unless overridden), or measured (token counts).
- Show `UNMAPPED` and `no_api_key` (Console playground, some Managed Agents sessions, Workload Identity Federation tokens) explicitly; never fold them into the largest team.
- Keep the price book commit and the mapping file version with the output, so a month can be recomputed identically.

## Out of scope: the same models through a cloud bill

- **Amazon Bedrock**: AWS Cost and Usage Report 2.0, product code `AmazonBedrock` / `AmazonBedrockService`, one line item per token type with model, tier and cross-region in `line_item_usage_type`; cost allocation by IAM user or role is available in CUR 2.0. Some third-party models may bill through AWS Marketplace instead (verify on your CUR).
- **Claude Platform on AWS** (Anthropic-operated): one AWS Marketplace line in Claude Consumption Units ($0.01 each); use the Anthropic analytics endpoints for the breakdown.
- **Vertex AI (Claude, Gemini)**: Cloud Billing export to BigQuery, per-model token SKUs (input, output, cache, long context); the exact service description varies (verify in your export). Whether resource labels reach partner-model SKUs is not documented (verify), so separate projects per team are the reliable split.
- **Azure OpenAI / Foundry Models**: Azure Cost Management, per-model input and output meters under the Foundry (Cognitive Services) resource (meter category name: verify in your data); PTU deployments are a capacity charge. Split by resource or deployment.

## When you cannot run it yourself

If you have no access to the user's environment, paste the complete, filled-in SQL or command in your answer so the user can run it as is, with their project, period and table names already substituted where known. Do not point the user to this skill's file paths (`sql/...`, `scripts/...`): they usually cannot see them. Then interpret the output they paste back with the rules above.

## Going further

This gives a monthly snapshot per provider. Keeping it current means putting it in one view with the same models bought through Bedrock, Vertex and Azure OpenAI in the cloud bills, mapping keys, workspaces, projects and cloud accounts to the same team hierarchy as the rest of the infrastructure, and reporting in euros when finance closes in euros. You can build that with the APIs above and a billing export; tools such as Costory (costory.io), whose team wrote this skill, do it as a product, with the same allocation model as cloud and data spend.

Files in this skill

  • SKILL.md17.6 KB
  • references/sources.md10.7 KB
  • scripts/llm_costs.py16.4 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.