llm-tokencost 0.3.0__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.
- llm_tokencost-0.3.0/LICENSE +21 -0
- llm_tokencost-0.3.0/PKG-INFO +203 -0
- llm_tokencost-0.3.0/README.md +175 -0
- llm_tokencost-0.3.0/pyproject.toml +53 -0
- llm_tokencost-0.3.0/setup.cfg +4 -0
- llm_tokencost-0.3.0/src/llm_tokencost.egg-info/PKG-INFO +203 -0
- llm_tokencost-0.3.0/src/llm_tokencost.egg-info/SOURCES.txt +13 -0
- llm_tokencost-0.3.0/src/llm_tokencost.egg-info/dependency_links.txt +1 -0
- llm_tokencost-0.3.0/src/llm_tokencost.egg-info/requires.txt +6 -0
- llm_tokencost-0.3.0/src/llm_tokencost.egg-info/top_level.txt +1 -0
- llm_tokencost-0.3.0/src/tokencost/__init__.py +7 -0
- llm_tokencost-0.3.0/src/tokencost/exceptions.py +17 -0
- llm_tokencost-0.3.0/src/tokencost/py.typed +0 -0
- llm_tokencost-0.3.0/src/tokencost/tracker.py +262 -0
- llm_tokencost-0.3.0/tests/test_tracker.py +490 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026
|
|
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,203 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: llm-tokencost
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: A lightweight Python library for tracking LLM API costs via litellm's callback system
|
|
5
|
+
Author-email: Paawan Purdhani <paawanpurdhani@gmail.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Paawan13/tokencost
|
|
8
|
+
Project-URL: Repository, https://github.com/Paawan13/tokencost
|
|
9
|
+
Project-URL: Bug Tracker, https://github.com/Paawan13/tokencost/issues
|
|
10
|
+
Keywords: llm,cost,tracking,token,budget,openai,anthropic,litellm
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
19
|
+
Requires-Python: >=3.9
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: litellm>=1.0.0
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: pytest>=7.0.0; extra == "dev"
|
|
25
|
+
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
|
|
26
|
+
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# tokencost
|
|
30
|
+
|
|
31
|
+
A lightweight Python library for tracking LLM API costs via litellm's callback system, with budget alerts and spending limits.
|
|
32
|
+
|
|
33
|
+
## Installation
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install tokencost
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Quick Start
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
import litellm
|
|
43
|
+
from tokencost import CostTracker, BudgetExceededError
|
|
44
|
+
|
|
45
|
+
# Create a tracker with a $5 budget
|
|
46
|
+
def alert(tracker):
|
|
47
|
+
print(f"Budget exceeded! Spent ${tracker.total_cost:.2f}")
|
|
48
|
+
|
|
49
|
+
tracker = CostTracker(
|
|
50
|
+
budget=5.00,
|
|
51
|
+
on_budget_exceeded=alert,
|
|
52
|
+
raise_on_budget=True
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
# Register with litellm
|
|
56
|
+
litellm.callbacks = [tracker]
|
|
57
|
+
|
|
58
|
+
# Make LLM calls as usual
|
|
59
|
+
try:
|
|
60
|
+
response = litellm.completion(
|
|
61
|
+
model="gpt-4",
|
|
62
|
+
messages=[{"role": "user", "content": "Hello!"}]
|
|
63
|
+
)
|
|
64
|
+
except BudgetExceededError as e:
|
|
65
|
+
print(f"Stopped at ${e.total_cost:.2f} (budget: ${e.budget:.2f})")
|
|
66
|
+
|
|
67
|
+
# Check usage
|
|
68
|
+
print(f"Total: ${tracker.total_cost:.4f} across {tracker.request_count} requests")
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Features
|
|
72
|
+
|
|
73
|
+
- **Real-time cost tracking** during LLM calls
|
|
74
|
+
- **Budget alerts** via callback and/or exception
|
|
75
|
+
- **Async support** for `litellm.acompletion()`
|
|
76
|
+
- **Per-model cost aggregation** via `cost_by_model` property
|
|
77
|
+
- **Automatic exit summary** — prints cost report when program ends
|
|
78
|
+
- **Thread-safe** for concurrent usage
|
|
79
|
+
- **Uses litellm's pricing data** for accurate costs (1600+ models)
|
|
80
|
+
|
|
81
|
+
## Async Support
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
import asyncio
|
|
85
|
+
import litellm
|
|
86
|
+
from tokencost import CostTracker
|
|
87
|
+
|
|
88
|
+
async def main():
|
|
89
|
+
tracker = CostTracker()
|
|
90
|
+
litellm.callbacks = [tracker]
|
|
91
|
+
|
|
92
|
+
# Works with async completions
|
|
93
|
+
response = await litellm.acompletion(
|
|
94
|
+
model="gpt-4",
|
|
95
|
+
messages=[{"role": "user", "content": "Hello!"}]
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
print(f"Cost: ${tracker.total_cost:.6f}")
|
|
99
|
+
|
|
100
|
+
asyncio.run(main())
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Per-Model Cost Breakdown
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
tracker = CostTracker()
|
|
107
|
+
litellm.callbacks = [tracker]
|
|
108
|
+
|
|
109
|
+
# Make calls to different models...
|
|
110
|
+
litellm.completion(model="gpt-4", messages=[...])
|
|
111
|
+
litellm.completion(model="gpt-3.5-turbo", messages=[...])
|
|
112
|
+
litellm.completion(model="claude-3-sonnet", messages=[...])
|
|
113
|
+
|
|
114
|
+
# Get cost breakdown by model
|
|
115
|
+
for model, cost in tracker.cost_by_model.items():
|
|
116
|
+
print(f"{model}: ${cost:.6f}")
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
## API Reference
|
|
120
|
+
|
|
121
|
+
### CostTracker
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
CostTracker(
|
|
125
|
+
budget: float | None = None, # Spending limit in USD
|
|
126
|
+
on_budget_exceeded: Callable | None = None, # Callback when exceeded
|
|
127
|
+
raise_on_budget: bool = False, # Raise exception when exceeded
|
|
128
|
+
print_summary: bool = True # Print summary on program exit
|
|
129
|
+
)
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
**Properties:**
|
|
133
|
+
|
|
134
|
+
- `total_cost: float` — Running total in USD
|
|
135
|
+
- `request_count: int` — Number of successful requests
|
|
136
|
+
- `history: list[dict]` — All logged requests
|
|
137
|
+
- `budget: float | None` — Configured budget
|
|
138
|
+
- `budget_exceeded: bool` — Whether budget has been exceeded
|
|
139
|
+
- `cost_by_model: dict[str, float]` — Cost aggregated by model name
|
|
140
|
+
|
|
141
|
+
**Methods:**
|
|
142
|
+
|
|
143
|
+
- `reset()` — Clear all tracked data
|
|
144
|
+
|
|
145
|
+
### BudgetExceededError
|
|
146
|
+
|
|
147
|
+
Raised when budget is exceeded (if `raise_on_budget=True`).
|
|
148
|
+
|
|
149
|
+
```python
|
|
150
|
+
class BudgetExceededError(Exception):
|
|
151
|
+
budget: float # Configured budget
|
|
152
|
+
total_cost: float # Actual spend when exceeded
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
## Exit Summary
|
|
156
|
+
|
|
157
|
+
When your program ends, a cost summary is automatically printed:
|
|
158
|
+
|
|
159
|
+
```
|
|
160
|
+
==================================================
|
|
161
|
+
LLM COST SUMMARY
|
|
162
|
+
==================================================
|
|
163
|
+
Total Cost: $0.001959
|
|
164
|
+
Total Requests: 4
|
|
165
|
+
Budget: $0.0100 (OK)
|
|
166
|
+
Remaining: $0.008041
|
|
167
|
+
--------------------------------------------------
|
|
168
|
+
Requests:
|
|
169
|
+
1. gpt-4: 7+18 tokens = $0.000750
|
|
170
|
+
2. gpt-4: 13+17 tokens = $0.000900
|
|
171
|
+
3. gpt-3.5-turbo: 8+82 tokens = $0.000166
|
|
172
|
+
4. gpt-3.5-turbo: 10+58 tokens = $0.000143
|
|
173
|
+
==================================================
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
Disable with `print_summary=False`.
|
|
177
|
+
|
|
178
|
+
## History Entry Format
|
|
179
|
+
|
|
180
|
+
Each request is logged with:
|
|
181
|
+
|
|
182
|
+
```python
|
|
183
|
+
{
|
|
184
|
+
"model": "gpt-4",
|
|
185
|
+
"prompt_tokens": 150,
|
|
186
|
+
"completion_tokens": 50,
|
|
187
|
+
"cost": 0.0123,
|
|
188
|
+
"timestamp": "2026-02-22T10:30:00Z"
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
## Development
|
|
193
|
+
|
|
194
|
+
```bash
|
|
195
|
+
git clone https://github.com/Paawan13/tokencost.git
|
|
196
|
+
cd tokencost
|
|
197
|
+
pip install -e ".[dev]"
|
|
198
|
+
pytest
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
## License
|
|
202
|
+
|
|
203
|
+
MIT
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
# tokencost
|
|
2
|
+
|
|
3
|
+
A lightweight Python library for tracking LLM API costs via litellm's callback system, with budget alerts and spending limits.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install tokencost
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick Start
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
import litellm
|
|
15
|
+
from tokencost import CostTracker, BudgetExceededError
|
|
16
|
+
|
|
17
|
+
# Create a tracker with a $5 budget
|
|
18
|
+
def alert(tracker):
|
|
19
|
+
print(f"Budget exceeded! Spent ${tracker.total_cost:.2f}")
|
|
20
|
+
|
|
21
|
+
tracker = CostTracker(
|
|
22
|
+
budget=5.00,
|
|
23
|
+
on_budget_exceeded=alert,
|
|
24
|
+
raise_on_budget=True
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
# Register with litellm
|
|
28
|
+
litellm.callbacks = [tracker]
|
|
29
|
+
|
|
30
|
+
# Make LLM calls as usual
|
|
31
|
+
try:
|
|
32
|
+
response = litellm.completion(
|
|
33
|
+
model="gpt-4",
|
|
34
|
+
messages=[{"role": "user", "content": "Hello!"}]
|
|
35
|
+
)
|
|
36
|
+
except BudgetExceededError as e:
|
|
37
|
+
print(f"Stopped at ${e.total_cost:.2f} (budget: ${e.budget:.2f})")
|
|
38
|
+
|
|
39
|
+
# Check usage
|
|
40
|
+
print(f"Total: ${tracker.total_cost:.4f} across {tracker.request_count} requests")
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Features
|
|
44
|
+
|
|
45
|
+
- **Real-time cost tracking** during LLM calls
|
|
46
|
+
- **Budget alerts** via callback and/or exception
|
|
47
|
+
- **Async support** for `litellm.acompletion()`
|
|
48
|
+
- **Per-model cost aggregation** via `cost_by_model` property
|
|
49
|
+
- **Automatic exit summary** — prints cost report when program ends
|
|
50
|
+
- **Thread-safe** for concurrent usage
|
|
51
|
+
- **Uses litellm's pricing data** for accurate costs (1600+ models)
|
|
52
|
+
|
|
53
|
+
## Async Support
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
import asyncio
|
|
57
|
+
import litellm
|
|
58
|
+
from tokencost import CostTracker
|
|
59
|
+
|
|
60
|
+
async def main():
|
|
61
|
+
tracker = CostTracker()
|
|
62
|
+
litellm.callbacks = [tracker]
|
|
63
|
+
|
|
64
|
+
# Works with async completions
|
|
65
|
+
response = await litellm.acompletion(
|
|
66
|
+
model="gpt-4",
|
|
67
|
+
messages=[{"role": "user", "content": "Hello!"}]
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
print(f"Cost: ${tracker.total_cost:.6f}")
|
|
71
|
+
|
|
72
|
+
asyncio.run(main())
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Per-Model Cost Breakdown
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
tracker = CostTracker()
|
|
79
|
+
litellm.callbacks = [tracker]
|
|
80
|
+
|
|
81
|
+
# Make calls to different models...
|
|
82
|
+
litellm.completion(model="gpt-4", messages=[...])
|
|
83
|
+
litellm.completion(model="gpt-3.5-turbo", messages=[...])
|
|
84
|
+
litellm.completion(model="claude-3-sonnet", messages=[...])
|
|
85
|
+
|
|
86
|
+
# Get cost breakdown by model
|
|
87
|
+
for model, cost in tracker.cost_by_model.items():
|
|
88
|
+
print(f"{model}: ${cost:.6f}")
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## API Reference
|
|
92
|
+
|
|
93
|
+
### CostTracker
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
CostTracker(
|
|
97
|
+
budget: float | None = None, # Spending limit in USD
|
|
98
|
+
on_budget_exceeded: Callable | None = None, # Callback when exceeded
|
|
99
|
+
raise_on_budget: bool = False, # Raise exception when exceeded
|
|
100
|
+
print_summary: bool = True # Print summary on program exit
|
|
101
|
+
)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
**Properties:**
|
|
105
|
+
|
|
106
|
+
- `total_cost: float` — Running total in USD
|
|
107
|
+
- `request_count: int` — Number of successful requests
|
|
108
|
+
- `history: list[dict]` — All logged requests
|
|
109
|
+
- `budget: float | None` — Configured budget
|
|
110
|
+
- `budget_exceeded: bool` — Whether budget has been exceeded
|
|
111
|
+
- `cost_by_model: dict[str, float]` — Cost aggregated by model name
|
|
112
|
+
|
|
113
|
+
**Methods:**
|
|
114
|
+
|
|
115
|
+
- `reset()` — Clear all tracked data
|
|
116
|
+
|
|
117
|
+
### BudgetExceededError
|
|
118
|
+
|
|
119
|
+
Raised when budget is exceeded (if `raise_on_budget=True`).
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
class BudgetExceededError(Exception):
|
|
123
|
+
budget: float # Configured budget
|
|
124
|
+
total_cost: float # Actual spend when exceeded
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## Exit Summary
|
|
128
|
+
|
|
129
|
+
When your program ends, a cost summary is automatically printed:
|
|
130
|
+
|
|
131
|
+
```
|
|
132
|
+
==================================================
|
|
133
|
+
LLM COST SUMMARY
|
|
134
|
+
==================================================
|
|
135
|
+
Total Cost: $0.001959
|
|
136
|
+
Total Requests: 4
|
|
137
|
+
Budget: $0.0100 (OK)
|
|
138
|
+
Remaining: $0.008041
|
|
139
|
+
--------------------------------------------------
|
|
140
|
+
Requests:
|
|
141
|
+
1. gpt-4: 7+18 tokens = $0.000750
|
|
142
|
+
2. gpt-4: 13+17 tokens = $0.000900
|
|
143
|
+
3. gpt-3.5-turbo: 8+82 tokens = $0.000166
|
|
144
|
+
4. gpt-3.5-turbo: 10+58 tokens = $0.000143
|
|
145
|
+
==================================================
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Disable with `print_summary=False`.
|
|
149
|
+
|
|
150
|
+
## History Entry Format
|
|
151
|
+
|
|
152
|
+
Each request is logged with:
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
{
|
|
156
|
+
"model": "gpt-4",
|
|
157
|
+
"prompt_tokens": 150,
|
|
158
|
+
"completion_tokens": 50,
|
|
159
|
+
"cost": 0.0123,
|
|
160
|
+
"timestamp": "2026-02-22T10:30:00Z"
|
|
161
|
+
}
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
## Development
|
|
165
|
+
|
|
166
|
+
```bash
|
|
167
|
+
git clone https://github.com/Paawan13/tokencost.git
|
|
168
|
+
cd tokencost
|
|
169
|
+
pip install -e ".[dev]"
|
|
170
|
+
pytest
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
## License
|
|
174
|
+
|
|
175
|
+
MIT
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "llm-tokencost"
|
|
7
|
+
version = "0.3.0"
|
|
8
|
+
description = "A lightweight Python library for tracking LLM API costs via litellm's callback system"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [
|
|
13
|
+
{name = "Paawan Purdhani", email = "paawanpurdhani@gmail.com"},
|
|
14
|
+
]
|
|
15
|
+
keywords = ["llm", "cost", "tracking", "token", "budget", "openai", "anthropic", "litellm"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 4 - Beta",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3.9",
|
|
21
|
+
"Programming Language :: Python :: 3.10",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
dependencies = [
|
|
28
|
+
"litellm>=1.0.0",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.optional-dependencies]
|
|
32
|
+
dev = [
|
|
33
|
+
"pytest>=7.0.0",
|
|
34
|
+
"pytest-cov>=4.0.0",
|
|
35
|
+
"pytest-asyncio>=0.21.0",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
[project.urls]
|
|
39
|
+
Homepage = "https://github.com/Paawan13/tokencost"
|
|
40
|
+
Repository = "https://github.com/Paawan13/tokencost"
|
|
41
|
+
"Bug Tracker" = "https://github.com/Paawan13/tokencost/issues"
|
|
42
|
+
|
|
43
|
+
[tool.setuptools]
|
|
44
|
+
package-dir = {"" = "src"}
|
|
45
|
+
|
|
46
|
+
[tool.setuptools.packages.find]
|
|
47
|
+
where = ["src"]
|
|
48
|
+
include = ["tokencost*"]
|
|
49
|
+
|
|
50
|
+
[tool.pytest.ini_options]
|
|
51
|
+
testpaths = ["tests"]
|
|
52
|
+
python_files = ["test_*.py"]
|
|
53
|
+
asyncio_mode = "auto"
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: llm-tokencost
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: A lightweight Python library for tracking LLM API costs via litellm's callback system
|
|
5
|
+
Author-email: Paawan Purdhani <paawanpurdhani@gmail.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Paawan13/tokencost
|
|
8
|
+
Project-URL: Repository, https://github.com/Paawan13/tokencost
|
|
9
|
+
Project-URL: Bug Tracker, https://github.com/Paawan13/tokencost/issues
|
|
10
|
+
Keywords: llm,cost,tracking,token,budget,openai,anthropic,litellm
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
19
|
+
Requires-Python: >=3.9
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: litellm>=1.0.0
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: pytest>=7.0.0; extra == "dev"
|
|
25
|
+
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
|
|
26
|
+
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# tokencost
|
|
30
|
+
|
|
31
|
+
A lightweight Python library for tracking LLM API costs via litellm's callback system, with budget alerts and spending limits.
|
|
32
|
+
|
|
33
|
+
## Installation
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install tokencost
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Quick Start
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
import litellm
|
|
43
|
+
from tokencost import CostTracker, BudgetExceededError
|
|
44
|
+
|
|
45
|
+
# Create a tracker with a $5 budget
|
|
46
|
+
def alert(tracker):
|
|
47
|
+
print(f"Budget exceeded! Spent ${tracker.total_cost:.2f}")
|
|
48
|
+
|
|
49
|
+
tracker = CostTracker(
|
|
50
|
+
budget=5.00,
|
|
51
|
+
on_budget_exceeded=alert,
|
|
52
|
+
raise_on_budget=True
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
# Register with litellm
|
|
56
|
+
litellm.callbacks = [tracker]
|
|
57
|
+
|
|
58
|
+
# Make LLM calls as usual
|
|
59
|
+
try:
|
|
60
|
+
response = litellm.completion(
|
|
61
|
+
model="gpt-4",
|
|
62
|
+
messages=[{"role": "user", "content": "Hello!"}]
|
|
63
|
+
)
|
|
64
|
+
except BudgetExceededError as e:
|
|
65
|
+
print(f"Stopped at ${e.total_cost:.2f} (budget: ${e.budget:.2f})")
|
|
66
|
+
|
|
67
|
+
# Check usage
|
|
68
|
+
print(f"Total: ${tracker.total_cost:.4f} across {tracker.request_count} requests")
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Features
|
|
72
|
+
|
|
73
|
+
- **Real-time cost tracking** during LLM calls
|
|
74
|
+
- **Budget alerts** via callback and/or exception
|
|
75
|
+
- **Async support** for `litellm.acompletion()`
|
|
76
|
+
- **Per-model cost aggregation** via `cost_by_model` property
|
|
77
|
+
- **Automatic exit summary** — prints cost report when program ends
|
|
78
|
+
- **Thread-safe** for concurrent usage
|
|
79
|
+
- **Uses litellm's pricing data** for accurate costs (1600+ models)
|
|
80
|
+
|
|
81
|
+
## Async Support
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
import asyncio
|
|
85
|
+
import litellm
|
|
86
|
+
from tokencost import CostTracker
|
|
87
|
+
|
|
88
|
+
async def main():
|
|
89
|
+
tracker = CostTracker()
|
|
90
|
+
litellm.callbacks = [tracker]
|
|
91
|
+
|
|
92
|
+
# Works with async completions
|
|
93
|
+
response = await litellm.acompletion(
|
|
94
|
+
model="gpt-4",
|
|
95
|
+
messages=[{"role": "user", "content": "Hello!"}]
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
print(f"Cost: ${tracker.total_cost:.6f}")
|
|
99
|
+
|
|
100
|
+
asyncio.run(main())
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Per-Model Cost Breakdown
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
tracker = CostTracker()
|
|
107
|
+
litellm.callbacks = [tracker]
|
|
108
|
+
|
|
109
|
+
# Make calls to different models...
|
|
110
|
+
litellm.completion(model="gpt-4", messages=[...])
|
|
111
|
+
litellm.completion(model="gpt-3.5-turbo", messages=[...])
|
|
112
|
+
litellm.completion(model="claude-3-sonnet", messages=[...])
|
|
113
|
+
|
|
114
|
+
# Get cost breakdown by model
|
|
115
|
+
for model, cost in tracker.cost_by_model.items():
|
|
116
|
+
print(f"{model}: ${cost:.6f}")
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
## API Reference
|
|
120
|
+
|
|
121
|
+
### CostTracker
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
CostTracker(
|
|
125
|
+
budget: float | None = None, # Spending limit in USD
|
|
126
|
+
on_budget_exceeded: Callable | None = None, # Callback when exceeded
|
|
127
|
+
raise_on_budget: bool = False, # Raise exception when exceeded
|
|
128
|
+
print_summary: bool = True # Print summary on program exit
|
|
129
|
+
)
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
**Properties:**
|
|
133
|
+
|
|
134
|
+
- `total_cost: float` — Running total in USD
|
|
135
|
+
- `request_count: int` — Number of successful requests
|
|
136
|
+
- `history: list[dict]` — All logged requests
|
|
137
|
+
- `budget: float | None` — Configured budget
|
|
138
|
+
- `budget_exceeded: bool` — Whether budget has been exceeded
|
|
139
|
+
- `cost_by_model: dict[str, float]` — Cost aggregated by model name
|
|
140
|
+
|
|
141
|
+
**Methods:**
|
|
142
|
+
|
|
143
|
+
- `reset()` — Clear all tracked data
|
|
144
|
+
|
|
145
|
+
### BudgetExceededError
|
|
146
|
+
|
|
147
|
+
Raised when budget is exceeded (if `raise_on_budget=True`).
|
|
148
|
+
|
|
149
|
+
```python
|
|
150
|
+
class BudgetExceededError(Exception):
|
|
151
|
+
budget: float # Configured budget
|
|
152
|
+
total_cost: float # Actual spend when exceeded
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
## Exit Summary
|
|
156
|
+
|
|
157
|
+
When your program ends, a cost summary is automatically printed:
|
|
158
|
+
|
|
159
|
+
```
|
|
160
|
+
==================================================
|
|
161
|
+
LLM COST SUMMARY
|
|
162
|
+
==================================================
|
|
163
|
+
Total Cost: $0.001959
|
|
164
|
+
Total Requests: 4
|
|
165
|
+
Budget: $0.0100 (OK)
|
|
166
|
+
Remaining: $0.008041
|
|
167
|
+
--------------------------------------------------
|
|
168
|
+
Requests:
|
|
169
|
+
1. gpt-4: 7+18 tokens = $0.000750
|
|
170
|
+
2. gpt-4: 13+17 tokens = $0.000900
|
|
171
|
+
3. gpt-3.5-turbo: 8+82 tokens = $0.000166
|
|
172
|
+
4. gpt-3.5-turbo: 10+58 tokens = $0.000143
|
|
173
|
+
==================================================
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
Disable with `print_summary=False`.
|
|
177
|
+
|
|
178
|
+
## History Entry Format
|
|
179
|
+
|
|
180
|
+
Each request is logged with:
|
|
181
|
+
|
|
182
|
+
```python
|
|
183
|
+
{
|
|
184
|
+
"model": "gpt-4",
|
|
185
|
+
"prompt_tokens": 150,
|
|
186
|
+
"completion_tokens": 50,
|
|
187
|
+
"cost": 0.0123,
|
|
188
|
+
"timestamp": "2026-02-22T10:30:00Z"
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
## Development
|
|
193
|
+
|
|
194
|
+
```bash
|
|
195
|
+
git clone https://github.com/Paawan13/tokencost.git
|
|
196
|
+
cd tokencost
|
|
197
|
+
pip install -e ".[dev]"
|
|
198
|
+
pytest
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
## License
|
|
202
|
+
|
|
203
|
+
MIT
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/llm_tokencost.egg-info/PKG-INFO
|
|
5
|
+
src/llm_tokencost.egg-info/SOURCES.txt
|
|
6
|
+
src/llm_tokencost.egg-info/dependency_links.txt
|
|
7
|
+
src/llm_tokencost.egg-info/requires.txt
|
|
8
|
+
src/llm_tokencost.egg-info/top_level.txt
|
|
9
|
+
src/tokencost/__init__.py
|
|
10
|
+
src/tokencost/exceptions.py
|
|
11
|
+
src/tokencost/py.typed
|
|
12
|
+
src/tokencost/tracker.py
|
|
13
|
+
tests/test_tracker.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
tokencost
|