llmprice-kit 2026.4.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,55 @@
1
+ name: Auto-Sync LLM Pricing Data
2
+
3
+ on:
4
+ schedule:
5
+ - cron: "0 6 * * *" # Every day at 6:00 AM UTC
6
+ workflow_dispatch: # Manual trigger
7
+
8
+ permissions:
9
+ contents: write
10
+
11
+ jobs:
12
+ sync-and-release:
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+
17
+ - name: Install uv
18
+ uses: astral-sh/setup-uv@v4
19
+
20
+ - name: Fetch latest pricing data
21
+ run: |
22
+ curl -sL "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json" \
23
+ -o src/llmprice/data/model_prices.json
24
+
25
+ - name: Check for changes
26
+ id: diff
27
+ run: |
28
+ git diff --quiet src/llmprice/data/model_prices.json && echo "changed=false" >> "$GITHUB_OUTPUT" || echo "changed=true" >> "$GITHUB_OUTPUT"
29
+
30
+ - name: Set date-based version
31
+ if: steps.diff.outputs.changed == 'true'
32
+ run: |
33
+ VERSION=$(date -u +"%Y.%-m.%-d")
34
+ sed -i "s/^version = .*/version = \"${VERSION}\"/" pyproject.toml
35
+ echo "VERSION=${VERSION}" >> "$GITHUB_ENV"
36
+
37
+ - name: Commit and tag
38
+ if: steps.diff.outputs.changed == 'true'
39
+ run: |
40
+ git config user.name "github-actions[bot]"
41
+ git config user.email "github-actions[bot]@users.noreply.github.com"
42
+ git add src/llmprice/data/model_prices.json pyproject.toml
43
+ git commit -m "sync: update pricing data ${VERSION}"
44
+ git tag "v${VERSION}"
45
+ git push origin main --tags
46
+
47
+ - name: Build package
48
+ if: steps.diff.outputs.changed == 'true'
49
+ run: uv build
50
+
51
+ - name: Publish to PyPI
52
+ if: steps.diff.outputs.changed == 'true'
53
+ env:
54
+ UV_PUBLISH_TOKEN: ${{ secrets.PYPI_API_TOKEN }}
55
+ run: uv publish
@@ -0,0 +1,10 @@
1
+ # Python-generated files
2
+ __pycache__/
3
+ *.py[oc]
4
+ build/
5
+ dist/
6
+ wheels/
7
+ *.egg-info
8
+
9
+ # Virtual environments
10
+ .venv
@@ -0,0 +1 @@
1
+ 3.13
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nilesh Verma
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,114 @@
1
+ Metadata-Version: 2.4
2
+ Name: llmprice-kit
3
+ Version: 2026.4.2
4
+ Summary: Fast, offline-first LLM pricing lookup with auto-sync from LiteLLM data. Get token costs, context windows, and capabilities for 2500+ models.
5
+ Project-URL: Homepage, https://github.com/TechyNilesh/LLMPrice
6
+ Project-URL: Repository, https://github.com/TechyNilesh/LLMPrice
7
+ Project-URL: Issues, https://github.com/TechyNilesh/LLMPrice/issues
8
+ Author-email: Nilesh Verma <me@nileshverma.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: anthropic,claude,cost,gemini,gpt,llm,openai,pricing,token
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Requires-Python: >=3.9
18
+ Requires-Dist: httpx>=0.24.0
19
+ Description-Content-Type: text/markdown
20
+
21
+ <p align="center">
22
+ <img src="https://raw.githubusercontent.com/TechyNilesh/LLMPrice/main/llmprice_hero.png" alt="LLMPrice Hero" width="100%">
23
+ </p>
24
+
25
+ # LLMPrice
26
+
27
+ [![PyPI version](https://img.shields.io/pypi/v/llmprice-kit)](https://pypi.org/project/llmprice/)
28
+ [![Downloads](https://static.pepy.tech/personalized-badge/llmprice-kit?period=total&units=international_system&left_color=grey&right_color=blue&left_text=downloads)](https://pepy.tech/project/llmprice-kit)
29
+ [![License: MIT](https://img.shields.io/pypi/l/llmprice-kit)](https://github.com/TechyNilesh/LLMPrice/blob/main/LICENSE)
30
+ [![Python](https://img.shields.io/pypi/pyversions/llmprice-kit)](https://pypi.org/project/llmprice/)
31
+ [![Data Source: LiteLLM](https://img.shields.io/badge/data%20source-LiteLLM-blue)](https://github.com/BerriAI/litellm)
32
+ [![Auto Sync](https://img.shields.io/github/actions/workflow/status/TechyNilesh/LLMPrice/auto-sync.yml?label=daily%20sync)](https://github.com/TechyNilesh/LLMPrice/actions/workflows/auto-sync.yml)
33
+
34
+ Fast, offline-first LLM pricing lookup for **2500+ models** across all major providers. Returns both Python objects and JSON.
35
+
36
+ Auto-synced daily from [LiteLLM](https://github.com/BerriAI/litellm) pricing data via GitHub Actions. Date-based versioning (`2026.4.2`).
37
+
38
+ ## Install
39
+
40
+ ```bash
41
+ pip install llmprice-kit
42
+ ```
43
+
44
+ ## Quick Start
45
+
46
+ ```python
47
+ from llmprice import LLMPrice
48
+
49
+ lp = LLMPrice()
50
+
51
+ # Get pricing as Python object
52
+ model = lp.get("gpt-4o")
53
+ print(model.input_cost_per_1m) # 2.5
54
+ print(model.output_cost_per_1m) # 10.0
55
+ print(model.max_input_tokens) # 128000
56
+ print(model.supports_vision) # True
57
+
58
+ # Get as JSON dict
59
+ data = lp.get_json("gpt-4o")
60
+ # {"name": "gpt-4o", "provider": "openai", "input_cost_per_1m": 2.5, ...}
61
+
62
+ # Compare models
63
+ models = lp.compare(["gpt-4o", "claude-opus-4-20250514", "gemini/gemini-2.0-flash"])
64
+ for m in models:
65
+ print(f"{m.name}: ${m.input_cost_per_1m}/1M in, ${m.output_cost_per_1m}/1M out")
66
+
67
+ # Search by capabilities
68
+ cheap_vision = lp.search(supports_vision=True, max_input_price=1.0)
69
+ reasoning = lp.search(supports_reasoning=True, provider="anthropic")
70
+
71
+ # List providers
72
+ lp.providers() # ['anthropic', 'openai', 'gemini', ...]
73
+
74
+ # Auto-update mode (fetches fresh data if >1 day old)
75
+ lp = LLMPrice(auto_update=True)
76
+ ```
77
+
78
+ ## CLI
79
+
80
+ ```bash
81
+ # Get model pricing
82
+ llmprice get gpt-4o
83
+
84
+ # Compare models
85
+ llmprice compare gpt-4o claude-opus-4-20250514
86
+
87
+ # Search with filters
88
+ llmprice search --provider openai --vision
89
+ llmprice search --reasoning --max-input-price 5.0
90
+
91
+ # List providers
92
+ llmprice providers
93
+
94
+ # Update data
95
+ llmprice update
96
+
97
+ # Check data freshness
98
+ llmprice info
99
+ ```
100
+
101
+ ## How It Works
102
+
103
+ - **Bundled data**: Ships with a snapshot of pricing data — works offline, zero latency
104
+ - **Auto-sync**: Optional background refresh from LiteLLM's upstream JSON
105
+ - **Date versioning**: Each release is tagged by date (e.g., `2026.4.2`), so `pip install llmprice-kit==2026.4.2` gives you that exact day's pricing
106
+ - **GitHub Actions**: Runs daily, checks for upstream changes, auto-publishes to PyPI
107
+
108
+ ## Data Source
109
+
110
+ Pricing data sourced from [LiteLLM's model_prices_and_context_window.json](https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json), which covers 2500+ models from 15+ providers including OpenAI, Anthropic, Google, AWS Bedrock, Azure, DeepSeek, Mistral, and more.
111
+
112
+ ## License
113
+
114
+ MIT
@@ -0,0 +1,94 @@
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/TechyNilesh/LLMPrice/main/llmprice_hero.png" alt="LLMPrice Hero" width="100%">
3
+ </p>
4
+
5
+ # LLMPrice
6
+
7
+ [![PyPI version](https://img.shields.io/pypi/v/llmprice-kit)](https://pypi.org/project/llmprice/)
8
+ [![Downloads](https://static.pepy.tech/personalized-badge/llmprice-kit?period=total&units=international_system&left_color=grey&right_color=blue&left_text=downloads)](https://pepy.tech/project/llmprice-kit)
9
+ [![License: MIT](https://img.shields.io/pypi/l/llmprice-kit)](https://github.com/TechyNilesh/LLMPrice/blob/main/LICENSE)
10
+ [![Python](https://img.shields.io/pypi/pyversions/llmprice-kit)](https://pypi.org/project/llmprice/)
11
+ [![Data Source: LiteLLM](https://img.shields.io/badge/data%20source-LiteLLM-blue)](https://github.com/BerriAI/litellm)
12
+ [![Auto Sync](https://img.shields.io/github/actions/workflow/status/TechyNilesh/LLMPrice/auto-sync.yml?label=daily%20sync)](https://github.com/TechyNilesh/LLMPrice/actions/workflows/auto-sync.yml)
13
+
14
+ Fast, offline-first LLM pricing lookup for **2500+ models** across all major providers. Returns both Python objects and JSON.
15
+
16
+ Auto-synced daily from [LiteLLM](https://github.com/BerriAI/litellm) pricing data via GitHub Actions. Date-based versioning (`2026.4.2`).
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ pip install llmprice-kit
22
+ ```
23
+
24
+ ## Quick Start
25
+
26
+ ```python
27
+ from llmprice import LLMPrice
28
+
29
+ lp = LLMPrice()
30
+
31
+ # Get pricing as Python object
32
+ model = lp.get("gpt-4o")
33
+ print(model.input_cost_per_1m) # 2.5
34
+ print(model.output_cost_per_1m) # 10.0
35
+ print(model.max_input_tokens) # 128000
36
+ print(model.supports_vision) # True
37
+
38
+ # Get as JSON dict
39
+ data = lp.get_json("gpt-4o")
40
+ # {"name": "gpt-4o", "provider": "openai", "input_cost_per_1m": 2.5, ...}
41
+
42
+ # Compare models
43
+ models = lp.compare(["gpt-4o", "claude-opus-4-20250514", "gemini/gemini-2.0-flash"])
44
+ for m in models:
45
+ print(f"{m.name}: ${m.input_cost_per_1m}/1M in, ${m.output_cost_per_1m}/1M out")
46
+
47
+ # Search by capabilities
48
+ cheap_vision = lp.search(supports_vision=True, max_input_price=1.0)
49
+ reasoning = lp.search(supports_reasoning=True, provider="anthropic")
50
+
51
+ # List providers
52
+ lp.providers() # ['anthropic', 'openai', 'gemini', ...]
53
+
54
+ # Auto-update mode (fetches fresh data if >1 day old)
55
+ lp = LLMPrice(auto_update=True)
56
+ ```
57
+
58
+ ## CLI
59
+
60
+ ```bash
61
+ # Get model pricing
62
+ llmprice get gpt-4o
63
+
64
+ # Compare models
65
+ llmprice compare gpt-4o claude-opus-4-20250514
66
+
67
+ # Search with filters
68
+ llmprice search --provider openai --vision
69
+ llmprice search --reasoning --max-input-price 5.0
70
+
71
+ # List providers
72
+ llmprice providers
73
+
74
+ # Update data
75
+ llmprice update
76
+
77
+ # Check data freshness
78
+ llmprice info
79
+ ```
80
+
81
+ ## How It Works
82
+
83
+ - **Bundled data**: Ships with a snapshot of pricing data — works offline, zero latency
84
+ - **Auto-sync**: Optional background refresh from LiteLLM's upstream JSON
85
+ - **Date versioning**: Each release is tagged by date (e.g., `2026.4.2`), so `pip install llmprice-kit==2026.4.2` gives you that exact day's pricing
86
+ - **GitHub Actions**: Runs daily, checks for upstream changes, auto-publishes to PyPI
87
+
88
+ ## Data Source
89
+
90
+ Pricing data sourced from [LiteLLM's model_prices_and_context_window.json](https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json), which covers 2500+ models from 15+ providers including OpenAI, Anthropic, Google, AWS Bedrock, Azure, DeepSeek, Mistral, and more.
91
+
92
+ ## License
93
+
94
+ MIT
Binary file
@@ -0,0 +1,36 @@
1
+ [project]
2
+ name = "llmprice-kit"
3
+ version = "2026.4.2"
4
+ description = "Fast, offline-first LLM pricing lookup with auto-sync from LiteLLM data. Get token costs, context windows, and capabilities for 2500+ models."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ authors = [
8
+ { name = "Nilesh Verma", email = "me@nileshverma.com" }
9
+ ]
10
+ requires-python = ">=3.9"
11
+ dependencies = [
12
+ "httpx>=0.24.0",
13
+ ]
14
+ keywords = ["llm", "pricing", "openai", "anthropic", "gemini", "token", "cost", "gpt", "claude"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Programming Language :: Python :: 3",
20
+ "Topic :: Software Development :: Libraries :: Python Modules",
21
+ ]
22
+
23
+ [project.urls]
24
+ Homepage = "https://github.com/TechyNilesh/LLMPrice"
25
+ Repository = "https://github.com/TechyNilesh/LLMPrice"
26
+ Issues = "https://github.com/TechyNilesh/LLMPrice/issues"
27
+
28
+ [project.scripts]
29
+ llmprice = "llmprice.cli:main"
30
+
31
+ [build-system]
32
+ requires = ["hatchling"]
33
+ build-backend = "hatchling.build"
34
+
35
+ [tool.hatch.build.targets.wheel]
36
+ packages = ["src/llmprice"]
@@ -0,0 +1,6 @@
1
+ """LLMPrice — Fast, offline-first LLM pricing lookup for 2500+ models."""
2
+
3
+ from .core import LLMPrice
4
+ from .models import ModelPrice
5
+
6
+ __all__ = ["LLMPrice", "ModelPrice"]
@@ -0,0 +1,94 @@
1
+ """CLI for llmprice — lookup LLM pricing from the terminal."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+
9
+ from .core import LLMPrice
10
+
11
+
12
+ def main() -> None:
13
+ parser = argparse.ArgumentParser(
14
+ prog="llmprice",
15
+ description="Fast LLM pricing lookup for 2500+ models.",
16
+ )
17
+ sub = parser.add_subparsers(dest="command")
18
+
19
+ # llmprice get <model>
20
+ get_p = sub.add_parser("get", help="Get pricing for a model")
21
+ get_p.add_argument("model", help="Model name (e.g., gpt-4o)")
22
+
23
+ # llmprice compare <model1> <model2> ...
24
+ cmp_p = sub.add_parser("compare", help="Compare models side by side")
25
+ cmp_p.add_argument("models", nargs="+", help="Model names to compare")
26
+
27
+ # llmprice search --provider openai --vision
28
+ search_p = sub.add_parser("search", help="Search models by filters")
29
+ search_p.add_argument("--provider", help="Filter by provider")
30
+ search_p.add_argument("--mode", help="Filter by mode (chat, embedding, etc.)")
31
+ search_p.add_argument("--vision", action="store_true", help="Supports vision")
32
+ search_p.add_argument("--reasoning", action="store_true", help="Supports reasoning")
33
+ search_p.add_argument("--max-input-price", type=float, help="Max input price per 1M tokens")
34
+ search_p.add_argument("--limit", type=int, default=20, help="Max results (default: 20)")
35
+
36
+ # llmprice providers
37
+ sub.add_parser("providers", help="List all providers")
38
+
39
+ # llmprice update
40
+ sub.add_parser("update", help="Fetch latest pricing data")
41
+
42
+ # llmprice info
43
+ sub.add_parser("info", help="Show data age and stats")
44
+
45
+ args = parser.parse_args()
46
+
47
+ if not args.command:
48
+ parser.print_help()
49
+ return
50
+
51
+ lp = LLMPrice()
52
+
53
+ if args.command == "get":
54
+ try:
55
+ result = lp.get_json(args.model)
56
+ print(json.dumps(result, indent=2))
57
+ except KeyError as e:
58
+ print(str(e), file=sys.stderr)
59
+ sys.exit(1)
60
+
61
+ elif args.command == "compare":
62
+ try:
63
+ results = lp.compare_json(args.models)
64
+ print(json.dumps(results, indent=2))
65
+ except KeyError as e:
66
+ print(str(e), file=sys.stderr)
67
+ sys.exit(1)
68
+
69
+ elif args.command == "search":
70
+ results = lp.search(
71
+ provider=args.provider,
72
+ mode=args.mode,
73
+ supports_vision=True if args.vision else None,
74
+ supports_reasoning=True if args.reasoning else None,
75
+ max_input_price=args.max_input_price,
76
+ )
77
+ for m in results[: args.limit]:
78
+ print(f"{m.name:50s} ${m.input_cost_per_1m:>8.2f} / ${m.output_cost_per_1m:>8.2f} [{m.provider}]")
79
+ print(f"\n{len(results)} models found (showing {min(len(results), args.limit)})")
80
+
81
+ elif args.command == "providers":
82
+ for p in lp.providers():
83
+ count = len(lp.by_provider(p))
84
+ print(f"{p:30s} {count:>4} models")
85
+
86
+ elif args.command == "update":
87
+ print("Fetching latest pricing data...")
88
+ lp.update()
89
+ print(f"Done. {lp.total_models} models loaded.")
90
+
91
+ elif args.command == "info":
92
+ print(f"Total models: {lp.total_models}")
93
+ print(f"Providers: {len(lp.providers())}")
94
+ print(f"{lp.data_age()}")
@@ -0,0 +1,208 @@
1
+ """Core LLMPrice class — offline-first pricing lookup with optional auto-sync."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import time
8
+ from datetime import datetime, timezone
9
+ from pathlib import Path
10
+ from typing import Any, Optional
11
+
12
+ from .models import ModelPrice
13
+
14
+ _BUNDLED_DATA = Path(__file__).parent / "data" / "model_prices.json"
15
+ _CACHE_DIR = Path(os.environ.get("LLMPRICE_CACHE_DIR", Path.home() / ".cache" / "llmprice"))
16
+ _CACHED_DATA = _CACHE_DIR / "model_prices.json"
17
+ _REMOTE_URL = (
18
+ os.environ.get("LLMPRICE_DATA_URL")
19
+ or "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"
20
+ )
21
+ _STALE_SECONDS = 86400 # 1 day
22
+
23
+
24
+ class LLMPrice:
25
+ """Fast, offline-first LLM pricing lookup.
26
+
27
+ Args:
28
+ auto_update: If True, fetches fresh data when local copy is stale (>1 day).
29
+ data_path: Override the data file path. Uses bundled data by default.
30
+ """
31
+
32
+ def __init__(self, auto_update: bool = False, data_path: Optional[str] = None) -> None:
33
+ self._auto_update = auto_update
34
+ self._data_path = Path(data_path) if data_path else None
35
+ self._raw: dict[str, Any] = {}
36
+ self._models: dict[str, ModelPrice] = {}
37
+ self._load()
38
+
39
+ def _resolve_data_file(self) -> Path:
40
+ """Determine which data file to load."""
41
+ if self._data_path and self._data_path.exists():
42
+ return self._data_path
43
+ if _CACHED_DATA.exists():
44
+ return _CACHED_DATA
45
+ return _BUNDLED_DATA
46
+
47
+ def _load(self) -> None:
48
+ """Load model data from the best available source."""
49
+ if self._auto_update and self._is_stale():
50
+ try:
51
+ self.update()
52
+ except Exception:
53
+ pass # fall back to local data
54
+
55
+ path = self._resolve_data_file()
56
+ with open(path, "r") as f:
57
+ self._raw = json.load(f)
58
+
59
+ self._models = {}
60
+ for key, val in self._raw.items():
61
+ if key == "sample_spec" or not isinstance(val, dict):
62
+ continue
63
+ self._models[key] = ModelPrice.from_litellm(key, val)
64
+
65
+ def _is_stale(self) -> bool:
66
+ """Check if local data is older than the stale threshold."""
67
+ path = self._resolve_data_file()
68
+ if not path.exists():
69
+ return True
70
+ age = time.time() - path.stat().st_mtime
71
+ return age > _STALE_SECONDS
72
+
73
+ def update(self) -> None:
74
+ """Fetch the latest pricing data from upstream."""
75
+ import httpx
76
+
77
+ _CACHE_DIR.mkdir(parents=True, exist_ok=True)
78
+ resp = httpx.get(_REMOTE_URL, timeout=30, follow_redirects=True)
79
+ resp.raise_for_status()
80
+ _CACHED_DATA.write_bytes(resp.content)
81
+ self._load_from_path(_CACHED_DATA)
82
+
83
+ def _load_from_path(self, path: Path) -> None:
84
+ """Reload data from a specific path."""
85
+ with open(path, "r") as f:
86
+ self._raw = json.load(f)
87
+ self._models = {}
88
+ for key, val in self._raw.items():
89
+ if key == "sample_spec" or not isinstance(val, dict):
90
+ continue
91
+ self._models[key] = ModelPrice.from_litellm(key, val)
92
+
93
+ # --- Query methods ---
94
+
95
+ def get(self, model: str) -> ModelPrice:
96
+ """Get pricing info for a specific model.
97
+
98
+ Args:
99
+ model: Model name (e.g., 'gpt-4o', 'claude-opus-4-20250514').
100
+
101
+ Returns:
102
+ ModelPrice object with pricing and capability data.
103
+
104
+ Raises:
105
+ KeyError: If model is not found.
106
+ """
107
+ if model in self._models:
108
+ return self._models[model]
109
+ # Fuzzy: try partial match
110
+ matches = [k for k in self._models if model.lower() in k.lower()]
111
+ if len(matches) == 1:
112
+ return self._models[matches[0]]
113
+ if matches:
114
+ raise KeyError(
115
+ f"Model '{model}' not found. Did you mean: {matches[:5]}"
116
+ )
117
+ raise KeyError(f"Model '{model}' not found.")
118
+
119
+ def get_json(self, model: str) -> dict[str, Any]:
120
+ """Get pricing info as a JSON-serializable dict."""
121
+ return self.get(model).to_dict()
122
+
123
+ def compare(self, models: list[str]) -> list[ModelPrice]:
124
+ """Compare multiple models side by side.
125
+
126
+ Returns:
127
+ List of ModelPrice objects.
128
+ """
129
+ return [self.get(m) for m in models]
130
+
131
+ def compare_json(self, models: list[str]) -> list[dict[str, Any]]:
132
+ """Compare multiple models, return as list of dicts."""
133
+ return [self.get(m).to_dict() for m in models]
134
+
135
+ def by_provider(self, provider: str) -> list[ModelPrice]:
136
+ """Get all models from a specific provider.
137
+
138
+ Args:
139
+ provider: Provider name (e.g., 'openai', 'anthropic', 'gemini').
140
+ """
141
+ return [
142
+ m for m in self._models.values()
143
+ if m.provider.lower() == provider.lower()
144
+ ]
145
+
146
+ def search(
147
+ self,
148
+ provider: Optional[str] = None,
149
+ mode: Optional[str] = None,
150
+ supports_vision: Optional[bool] = None,
151
+ supports_function_calling: Optional[bool] = None,
152
+ supports_reasoning: Optional[bool] = None,
153
+ max_input_price: Optional[float] = None,
154
+ max_output_price: Optional[float] = None,
155
+ min_context: Optional[int] = None,
156
+ ) -> list[ModelPrice]:
157
+ """Search models by capabilities and price filters.
158
+
159
+ All prices are per 1M tokens. Context is in tokens.
160
+ """
161
+ results = list(self._models.values())
162
+
163
+ if provider:
164
+ results = [m for m in results if m.provider.lower() == provider.lower()]
165
+ if mode:
166
+ results = [m for m in results if m.mode == mode]
167
+ if supports_vision is not None:
168
+ results = [m for m in results if m.supports_vision == supports_vision]
169
+ if supports_function_calling is not None:
170
+ results = [m for m in results if m.supports_function_calling == supports_function_calling]
171
+ if supports_reasoning is not None:
172
+ results = [m for m in results if m.supports_reasoning == supports_reasoning]
173
+ if max_input_price is not None:
174
+ results = [m for m in results if 0 < m.input_cost_per_1m <= max_input_price]
175
+ if max_output_price is not None:
176
+ results = [m for m in results if 0 < m.output_cost_per_1m <= max_output_price]
177
+ if min_context is not None:
178
+ results = [m for m in results if m.max_input_tokens >= min_context]
179
+
180
+ return results
181
+
182
+ def providers(self) -> list[str]:
183
+ """List all available providers."""
184
+ return sorted(set(m.provider for m in self._models.values() if m.provider))
185
+
186
+ def all_models(self) -> list[str]:
187
+ """List all model names."""
188
+ return list(self._models.keys())
189
+
190
+ def data_age(self) -> str:
191
+ """Return human-readable age of the local data."""
192
+ path = self._resolve_data_file()
193
+ if not path.exists():
194
+ return "No data file found."
195
+ age_seconds = time.time() - path.stat().st_mtime
196
+ days = int(age_seconds // 86400)
197
+ hours = int((age_seconds % 86400) // 3600)
198
+ if days > 0:
199
+ return f"Data is {days}d {hours}h old."
200
+ return f"Data is {hours}h old."
201
+
202
+ @property
203
+ def total_models(self) -> int:
204
+ """Total number of models in the dataset."""
205
+ return len(self._models)
206
+
207
+ def __repr__(self) -> str:
208
+ return f"LLMPrice(models={self.total_models}, auto_update={self._auto_update})"
File without changes