Metadata-Version: 2.5
Name: llm-cost-shield
Version: 0.1.0
Summary: 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.
Project-URL: Homepage, https://www.ahmadzia.com/tools/llm-cost-shield
Project-URL: Documentation, https://www.ahmadzia.com/tools/llm-cost-shield
Project-URL: Source, https://github.com/MuhammadAhmadZia/llm-cost-shield
Project-URL: Issues, https://github.com/MuhammadAhmadZia/llm-cost-shield/issues
Project-URL: Changelog, https://github.com/MuhammadAhmadZia/llm-cost-shield/blob/main/python/CHANGELOG.md
Project-URL: Author, https://www.ahmadzia.com
Project-URL: Research, https://www.ahmadzia.com/research
Author-email: Muhammad Ahmad Zia <muhammad.zia@cs.uol.edu.pk>
License-Expression: MIT
License-File: LICENSE
Keywords: ai-cost,anthropic,bedrock,budget,cache,cost,finops,gemini,green-ai,llm,openai,openrouter,rate-limit,tokens
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.9
Provides-Extra: test
Requires-Dist: pytest>=7; extra == 'test'
Description-Content-Type: text/markdown

# 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.

```bash
pip install llm-cost-shield
```

This is the Python version of the [npm package](https://www.npmjs.com/package/llm-cost-shield). 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

```python
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

```bash
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](https://www.npmjs.com/package/llm-cost-shield).

## 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](https://www.ahmadzia.com), who helps e-commerce and SaaS teams cut AI and SaaS costs, and researches energy-efficient AI inference. MIT licensed.

<!-- ahmadzia-links -->
## Guide, help and author

- **Full guide with examples and FAQs:** [www.ahmadzia.com/tools/llm-cost-shield](https://www.ahmadzia.com/tools/llm-cost-shield)
- **Background reading:** [How to reduce LLM costs: 10 methods ranked by what they save](https://www.ahmadzia.com/blog/how-to-reduce-llm-costs)
- **All 30 free tools and agent skills:** [ahmadzia.com/tools](https://www.ahmadzia.com/tools) · [ahmadzia.com/skills](https://www.ahmadzia.com/skills)
- **Want it set up, fixed or tuned for your store?** [Book a free call](https://www.ahmadzia.com/contact)

Built by **[Ahmad Zia](https://www.ahmadzia.com)** (Muhammad Ahmad Zia), an AI consultant for ecommerce since 2020 and green AI researcher at the University of Lahore. [Research](https://www.ahmadzia.com/research) · [Google Scholar](https://scholar.google.com/citations?user=sqjdX2EAAAAJ&hl=en) · [ORCID](https://orcid.org/0000-0002-3208-6246) · [LinkedIn](https://www.linkedin.com/in/muhammad-ahmadzia/) · [GitHub](https://github.com/MuhammadAhmadZia)
<!-- /ahmadzia-links -->
