Skip to main content

llm-cost-shield (Python)

Stop surprise AI bills, in Python. Spending limits per user, per feature and per day, a guard against retry and agent loops, rate limits, a response cache, and routing of simple requests to a cheaper model. Works with OpenAI, Anthropic, Google Gemini, Amazon Bedrock, OpenRouter or any LLM API. No dependencies.

pip install llm-cost-shield

This is the Python version of the npm package. The test suite checks it against the JavaScript version on 88 usage and pricing cases and on a full analyzer run, so both give the same costs.

Quick start

from openai import OpenAI
from llm_cost_shield import CostShield, BudgetExceededError, RateLimitError, LoopDetectedError, pick_model

client = OpenAI()
shield = CostShield(
    # USD per 1M tokens. Copy current numbers from your provider's pricing page.
    prices={
        "your-strong-model": {"input": 0, "output": 0, "cachedInput": 0},
        "your-cheap-model": {"input": 0, "output": 0},
    },
    budgets={"daily_usd": 20, "per_user_daily_usd": 0.5, "per_feature_daily_usd": {"support-bot": 5}},
    time_zone="Asia/Karachi",                 # when the daily budget resets (default UTC)
    rate_limit={"per_user_per_minute": 20},
    cache_ttl_s=6 * 3600,                     # reuse identical answers for 6 hours (per user by default)
)

def answer(user_id: str, question: str) -> str:
    model = pick_model(question, cheap="your-cheap-model", strong="your-strong-model")
    request = {"model": model, "messages": [{"role": "user", "content": question}], "max_tokens": 400}
    try:
        res = shield.run(lambda: client.chat.completions.create(**request), model=model, request=request, user=user_id, feature="support-bot")
        return res.choices[0].message.content
    except BudgetExceededError:
        return "You have reached today's limit. Please try again tomorrow."
    except (RateLimitError, LoopDetectedError):
        return "Please wait a moment and try again."

With async clients (AsyncOpenAI, AsyncAnthropic), use await shield.arun(lambda: client.chat.completions.create(**request), ...).

SDK response objects (pydantic models) are read directly; there is no need to convert them.

How it works

  • Budgets are reserved before the call. The shield adds the worst case (request size plus max_tokens) to every budget at once, then replaces it with the real cost after the call. Twenty requests at the same moment cannot spend more than the budget allows, and a failed call gives its reservation back. The in-memory store is thread-safe; for several workers or servers, pass a store backed by Redis or your database with get, an atomic incr, and optionally get_cache, set_cache and hit.
  • Loop guard: the same request from the same user more than 8 times in 60 seconds raises LoopDetectedError (loop_guard=False turns it off).
  • Cache: per user by default, so one customer never gets an answer made for another. Pass cache_scope="global" for answers that are the same for everyone.
  • Exact costs: read_usage understands OpenAI Chat Completions and Responses, Anthropic (including 5-minute and 1-hour cache writes), Gemini (including thinking tokens, which are billed as output but reported separately), Bedrock Converse, OpenRouter (its reported cost is used) and the Vercel AI SDK. Prices can have cachedInput, cacheWrite, cacheWrite1h, longContext, tiers (batch, flex, priority) and dated entries. See examples/prices.example.json.
  • Streaming: call shield.check(...) before the stream and shield.track(final_usage, model=...) after it.

The analyzer

llm-cost-shield analyze usage.jsonl --prices prices.json --cheap your-cheap-model

It reads JSONL, JSON or CSV logs (or raw provider usage objects) and shows spend by model, feature and user, repeated requests, routing savings, thinking-token share, whether prompt caching saves or loses money, long-context surcharges, likely loops and abnormal users. Full details are in the npm package README.

Sustainable Development Goals

This tool supports SDG targets 12.2 and 7.3 (efficient use of resources, energy efficiency): every cached answer, avoided loop and request moved to a smaller model is inference compute and electricity never used. It also supports target 8.3: a runaway AI bill is a cash-flow shock a small business may not survive, and spending limits make AI features safe to try.

About

Built by Ahmad Zia, who helps e-commerce and SaaS teams cut AI and SaaS costs, and researches energy-efficient AI inference. MIT licensed.

Guide, help and author

Built by Ahmad Zia (Muhammad Ahmad Zia), an AI consultant for ecommerce since 2020 and green AI researcher at the University of Lahore. Research · Google Scholar · ORCID · LinkedIn · GitHub

Metadata

Release files for llm-cost-shield 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for llm-cost-shield 0.1.0
File Size Uploaded Provenance Actions
llm_cost_shield-0.1.0.tar.gz 24.7 kB With provenance Details for llm_cost_shield-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for llm-cost-shield 0.1.0
File Interpreter ABI Platform Actions
llm_cost_shield-0.1.0-py3-none-any.whl Python 3 none any Details for llm_cost_shield-0.1.0-py3-none-any.whl

Total release size: 41.4 kB

Release files / llm_cost_shield-0.1.0.tar.gz

Download URL llm_cost_shield-0.1.0.tar.gz
Size 24.7 kB
Tags Source
SHA-256 checksum
How to use checksums
4417761e730d7117080bf2162b60dd385c1f4dab373df1798d393b298e78a44d
BLAKE2b-256 checksum
How to use checksums
cf628a3816282c06b2c3358af732863ee588290bee26a3b3ad2b54ffef4c29b4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.

Transparency log

Release files / llm_cost_shield-0.1.0-py3-none-any.whl

Download URL llm_cost_shield-0.1.0-py3-none-any.whl
Size 16.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e0e6d57ad8b611ee8cd578c7c4ae9752ffc69c56947a07e7d0dd11d412743c06
BLAKE2b-256 checksum
How to use checksums
576f6dd8519cedbaaf6356d9c3ea77b5324362cac0be8d68ff740a558f94497e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.

Transparency log

Security for llm-cost-shield 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for llm_cost_shield-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page