Skip to main content Switch to mobile version llm-cost-shield 0.1.0 Stop surprise AI bills: per-user and daily budgets reserved before each call, loop guard, rate limits, a per-user response cache and cheap-model routing for OpenAI, Anthropic, Gemini, Bedrock, OpenRouter or any LLM API, with exact cost accounting (thinking tokens, cache writes, long-context and batch prices) and a usage-log analyzer. No dependencies.
pip install llm-cost-shield==0.1.0 Copy PIP instructions
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.
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.
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.
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.
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
Full guide with examples and FAQs: www.ahmadzia.com/tools/llm-cost-shield
Background reading: How to reduce LLM costs: 10 methods ranked by what they save
All 30 free tools and agent skills: ahmadzia.com/tools · ahmadzia.com/skills
Want it set up, fixed or tuned for your store? Book a free call
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
Released: Dec 5, 2026
Author: Muhammad Ahmad Zia
Both files in this release have provenance metadata.
View provenance details
MIT View SPDX License List
ai-cost anthropic bedrock budget cache cost finops gemini green-ai llm openai openrouter rate-limit tokens
Development Status 4 - Beta
Intended Audience Developers
Operating System OS Independent
Programming Language Python :: 3
Topic Scientific/Engineering :: Artificial Intelligence
Software Development :: Libraries
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)
Built distribution (wheel)
Total release size: 41.4 kB
Release files / llm_cost_shield-0.1.0.tar.gz
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.
Release files / llm_cost_shield-0.1.0-py3-none-any.whl
Security for llm-cost-shield 0.1.0
Both files in this release have been uploaded with provenance metadata.
With provenance llm_cost_shield-0.1.0.tar.gz Dec 5, 2026
With provenance llm_cost_shield-0.1.0-py3-none-any.whl Dec 5, 2026
Attestation for llm_cost_shield-0.1.0.tar.gz
Attestation for llm_cost_shield-0.1.0-py3-none-any.whl
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
Dec 5, 2026 2 release files Full provenance
"PyPI", "Python Package Index", and the blocks logos are registered trademarks of the Python Software Foundation.
© 2026 Python Software Foundation
Deployed from 4d99e05











