tokonomics 0.1.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.
- tokonomics-0.1.0/.copier-answers.yml +21 -0
- tokonomics-0.1.0/.github/FUNDING.yml +3 -0
- tokonomics-0.1.0/.github/copilot-instructions.md +19 -0
- tokonomics-0.1.0/.github/dependabot.yml +9 -0
- tokonomics-0.1.0/.github/workflows/build.yml +88 -0
- tokonomics-0.1.0/.github/workflows/documentation.yml +57 -0
- tokonomics-0.1.0/.gitignore +32 -0
- tokonomics-0.1.0/.pre-commit-config.yaml +48 -0
- tokonomics-0.1.0/LICENSE +22 -0
- tokonomics-0.1.0/PKG-INFO +158 -0
- tokonomics-0.1.0/README.md +107 -0
- tokonomics-0.1.0/docs/.empty +0 -0
- tokonomics-0.1.0/duties.py +60 -0
- tokonomics-0.1.0/mkdocs.yml +92 -0
- tokonomics-0.1.0/overrides/_dummy.txt +1 -0
- tokonomics-0.1.0/pyproject.toml +250 -0
- tokonomics-0.1.0/src/tokonomics/__init__.py +6 -0
- tokonomics-0.1.0/src/tokonomics/core.py +159 -0
- tokonomics-0.1.0/src/tokonomics/py.typed +0 -0
- tokonomics-0.1.0/src/tokonomics/toko_types.py +23 -0
- tokonomics-0.1.0/tests/__init__.py +3 -0
- tokonomics-0.1.0/tests/conftest.py +1 -0
- tokonomics-0.1.0/tests/test_tokonomics.py +137 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Changes here will be overwritten by Copier
|
|
2
|
+
_commit: v1.8.2
|
|
3
|
+
_src_path: .\copier-phil65\
|
|
4
|
+
author_email: philipptemminghoff@googlemail.com
|
|
5
|
+
author_fullname: Philipp Temminghoff
|
|
6
|
+
author_username: phil65
|
|
7
|
+
copyright_date: '2024'
|
|
8
|
+
copyright_holder: Philipp Temminghoff
|
|
9
|
+
copyright_holder_email: philipptemminghoff@googlemail.com
|
|
10
|
+
libraries_use_pydantic: false
|
|
11
|
+
libraries_use_qt: false
|
|
12
|
+
project_description: Calcuate costs for LLM Usage based on token count
|
|
13
|
+
project_name: Tokonomics
|
|
14
|
+
python_minimum_version: '3.12'
|
|
15
|
+
python_package_command_line_name: tokonomics
|
|
16
|
+
python_package_distribution_name: tokonomics
|
|
17
|
+
python_package_import_name: tokonomics
|
|
18
|
+
repository_name: tokonomics
|
|
19
|
+
repository_namespace: phil65
|
|
20
|
+
repository_provider: github.com
|
|
21
|
+
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
## Code style
|
|
2
|
+
|
|
3
|
+
You can assume Python 3.12.
|
|
4
|
+
Use newest language features if possible
|
|
5
|
+
Consider using pattern matching, walrus operators and other new syntax features.
|
|
6
|
+
Adhere to pep8.
|
|
7
|
+
|
|
8
|
+
## Tests
|
|
9
|
+
|
|
10
|
+
Tests are written using PyTest. Dont put tests into a class.
|
|
11
|
+
|
|
12
|
+
## DocStrings
|
|
13
|
+
|
|
14
|
+
DocStrings are written in google-style.
|
|
15
|
+
Dont add the types to the "Args" section.
|
|
16
|
+
Only add a Return section if a value is returned and the meaning of the returned value
|
|
17
|
+
is not obvious.
|
|
18
|
+
You can use markdown admonitions with python-markdown syntax if neccessary (!!! info, !!! note, !!! warning).
|
|
19
|
+
You can use markdown tables and markdown lists if neccessary.
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
name: Build
|
|
2
|
+
|
|
3
|
+
on: [push, pull_request]
|
|
4
|
+
|
|
5
|
+
jobs:
|
|
6
|
+
test:
|
|
7
|
+
runs-on: ${{ matrix.os }}
|
|
8
|
+
continue-on-error: ${{ matrix.python_version == '3.14' }}
|
|
9
|
+
strategy:
|
|
10
|
+
matrix:
|
|
11
|
+
python_version: ["3.12", "3.13", "3.14"]
|
|
12
|
+
os: ["ubuntu-latest", "macos-latest", "windows-latest"]
|
|
13
|
+
steps:
|
|
14
|
+
- name: Check out repository
|
|
15
|
+
uses: actions/checkout@v4
|
|
16
|
+
|
|
17
|
+
- name: Set up Python ${{ matrix.python_version }}
|
|
18
|
+
uses: actions/setup-python@v5
|
|
19
|
+
with:
|
|
20
|
+
python-version: ${{ matrix.python_version }}
|
|
21
|
+
allow-prereleases: true
|
|
22
|
+
|
|
23
|
+
- name: Install uv
|
|
24
|
+
uses: astral-sh/setup-uv@v4
|
|
25
|
+
with:
|
|
26
|
+
enable-cache: true
|
|
27
|
+
cache-dependency-glob: pyproject.toml
|
|
28
|
+
cache-suffix: py${{ matrix.python_version }}
|
|
29
|
+
|
|
30
|
+
- name: Install dependencies (uv sync)
|
|
31
|
+
run: uv sync --all-extras --no-group docs
|
|
32
|
+
|
|
33
|
+
- name: Check for code issues (ruff check)
|
|
34
|
+
uses: astral-sh/ruff-action@v1
|
|
35
|
+
|
|
36
|
+
- name: Check code format (ruff format)
|
|
37
|
+
uses: astral-sh/ruff-action@v1
|
|
38
|
+
with:
|
|
39
|
+
args: "format --check"
|
|
40
|
+
|
|
41
|
+
- name: Static type checking (MyPy)
|
|
42
|
+
run: uv run --no-group docs mypy src/tokonomics/
|
|
43
|
+
|
|
44
|
+
- name: Run tests
|
|
45
|
+
run: uv run --no-group docs pytest --cov-report=xml --cov=src/tokonomics/ --cov-report=term-missing
|
|
46
|
+
|
|
47
|
+
- name: Upload test results to Codecov
|
|
48
|
+
uses: codecov/codecov-action@v5
|
|
49
|
+
with:
|
|
50
|
+
fail_ci_if_error: false
|
|
51
|
+
verbose: true
|
|
52
|
+
|
|
53
|
+
release:
|
|
54
|
+
runs-on: ubuntu-latest
|
|
55
|
+
needs: test
|
|
56
|
+
if: startsWith(github.ref, 'refs/tags/')
|
|
57
|
+
permissions:
|
|
58
|
+
# this permission is mandatory for trusted publishing
|
|
59
|
+
id-token: write
|
|
60
|
+
contents: write
|
|
61
|
+
steps:
|
|
62
|
+
- name: Check out repository
|
|
63
|
+
uses: actions/checkout@v4
|
|
64
|
+
|
|
65
|
+
- name: Set up Python
|
|
66
|
+
uses: actions/setup-python@v5
|
|
67
|
+
with:
|
|
68
|
+
python-version: "3.12"
|
|
69
|
+
|
|
70
|
+
- name: Install uv
|
|
71
|
+
uses: astral-sh/setup-uv@v4
|
|
72
|
+
with:
|
|
73
|
+
enable-cache: true
|
|
74
|
+
cache-dependency-glob: pyproject.toml
|
|
75
|
+
cache-suffix: py${{ matrix.python_version }}
|
|
76
|
+
|
|
77
|
+
- name: Build package
|
|
78
|
+
run: uv build
|
|
79
|
+
|
|
80
|
+
- name: Publish package distributions to PyPI
|
|
81
|
+
uses: pypa/gh-action-pypi-publish@release/v1
|
|
82
|
+
|
|
83
|
+
- name: Release package on GitHub
|
|
84
|
+
uses: ncipollo/release-action@v1
|
|
85
|
+
with:
|
|
86
|
+
body: ${{ github.event.head_commit.message }}
|
|
87
|
+
artifacts: dist/*.whl,dist/*.tar.gz
|
|
88
|
+
token: ${{ secrets.GITHUB_TOKEN }}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
name: Build documentation
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches:
|
|
6
|
+
- main
|
|
7
|
+
|
|
8
|
+
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
|
|
9
|
+
permissions:
|
|
10
|
+
contents: read
|
|
11
|
+
pages: write
|
|
12
|
+
id-token: write
|
|
13
|
+
|
|
14
|
+
# Allow one concurrent deployment
|
|
15
|
+
concurrency:
|
|
16
|
+
group: "pages"
|
|
17
|
+
cancel-in-progress: true
|
|
18
|
+
|
|
19
|
+
# Default to bash
|
|
20
|
+
defaults:
|
|
21
|
+
run:
|
|
22
|
+
shell: bash
|
|
23
|
+
|
|
24
|
+
jobs:
|
|
25
|
+
build:
|
|
26
|
+
runs-on: ubuntu-latest
|
|
27
|
+
|
|
28
|
+
steps:
|
|
29
|
+
- uses: actions/checkout@v4
|
|
30
|
+
with:
|
|
31
|
+
fetch-depth: 0
|
|
32
|
+
- name: Set up Python
|
|
33
|
+
uses: actions/setup-python@v5
|
|
34
|
+
with:
|
|
35
|
+
python-version: "3.12"
|
|
36
|
+
- name: Install uv
|
|
37
|
+
uses: astral-sh/setup-uv@v4
|
|
38
|
+
- name: Install dependencies
|
|
39
|
+
run: |
|
|
40
|
+
uv sync --all-extras
|
|
41
|
+
- name: Build
|
|
42
|
+
run: uv run mknodes build
|
|
43
|
+
- name: Upload artifact
|
|
44
|
+
uses: actions/upload-pages-artifact@v3
|
|
45
|
+
with:
|
|
46
|
+
path: ./site
|
|
47
|
+
|
|
48
|
+
deploy:
|
|
49
|
+
environment:
|
|
50
|
+
name: github-pages
|
|
51
|
+
url: ${{ steps.deployment.outputs.page_url }}
|
|
52
|
+
runs-on: ubuntu-latest
|
|
53
|
+
needs: build
|
|
54
|
+
steps:
|
|
55
|
+
- name: Deploy to GitHub Pages
|
|
56
|
+
id: deployment
|
|
57
|
+
uses: actions/deploy-pages@v4
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
# Distribution / packaging
|
|
5
|
+
*.sublime-workspace
|
|
6
|
+
# Unit test / coverage reports
|
|
7
|
+
.coverage
|
|
8
|
+
coverage.xml
|
|
9
|
+
.cache
|
|
10
|
+
.hatch
|
|
11
|
+
.pytest_cache/
|
|
12
|
+
junit.xml
|
|
13
|
+
# Jupyter Notebook
|
|
14
|
+
.ipynb_checkpoints
|
|
15
|
+
# pyenv
|
|
16
|
+
.python-version
|
|
17
|
+
# dotenv
|
|
18
|
+
.env
|
|
19
|
+
# virtualenv
|
|
20
|
+
.venv
|
|
21
|
+
# mkdocs documentation
|
|
22
|
+
/site
|
|
23
|
+
# mypy
|
|
24
|
+
.mypy_cache/
|
|
25
|
+
# .vscode
|
|
26
|
+
.vscode/
|
|
27
|
+
# OS files
|
|
28
|
+
.DS_Store
|
|
29
|
+
# uv
|
|
30
|
+
uv.lock
|
|
31
|
+
# DiskCache cache file
|
|
32
|
+
./model_cache
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
default_language_version:
|
|
2
|
+
python: python3.12
|
|
3
|
+
default_stages: [pre-commit]
|
|
4
|
+
repos:
|
|
5
|
+
- repo: local
|
|
6
|
+
hooks:
|
|
7
|
+
- id: pytest-check
|
|
8
|
+
name: pytest-check
|
|
9
|
+
entry: uv run pytest
|
|
10
|
+
language: system
|
|
11
|
+
# stages: [push]
|
|
12
|
+
types: [python]
|
|
13
|
+
pass_filenames: false
|
|
14
|
+
always_run: true
|
|
15
|
+
|
|
16
|
+
- repo: https://github.com/pre-commit/pre-commit-hooks
|
|
17
|
+
# https://pre-commit.com/hooks.html
|
|
18
|
+
rev: v5.0.0
|
|
19
|
+
hooks:
|
|
20
|
+
- id: check-added-large-files
|
|
21
|
+
- id: check-case-conflict
|
|
22
|
+
- id: check-merge-conflict
|
|
23
|
+
- id: check-toml
|
|
24
|
+
- id: check-json
|
|
25
|
+
- id: check-xml
|
|
26
|
+
- id: check-yaml
|
|
27
|
+
args: [--allow-multiple-documents, --unsafe]
|
|
28
|
+
- id: debug-statements
|
|
29
|
+
- id: detect-private-key
|
|
30
|
+
|
|
31
|
+
- repo: https://github.com/pre-commit/mirrors-mypy
|
|
32
|
+
rev: v1.13.0
|
|
33
|
+
hooks:
|
|
34
|
+
- id: mypy
|
|
35
|
+
additional_dependencies: [orjson]
|
|
36
|
+
|
|
37
|
+
- repo: https://github.com/charliermarsh/ruff-pre-commit
|
|
38
|
+
rev: v0.8.4
|
|
39
|
+
hooks:
|
|
40
|
+
- id: ruff
|
|
41
|
+
- id: ruff-format
|
|
42
|
+
|
|
43
|
+
- repo: https://github.com/commitizen-tools/commitizen
|
|
44
|
+
rev: v4.1.0
|
|
45
|
+
hooks:
|
|
46
|
+
- id: commitizen
|
|
47
|
+
stages: [commit-msg]
|
|
48
|
+
additional_dependencies: [typing-extensions]
|
tokonomics-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024, Philipp Temminghoff
|
|
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.
|
|
22
|
+
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tokonomics
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Calcuate costs for LLM Usage based on token count
|
|
5
|
+
Project-URL: Documentation, https://phil65.github.io/tokonomics/
|
|
6
|
+
Project-URL: Source, https://github.com/phil65/tokonomics
|
|
7
|
+
Project-URL: Issues, https://github.com/phil65/tokonomics/issues
|
|
8
|
+
Project-URL: Discussions, https://github.com/phil65/tokonomics/discussions
|
|
9
|
+
Project-URL: Code coverage, https://app.codecov.io/gh/phil65/tokonomics
|
|
10
|
+
Author-email: Philipp Temminghoff <philipptemminghoff@googlemail.com>
|
|
11
|
+
License: MIT License
|
|
12
|
+
|
|
13
|
+
Copyright (c) 2024, Philipp Temminghoff
|
|
14
|
+
|
|
15
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
16
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
17
|
+
in the Software without restriction, including without limitation the rights
|
|
18
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
19
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
20
|
+
furnished to do so, subject to the following conditions:
|
|
21
|
+
|
|
22
|
+
The above copyright notice and this permission notice shall be included in all
|
|
23
|
+
copies or substantial portions of the Software.
|
|
24
|
+
|
|
25
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
26
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
27
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
28
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
29
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
30
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
31
|
+
SOFTWARE.
|
|
32
|
+
|
|
33
|
+
License-File: LICENSE
|
|
34
|
+
Classifier: Development Status :: 4 - Beta
|
|
35
|
+
Classifier: Intended Audience :: Developers
|
|
36
|
+
Classifier: Operating System :: OS Independent
|
|
37
|
+
Classifier: Programming Language :: Python :: 3
|
|
38
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
39
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
40
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
41
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
42
|
+
Classifier: Topic :: Documentation
|
|
43
|
+
Classifier: Topic :: Software Development
|
|
44
|
+
Classifier: Topic :: Utilities
|
|
45
|
+
Classifier: Typing :: Typed
|
|
46
|
+
Requires-Python: >=3.12
|
|
47
|
+
Requires-Dist: diskcache>=5.6.3
|
|
48
|
+
Requires-Dist: httpx>=0.27.2
|
|
49
|
+
Requires-Dist: platformdirs>=4.3.6
|
|
50
|
+
Description-Content-Type: text/markdown
|
|
51
|
+
|
|
52
|
+
# Tokonomics
|
|
53
|
+
|
|
54
|
+
[](https://pypi.org/project/tokonomics/)
|
|
55
|
+
[](https://pypi.org/project/tokonomics/)
|
|
56
|
+
[](https://pypi.org/project/tokonomics/)
|
|
57
|
+
[](https://pypi.org/project/tokonomics/)
|
|
58
|
+
[](https://pypi.org/project/tokonomics/)
|
|
59
|
+
[](https://pypi.org/project/tokonomics/)
|
|
60
|
+
[](https://pypi.org/project/tokonomics/)
|
|
61
|
+
[](https://pypi.org/project/tokonomics/)
|
|
62
|
+
[](https://pypi.org/project/tokonomics/)
|
|
63
|
+
[](https://github.com/phil65/tokonomics/releases)
|
|
64
|
+
[](https://github.com/phil65/tokonomics/graphs/contributors)
|
|
65
|
+
[](https://github.com/phil65/tokonomics/discussions)
|
|
66
|
+
[](https://github.com/phil65/tokonomics/forks)
|
|
67
|
+
[](https://github.com/phil65/tokonomics/issues)
|
|
68
|
+
[](https://github.com/phil65/tokonomics/pulls)
|
|
69
|
+
[](https://github.com/phil65/tokonomics/watchers)
|
|
70
|
+
[](https://github.com/phil65/tokonomics/stars)
|
|
71
|
+
[](https://github.com/phil65/tokonomics)
|
|
72
|
+
[](https://github.com/phil65/tokonomics/commits)
|
|
73
|
+
[](https://github.com/phil65/tokonomics/releases)
|
|
74
|
+
[](https://github.com/phil65/tokonomics)
|
|
75
|
+
[](https://github.com/phil65/tokonomics)
|
|
76
|
+
[](https://github.com/phil65/tokonomics)
|
|
77
|
+
[](https://github.com/phil65/tokonomics)
|
|
78
|
+
[](https://codecov.io/gh/phil65/tokonomics/)
|
|
79
|
+
[](https://github.com/psf/black)
|
|
80
|
+
[](https://pyup.io/repos/github/phil65/tokonomics/)
|
|
81
|
+
|
|
82
|
+
[Read the documentation!](https://phil65.github.io/tokonomics/)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
Calculate costs for LLM usage based on token counts using LiteLLM's pricing data.
|
|
87
|
+
|
|
88
|
+
## Installation
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
pip install tokonomics
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## Features
|
|
95
|
+
|
|
96
|
+
- Automatic cost calculation for various LLM models
|
|
97
|
+
- Caches pricing data locally (24-hour default cache duration)
|
|
98
|
+
- Supports multiple model name formats (e.g., "gpt-4", "openai:gpt-4")
|
|
99
|
+
- Asynchronous API
|
|
100
|
+
- Fully typed with runtime type checking
|
|
101
|
+
- Zero configuration required
|
|
102
|
+
|
|
103
|
+
## Usage
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
import asyncio
|
|
107
|
+
from tokonomics import calculate_token_cost, TokenUsage
|
|
108
|
+
|
|
109
|
+
async def main():
|
|
110
|
+
# Define your token usage
|
|
111
|
+
usage = TokenUsage(
|
|
112
|
+
prompt=100, # tokens used in the prompt
|
|
113
|
+
completion=50, # tokens used in the completion
|
|
114
|
+
total=150 # total tokens used
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
# Calculate cost
|
|
118
|
+
cost = await calculate_token_cost("gpt-4", usage)
|
|
119
|
+
if cost:
|
|
120
|
+
print(f"Total cost: ${cost:.6f}")
|
|
121
|
+
else:
|
|
122
|
+
print("Could not determine cost for model")
|
|
123
|
+
|
|
124
|
+
asyncio.run(main())
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
You can customize the cache timeout:
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
from tokonomics import get_model_costs
|
|
131
|
+
|
|
132
|
+
# Get model costs with custom cache duration (e.g., 1 hour)
|
|
133
|
+
costs = await get_model_costs("gpt-4", cache_timeout=3600)
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## Model Name Support
|
|
137
|
+
|
|
138
|
+
The library supports multiple formats for model names:
|
|
139
|
+
- Direct model names: `"gpt-4"`
|
|
140
|
+
- Provider-prefixed: `"openai:gpt-4"`
|
|
141
|
+
- Provider-path style: `"openai/gpt-4"`
|
|
142
|
+
|
|
143
|
+
Names are matched case-insensitively.
|
|
144
|
+
|
|
145
|
+
## Data Source
|
|
146
|
+
|
|
147
|
+
Pricing data is sourced from [LiteLLM's pricing repository](https://github.com/BerriAI/litellm) and is automatically cached locally using `diskcache`. The cache is updated when pricing data is not found or has expired.
|
|
148
|
+
|
|
149
|
+
## Requirements
|
|
150
|
+
|
|
151
|
+
- Python 3.12+
|
|
152
|
+
- `httpx`
|
|
153
|
+
- `diskcache`
|
|
154
|
+
- `platformdirs`
|
|
155
|
+
|
|
156
|
+
## License
|
|
157
|
+
|
|
158
|
+
This project is licensed under the MIT License - see the LICENSE file for details.
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# Tokonomics
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/tokonomics/)
|
|
4
|
+
[](https://pypi.org/project/tokonomics/)
|
|
5
|
+
[](https://pypi.org/project/tokonomics/)
|
|
6
|
+
[](https://pypi.org/project/tokonomics/)
|
|
7
|
+
[](https://pypi.org/project/tokonomics/)
|
|
8
|
+
[](https://pypi.org/project/tokonomics/)
|
|
9
|
+
[](https://pypi.org/project/tokonomics/)
|
|
10
|
+
[](https://pypi.org/project/tokonomics/)
|
|
11
|
+
[](https://pypi.org/project/tokonomics/)
|
|
12
|
+
[](https://github.com/phil65/tokonomics/releases)
|
|
13
|
+
[](https://github.com/phil65/tokonomics/graphs/contributors)
|
|
14
|
+
[](https://github.com/phil65/tokonomics/discussions)
|
|
15
|
+
[](https://github.com/phil65/tokonomics/forks)
|
|
16
|
+
[](https://github.com/phil65/tokonomics/issues)
|
|
17
|
+
[](https://github.com/phil65/tokonomics/pulls)
|
|
18
|
+
[](https://github.com/phil65/tokonomics/watchers)
|
|
19
|
+
[](https://github.com/phil65/tokonomics/stars)
|
|
20
|
+
[](https://github.com/phil65/tokonomics)
|
|
21
|
+
[](https://github.com/phil65/tokonomics/commits)
|
|
22
|
+
[](https://github.com/phil65/tokonomics/releases)
|
|
23
|
+
[](https://github.com/phil65/tokonomics)
|
|
24
|
+
[](https://github.com/phil65/tokonomics)
|
|
25
|
+
[](https://github.com/phil65/tokonomics)
|
|
26
|
+
[](https://github.com/phil65/tokonomics)
|
|
27
|
+
[](https://codecov.io/gh/phil65/tokonomics/)
|
|
28
|
+
[](https://github.com/psf/black)
|
|
29
|
+
[](https://pyup.io/repos/github/phil65/tokonomics/)
|
|
30
|
+
|
|
31
|
+
[Read the documentation!](https://phil65.github.io/tokonomics/)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
Calculate costs for LLM usage based on token counts using LiteLLM's pricing data.
|
|
36
|
+
|
|
37
|
+
## Installation
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install tokonomics
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Features
|
|
44
|
+
|
|
45
|
+
- Automatic cost calculation for various LLM models
|
|
46
|
+
- Caches pricing data locally (24-hour default cache duration)
|
|
47
|
+
- Supports multiple model name formats (e.g., "gpt-4", "openai:gpt-4")
|
|
48
|
+
- Asynchronous API
|
|
49
|
+
- Fully typed with runtime type checking
|
|
50
|
+
- Zero configuration required
|
|
51
|
+
|
|
52
|
+
## Usage
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
import asyncio
|
|
56
|
+
from tokonomics import calculate_token_cost, TokenUsage
|
|
57
|
+
|
|
58
|
+
async def main():
|
|
59
|
+
# Define your token usage
|
|
60
|
+
usage = TokenUsage(
|
|
61
|
+
prompt=100, # tokens used in the prompt
|
|
62
|
+
completion=50, # tokens used in the completion
|
|
63
|
+
total=150 # total tokens used
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
# Calculate cost
|
|
67
|
+
cost = await calculate_token_cost("gpt-4", usage)
|
|
68
|
+
if cost:
|
|
69
|
+
print(f"Total cost: ${cost:.6f}")
|
|
70
|
+
else:
|
|
71
|
+
print("Could not determine cost for model")
|
|
72
|
+
|
|
73
|
+
asyncio.run(main())
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
You can customize the cache timeout:
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from tokonomics import get_model_costs
|
|
80
|
+
|
|
81
|
+
# Get model costs with custom cache duration (e.g., 1 hour)
|
|
82
|
+
costs = await get_model_costs("gpt-4", cache_timeout=3600)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Model Name Support
|
|
86
|
+
|
|
87
|
+
The library supports multiple formats for model names:
|
|
88
|
+
- Direct model names: `"gpt-4"`
|
|
89
|
+
- Provider-prefixed: `"openai:gpt-4"`
|
|
90
|
+
- Provider-path style: `"openai/gpt-4"`
|
|
91
|
+
|
|
92
|
+
Names are matched case-insensitively.
|
|
93
|
+
|
|
94
|
+
## Data Source
|
|
95
|
+
|
|
96
|
+
Pricing data is sourced from [LiteLLM's pricing repository](https://github.com/BerriAI/litellm) and is automatically cached locally using `diskcache`. The cache is updated when pricing data is not found or has expired.
|
|
97
|
+
|
|
98
|
+
## Requirements
|
|
99
|
+
|
|
100
|
+
- Python 3.12+
|
|
101
|
+
- `httpx`
|
|
102
|
+
- `diskcache`
|
|
103
|
+
- `platformdirs`
|
|
104
|
+
|
|
105
|
+
## License
|
|
106
|
+
|
|
107
|
+
This project is licensed under the MIT License - see the LICENSE file for details.
|
|
File without changes
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from duty import duty
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@duty(capture=False)
|
|
7
|
+
def build(ctx, *args: str):
|
|
8
|
+
"""Build a MkNodes page."""
|
|
9
|
+
args_str = " " + " ".join(args) if args else ""
|
|
10
|
+
ctx.run(f"uv run mknodes build{args_str}")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@duty(capture=False)
|
|
14
|
+
def serve(ctx, *args: str):
|
|
15
|
+
"""Serve a MkNodes page."""
|
|
16
|
+
args_str = " " + " ".join(args) if args else ""
|
|
17
|
+
ctx.run(f"uv run mknodes serve{args_str}")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@duty(capture=False)
|
|
21
|
+
def test(ctx, *args: str):
|
|
22
|
+
"""Serve a MkNodes page."""
|
|
23
|
+
args_str = " " + " ".join(args) if args else ""
|
|
24
|
+
ctx.run(f"uv run pytest{args_str}")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@duty(capture=False)
|
|
28
|
+
def clean(ctx):
|
|
29
|
+
"""Clean all files from the Git directory except checked-in files."""
|
|
30
|
+
ctx.run("git clean -dfX")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@duty(capture=False)
|
|
34
|
+
def update(ctx):
|
|
35
|
+
"""Update all environment packages using pip directly."""
|
|
36
|
+
ctx.run("uv lock --upgrade")
|
|
37
|
+
ctx.run("uv sync --all-extras")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@duty(capture=False)
|
|
41
|
+
def lint(ctx):
|
|
42
|
+
"""Lint the code and fix issues if possible."""
|
|
43
|
+
ctx.run("uv run ruff check --fix --unsafe-fixes .")
|
|
44
|
+
ctx.run("uv run ruff format .")
|
|
45
|
+
ctx.run("uv run mypy src/tokonomics/")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@duty(capture=False)
|
|
49
|
+
def lint_check(ctx):
|
|
50
|
+
"""Lint the code."""
|
|
51
|
+
ctx.run("uv run ruff check .")
|
|
52
|
+
ctx.run("uv run ruff format --check .")
|
|
53
|
+
ctx.run("uv run mypy src/tokonomics/")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@duty(capture=False)
|
|
57
|
+
def version(ctx, *args: str):
|
|
58
|
+
"""Bump package version."""
|
|
59
|
+
args_str = " " + " ".join(args) if args else ""
|
|
60
|
+
ctx.run(f"hatch version{args_str}")
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
site_name: "Tokonomics"
|
|
2
|
+
site_description: "Calcuate costs for LLM Usage based on token count"
|
|
3
|
+
repo_url: "https://github.com/phil65/tokonomics/"
|
|
4
|
+
site_url: https://phil65.github.io/tokonomics/
|
|
5
|
+
site_author: "Philipp Temminghoff"
|
|
6
|
+
copyright: Copyright © 2024 Philipp Temminghoff
|
|
7
|
+
|
|
8
|
+
theme:
|
|
9
|
+
name: material
|
|
10
|
+
custom_dir: overrides
|
|
11
|
+
icon:
|
|
12
|
+
logo: material/graph-outline
|
|
13
|
+
palette:
|
|
14
|
+
# Palette toggle for automatic mode
|
|
15
|
+
- media: "(prefers-color-scheme)"
|
|
16
|
+
toggle:
|
|
17
|
+
icon: material/brightness-auto
|
|
18
|
+
name: Switch to light mode
|
|
19
|
+
|
|
20
|
+
# Palette toggle for light mode
|
|
21
|
+
- media: "(prefers-color-scheme: light)"
|
|
22
|
+
scheme: default
|
|
23
|
+
primary: red
|
|
24
|
+
toggle:
|
|
25
|
+
icon: material/brightness-7
|
|
26
|
+
name: Switch to dark mode
|
|
27
|
+
|
|
28
|
+
# Palette toggle for dark mode
|
|
29
|
+
- media: "(prefers-color-scheme: dark)"
|
|
30
|
+
scheme: slate
|
|
31
|
+
primary: red
|
|
32
|
+
toggle:
|
|
33
|
+
icon: material/brightness-4
|
|
34
|
+
name: Switch to system preference
|
|
35
|
+
features:
|
|
36
|
+
- announce.dismiss
|
|
37
|
+
- content.action.edit
|
|
38
|
+
- content.code.copy
|
|
39
|
+
- content.code.select
|
|
40
|
+
- content.code.annotate
|
|
41
|
+
- content.tooltips
|
|
42
|
+
# - content.tabs.link
|
|
43
|
+
- navigation.tracking # update URL based on current item in TOC
|
|
44
|
+
- navigation.path # shows breadcrumbs
|
|
45
|
+
- navigation.tabs # make top level tabs
|
|
46
|
+
- navigation.indexes # documents can be directly attached to sections (overview pages)
|
|
47
|
+
- navigation.footer # next/previous page buttons in footer
|
|
48
|
+
- navigation.top # adds back-to-top button
|
|
49
|
+
# - navigation.sections # top-level sections are rendered as groups
|
|
50
|
+
# - navigation.expand # expand all subsections in left sidebar by default
|
|
51
|
+
- toc.follow # makes toc follow scrolling
|
|
52
|
+
# - toc.integrate # integrates toc into left menu
|
|
53
|
+
- search.highlight
|
|
54
|
+
- search.suggest
|
|
55
|
+
# - search.share
|
|
56
|
+
|
|
57
|
+
plugins:
|
|
58
|
+
- search
|
|
59
|
+
- autorefs
|
|
60
|
+
- mknodes
|
|
61
|
+
- mkdocstrings:
|
|
62
|
+
default_handler: python
|
|
63
|
+
handlers:
|
|
64
|
+
python:
|
|
65
|
+
import:
|
|
66
|
+
- url: https://docs.python.org/3/objects.inv
|
|
67
|
+
domains: [std, py]
|
|
68
|
+
options:
|
|
69
|
+
# https://mkdocstrings.github.io/python/usage/
|
|
70
|
+
enable_inventory: !ENV [CI, false]
|
|
71
|
+
show_signature_annotations: true
|
|
72
|
+
show_symbol_type_toc: true
|
|
73
|
+
show_symbol_type_heading: true
|
|
74
|
+
show_root_toc_entry: false
|
|
75
|
+
# merge_init_into_class: true
|
|
76
|
+
ignore_init_summary: true
|
|
77
|
+
inherited_members: false
|
|
78
|
+
signature_crossrefs: true
|
|
79
|
+
separate_signature: true
|
|
80
|
+
line_length: 90
|
|
81
|
+
markdown_extensions:
|
|
82
|
+
- attr_list
|
|
83
|
+
- pymdownx.emoji
|
|
84
|
+
- toc:
|
|
85
|
+
permalink: true
|
|
86
|
+
|
|
87
|
+
extra:
|
|
88
|
+
social:
|
|
89
|
+
- icon: fontawesome/brands/github
|
|
90
|
+
link: https://github.com/phil65
|
|
91
|
+
- icon: fontawesome/brands/python
|
|
92
|
+
link: https://pypi.org/project/tokonomics/
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
File exists to make sure that folder exists for git
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
[tool.hatch.version]
|
|
2
|
+
source = "regex_commit"
|
|
3
|
+
commit_extra_args = ["-e"]
|
|
4
|
+
path = "src/tokonomics/__init__.py"
|
|
5
|
+
|
|
6
|
+
[build-system]
|
|
7
|
+
requires = ["hatchling", "hatch-regex-commit"]
|
|
8
|
+
build-backend = "hatchling.build"
|
|
9
|
+
|
|
10
|
+
[project]
|
|
11
|
+
name = "tokonomics"
|
|
12
|
+
description = "Calcuate costs for LLM Usage based on token count"
|
|
13
|
+
authors = [
|
|
14
|
+
{ name = "Philipp Temminghoff", email = "philipptemminghoff@googlemail.com" },
|
|
15
|
+
]
|
|
16
|
+
readme = "README.md"
|
|
17
|
+
dynamic = ["version"]
|
|
18
|
+
classifiers = [
|
|
19
|
+
"Development Status :: 4 - Beta",
|
|
20
|
+
"Intended Audience :: Developers",
|
|
21
|
+
"Operating System :: OS Independent",
|
|
22
|
+
"Programming Language :: Python :: 3",
|
|
23
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
24
|
+
"Programming Language :: Python :: 3.12",
|
|
25
|
+
"Programming Language :: Python :: 3.13",
|
|
26
|
+
"Programming Language :: Python :: 3.14",
|
|
27
|
+
"Topic :: Documentation",
|
|
28
|
+
"Topic :: Software Development",
|
|
29
|
+
"Topic :: Utilities",
|
|
30
|
+
"Typing :: Typed",
|
|
31
|
+
|
|
32
|
+
]
|
|
33
|
+
keywords = []
|
|
34
|
+
requires-python = ">=3.12"
|
|
35
|
+
license = { file = "LICENSE" }
|
|
36
|
+
dependencies = [
|
|
37
|
+
"diskcache>=5.6.3",
|
|
38
|
+
"httpx>=0.27.2",
|
|
39
|
+
# Only add below (Copier)
|
|
40
|
+
"platformdirs>=4.3.6",
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
[tool.uv]
|
|
44
|
+
default-groups = ["dev", "lint", "docs"]
|
|
45
|
+
|
|
46
|
+
[dependency-groups]
|
|
47
|
+
dev = [
|
|
48
|
+
"pytest",
|
|
49
|
+
"pytest-cov",
|
|
50
|
+
"pyreadline3",
|
|
51
|
+
"devtools",
|
|
52
|
+
# Only add below (Copier)
|
|
53
|
+
"pytest-asyncio>=0.25.0",
|
|
54
|
+
"respx>=0.22.0",
|
|
55
|
+
]
|
|
56
|
+
benchmark = ["pyinstrument"]
|
|
57
|
+
lint = [
|
|
58
|
+
"ruff",
|
|
59
|
+
"mypy[faster-cache]; python_version < '3.14'",
|
|
60
|
+
"mypy; python_version >= '3.14'",
|
|
61
|
+
# Only add below (Copier)
|
|
62
|
+
]
|
|
63
|
+
docs = [
|
|
64
|
+
"mkdocs-mknodes",
|
|
65
|
+
"mkdocs-material",
|
|
66
|
+
# Only add below (Copier)
|
|
67
|
+
]
|
|
68
|
+
|
|
69
|
+
[project.urls]
|
|
70
|
+
Documentation = "https://phil65.github.io/tokonomics/"
|
|
71
|
+
Source = "https://github.com/phil65/tokonomics"
|
|
72
|
+
Issues = "https://github.com/phil65/tokonomics/issues"
|
|
73
|
+
Discussions = "https://github.com/phil65/tokonomics/discussions"
|
|
74
|
+
"Code coverage" = "https://app.codecov.io/gh/phil65/tokonomics"
|
|
75
|
+
|
|
76
|
+
[tool.pytest.ini_options]
|
|
77
|
+
testpaths = "tests/"
|
|
78
|
+
log_cli = true
|
|
79
|
+
log_format = "%(asctime)s %(levelname)s %(message)s"
|
|
80
|
+
log_date_format = "%Y-%m-%d %H:%M:%S"
|
|
81
|
+
asyncio_mode = "auto"
|
|
82
|
+
asyncio_mode_fixture_scope = "function"
|
|
83
|
+
|
|
84
|
+
[tool.coverage.report]
|
|
85
|
+
exclude_lines = [
|
|
86
|
+
"pragma: no cover",
|
|
87
|
+
"if TYPE_CHECKING:",
|
|
88
|
+
"@overload",
|
|
89
|
+
"except ImportError",
|
|
90
|
+
'if __name__ == "__main__":',
|
|
91
|
+
]
|
|
92
|
+
|
|
93
|
+
[tool.mypy]
|
|
94
|
+
python_version = "3.12"
|
|
95
|
+
disable_error_code = ["misc", "import"]
|
|
96
|
+
pretty = true
|
|
97
|
+
check_untyped_defs = true
|
|
98
|
+
exclude = ['venv/', '.venv/', 'tests/']
|
|
99
|
+
plugins = []
|
|
100
|
+
|
|
101
|
+
[tool.ruff]
|
|
102
|
+
line-length = 90
|
|
103
|
+
extend-exclude = ['docs']
|
|
104
|
+
target-version = "py312"
|
|
105
|
+
|
|
106
|
+
[tool.ruff.lint]
|
|
107
|
+
select = [
|
|
108
|
+
"A", # Flake8-builtins
|
|
109
|
+
# "ANN", # Flake8-Annotations
|
|
110
|
+
# "ASYNC", # Flake8-Async
|
|
111
|
+
# "ARG", # # Flake8-Unused-Arguments
|
|
112
|
+
"B", # flake8-bugbear
|
|
113
|
+
"BLE", # Flake8-blind-except
|
|
114
|
+
"C",
|
|
115
|
+
"C4", # flake8-comprehensions
|
|
116
|
+
# "C90", # MCCabe
|
|
117
|
+
"COM", # Flake8-commas
|
|
118
|
+
# "CPY", # Copyright-related rules
|
|
119
|
+
"D", # PyDocStyle
|
|
120
|
+
# "DTZ", # Flake8- Datetimez
|
|
121
|
+
"E", # PyCodeStyle Error
|
|
122
|
+
"EM", # flake8-errmsg
|
|
123
|
+
# "ERA", # Eradicate
|
|
124
|
+
"EXE", # flake8-executable
|
|
125
|
+
"F", # PyFlakes
|
|
126
|
+
"FA", # flake8-future-annotations
|
|
127
|
+
# "FBT", # flake8-boolean-trap
|
|
128
|
+
# "FIX", # flake8-fixme
|
|
129
|
+
"FLY", # flynt
|
|
130
|
+
"G", # flake8-logging-format
|
|
131
|
+
"I", # ISort
|
|
132
|
+
"ICN", # Flake8-import-conventions
|
|
133
|
+
"INP", # flake8-no-pep420
|
|
134
|
+
"INT", # flake8-gettext
|
|
135
|
+
"ISC", # flake8-implicit-str-concat
|
|
136
|
+
"N", # pep8-naming
|
|
137
|
+
# "NPY", # numpy-specific rules
|
|
138
|
+
# "PD", # pandas-vet
|
|
139
|
+
"PERF", # perflint
|
|
140
|
+
# "PGH", # pygrep-hooks
|
|
141
|
+
"PIE", # flake8-pie
|
|
142
|
+
"PLE", # PyLint Error
|
|
143
|
+
"PLC", # PyLint convention
|
|
144
|
+
# "PLW", # PyLint Warning
|
|
145
|
+
"PLR", # PyLint refactor
|
|
146
|
+
"PT", # flake8-pytest-style
|
|
147
|
+
"PTH", # flake8-use-pathlib
|
|
148
|
+
"PYI", # flake8-pyi
|
|
149
|
+
"Q", # flake8-quotes
|
|
150
|
+
"RET", # flake8-return
|
|
151
|
+
"RSE", # flake8-raise
|
|
152
|
+
"RUF", # ruff-specific rules
|
|
153
|
+
# "S", # flake8-bandit
|
|
154
|
+
"SIM", # flake8-simplify
|
|
155
|
+
"SLF", # flake8-self
|
|
156
|
+
"SLOT", # flake8-slots
|
|
157
|
+
# "T",
|
|
158
|
+
# "TD", # flake8-todos
|
|
159
|
+
"T10", # flake8-debugger
|
|
160
|
+
# "T20", # flake8-print
|
|
161
|
+
"TC", # flake8-type-checking
|
|
162
|
+
"TID", # flake8-tidy-imports
|
|
163
|
+
"TRY", # tryceratops
|
|
164
|
+
"UP", # PyUpgrade
|
|
165
|
+
"W", # PyCodeStyle warning
|
|
166
|
+
"YTT", # flake8-2020
|
|
167
|
+
]
|
|
168
|
+
ignore = [
|
|
169
|
+
"C408", # Unnecessary {obj_type} call (rewrite as a literal)
|
|
170
|
+
"B905", # zip() without an explicit strict= parameter
|
|
171
|
+
"C901", # {name} is too complex ({complexity} > {max_complexity})
|
|
172
|
+
"COM812",
|
|
173
|
+
# "CPY001", # Missing copyright notice at top of file
|
|
174
|
+
"D100", # Missing docstring in public module
|
|
175
|
+
"D101", # Missing docstring in public class
|
|
176
|
+
"D102", # Missing docstring in public method
|
|
177
|
+
"D103", # Missing docstring in public function
|
|
178
|
+
"D104", # Missing docstring in public package
|
|
179
|
+
"D105", # Missing docstring in magic method
|
|
180
|
+
"D106", # Missing docstring in public nested class
|
|
181
|
+
"D107", # Missing docstring in __init__
|
|
182
|
+
"D203", # 1 blank line required before class docstring
|
|
183
|
+
"D204", # 1 blank line required after class docstring
|
|
184
|
+
"D213", # Multi-line docstring summary should start at the second line
|
|
185
|
+
"D215", # Section underline is over-indented ("{name}")
|
|
186
|
+
"D400", # First line should end with a period
|
|
187
|
+
"D401", # First line of docstring should be in imperative mood: "{first_line}"
|
|
188
|
+
"D404", # First word of the docstring should not be "This"
|
|
189
|
+
"D406", # Section name should end with a newline ("{name}")
|
|
190
|
+
"D407", # Missing dashed underline after section ("{name}")
|
|
191
|
+
"D408", # Section underline should be in the line following the section's name ("{name}")
|
|
192
|
+
"D409", # Section underline should match the length of its name ("{name}")
|
|
193
|
+
"D413", # Missing blank line after last section ("{name}")
|
|
194
|
+
"ISC001",
|
|
195
|
+
"PLR0912", # Too many branches
|
|
196
|
+
"PLR0913", # Too many arguments to function call
|
|
197
|
+
"PLR0915", # Too many statements
|
|
198
|
+
# "PLR2004", # Magic values instead of named consts
|
|
199
|
+
"SLF001", # Private member accessed
|
|
200
|
+
"TRY003", # Avoid specifying long messages outside the exception class
|
|
201
|
+
]
|
|
202
|
+
|
|
203
|
+
[tool.ruff.lint.flake8-quotes]
|
|
204
|
+
docstring-quotes = "double"
|
|
205
|
+
|
|
206
|
+
[tool.ruff.format]
|
|
207
|
+
# Enable preview style formatting.
|
|
208
|
+
preview = true
|
|
209
|
+
|
|
210
|
+
[tool.ruff.lint.isort]
|
|
211
|
+
lines-after-imports = 2
|
|
212
|
+
# lines-between-types = 1
|
|
213
|
+
# atomic = true
|
|
214
|
+
force-sort-within-sections = true
|
|
215
|
+
combine-as-imports = true
|
|
216
|
+
|
|
217
|
+
[tool.ruff.lint.per-file-ignores]
|
|
218
|
+
"__init__.py" = ["E402", "I001"]
|
|
219
|
+
"scripts/*" = ["INP001"]
|
|
220
|
+
|
|
221
|
+
[tool.pyright]
|
|
222
|
+
venvPath = "."
|
|
223
|
+
venv = ".venv"
|
|
224
|
+
pythonVersion = "3.12"
|
|
225
|
+
pythonPlatform = "All"
|
|
226
|
+
typeCheckingMode = "basic"
|
|
227
|
+
deprecateTypingAliases = true
|
|
228
|
+
reportMissingTypeStubs = false
|
|
229
|
+
reportUnusedCallResult = false
|
|
230
|
+
reportUnknownVariableType = false
|
|
231
|
+
reportAny = false
|
|
232
|
+
reportImplicitOverride = false
|
|
233
|
+
reportUnusedFunction = false
|
|
234
|
+
reportImplicitStringConcatenation = false
|
|
235
|
+
reportIgnoreCommentWithoutRule = false
|
|
236
|
+
reportUnannotatedClassAttribute = false
|
|
237
|
+
reportSelfClsParameterName = false
|
|
238
|
+
reportPrivateImportUsage = false
|
|
239
|
+
|
|
240
|
+
[tool.mknodes]
|
|
241
|
+
allowed-commit-types = [
|
|
242
|
+
"fix",
|
|
243
|
+
"feat",
|
|
244
|
+
"refactor",
|
|
245
|
+
"docs",
|
|
246
|
+
"test",
|
|
247
|
+
"build",
|
|
248
|
+
"chore",
|
|
249
|
+
]
|
|
250
|
+
docstring-style = "google"
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Utilities for calculating token costs using LiteLLM pricing data."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import pathlib
|
|
7
|
+
|
|
8
|
+
import diskcache
|
|
9
|
+
import httpx
|
|
10
|
+
from platformdirs import user_data_dir
|
|
11
|
+
|
|
12
|
+
from tokonomics.toko_types import ModelCosts, TokenUsage
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
# Cache cost data persistently
|
|
19
|
+
PRICING_DIR = pathlib.Path(user_data_dir("tokonomics", "tokonomics")) / "pricing"
|
|
20
|
+
PRICING_DIR.mkdir(parents=True, exist_ok=True)
|
|
21
|
+
_cost_cache = diskcache.Cache(directory=str(PRICING_DIR))
|
|
22
|
+
|
|
23
|
+
# Cache timeout in seconds (24 hours)
|
|
24
|
+
_CACHE_TIMEOUT = 86400
|
|
25
|
+
|
|
26
|
+
LITELLM_PRICES_URL = "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def find_litellm_model_name(model: str) -> str | None:
|
|
30
|
+
"""Find matching model name in LiteLLM pricing data.
|
|
31
|
+
|
|
32
|
+
Attempts to match the input model name against cached LiteLLM pricing data
|
|
33
|
+
by trying different formats (direct match, base name, provider format).
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
model: Input model name (e.g. "openai:gpt-4", "gpt-4")
|
|
37
|
+
|
|
38
|
+
Returns:
|
|
39
|
+
str | None: Matching LiteLLM model name if found in cache, None otherwise
|
|
40
|
+
"""
|
|
41
|
+
logger.debug("Looking up model costs for: %s", model)
|
|
42
|
+
|
|
43
|
+
# Normalize case
|
|
44
|
+
model = model.lower()
|
|
45
|
+
|
|
46
|
+
# First check direct match
|
|
47
|
+
if model in _cost_cache:
|
|
48
|
+
logger.debug("Found direct cache match for: %s", model)
|
|
49
|
+
return model
|
|
50
|
+
|
|
51
|
+
# For provider:model format, try both variants
|
|
52
|
+
if ":" in model:
|
|
53
|
+
provider, model_name = model.split(":", 1)
|
|
54
|
+
# Try just model name (normalized)
|
|
55
|
+
model_name = model_name.lower()
|
|
56
|
+
if _cost_cache.get(model_name, None) is not None:
|
|
57
|
+
logger.debug("Found cache match for base name: %s", model_name)
|
|
58
|
+
return model_name
|
|
59
|
+
# Try provider/model format (normalized)
|
|
60
|
+
provider_format = f"{provider.lower()}/{model_name}"
|
|
61
|
+
if _cost_cache.get(provider_format, None) is not None:
|
|
62
|
+
logger.debug("Found cache match for provider format: %s", provider_format)
|
|
63
|
+
return provider_format
|
|
64
|
+
|
|
65
|
+
logger.debug("No cache match found for: %s", model)
|
|
66
|
+
return None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
async def get_model_costs(
|
|
70
|
+
model: str,
|
|
71
|
+
*,
|
|
72
|
+
cache_timeout: int = _CACHE_TIMEOUT,
|
|
73
|
+
) -> ModelCosts | None:
|
|
74
|
+
"""Get cost information for a model from LiteLLM pricing data.
|
|
75
|
+
|
|
76
|
+
Attempts to find model costs in cache first. If not found, downloads fresh
|
|
77
|
+
pricing data from LiteLLM's GitHub repository and updates the cache.
|
|
78
|
+
|
|
79
|
+
Args:
|
|
80
|
+
model: Name of the model to look up costs for
|
|
81
|
+
cache_timeout: Number of seconds to keep prices in cache (default: 24 hours)
|
|
82
|
+
|
|
83
|
+
Returns:
|
|
84
|
+
ModelCosts | None: Model's cost information if found, None otherwise
|
|
85
|
+
"""
|
|
86
|
+
# Find matching model name in LiteLLM format
|
|
87
|
+
if litellm_name := find_litellm_model_name(model):
|
|
88
|
+
return _cost_cache.get(litellm_name) # pyright: ignore
|
|
89
|
+
|
|
90
|
+
# Not in cache, try to fetch
|
|
91
|
+
try:
|
|
92
|
+
logger.debug("Downloading pricing data from LiteLLM...")
|
|
93
|
+
async with httpx.AsyncClient() as client:
|
|
94
|
+
response = await client.get(LITELLM_PRICES_URL)
|
|
95
|
+
response.raise_for_status()
|
|
96
|
+
data = response.json()
|
|
97
|
+
logger.debug("Successfully downloaded pricing data")
|
|
98
|
+
|
|
99
|
+
# Extract just the cost information we need
|
|
100
|
+
all_costs: dict[str, ModelCosts] = {}
|
|
101
|
+
for name, info in data.items():
|
|
102
|
+
if not isinstance(info, dict): # Skip sample_spec
|
|
103
|
+
continue
|
|
104
|
+
if "input_cost_per_token" not in info or "output_cost_per_token" not in info:
|
|
105
|
+
continue
|
|
106
|
+
# Store with normalized case
|
|
107
|
+
all_costs[name.lower()] = ModelCosts(
|
|
108
|
+
input_cost_per_token=float(info["input_cost_per_token"]),
|
|
109
|
+
output_cost_per_token=float(info["output_cost_per_token"]),
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
logger.debug("Extracted costs for %d models", len(all_costs))
|
|
113
|
+
|
|
114
|
+
# Update cache with all costs
|
|
115
|
+
for model_name, cost_info in all_costs.items():
|
|
116
|
+
_cost_cache.set(model_name, cost_info, expire=cache_timeout)
|
|
117
|
+
logger.debug("Updated cache with new pricing data")
|
|
118
|
+
|
|
119
|
+
# Return costs for requested model
|
|
120
|
+
if model in all_costs:
|
|
121
|
+
logger.debug("Found costs for requested model: %s", model)
|
|
122
|
+
return all_costs[model]
|
|
123
|
+
except Exception as e: # noqa: BLE001
|
|
124
|
+
logger.debug("Failed to get model costs: %s", e)
|
|
125
|
+
return None
|
|
126
|
+
else:
|
|
127
|
+
logger.debug("No costs found for model: %s", model)
|
|
128
|
+
return None
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
async def calculate_token_cost(
|
|
132
|
+
model: str,
|
|
133
|
+
token_usage: TokenUsage,
|
|
134
|
+
*,
|
|
135
|
+
cache_timeout: int = _CACHE_TIMEOUT,
|
|
136
|
+
) -> float | None:
|
|
137
|
+
"""Calculate total cost for token usage based on model pricing.
|
|
138
|
+
|
|
139
|
+
Combines input and output token counts with their respective costs to
|
|
140
|
+
calculate the total cost of the usage.
|
|
141
|
+
|
|
142
|
+
Args:
|
|
143
|
+
model: Name of the model used
|
|
144
|
+
token_usage: Dictionary containing 'prompt' and 'completion' token counts
|
|
145
|
+
cache_timeout: Number of seconds to keep prices in cache (default: 24 hours)
|
|
146
|
+
|
|
147
|
+
Returns:
|
|
148
|
+
float | None: Total cost in dollars if pricing data available, None otherwise
|
|
149
|
+
"""
|
|
150
|
+
costs = await get_model_costs(model, cache_timeout=cache_timeout)
|
|
151
|
+
if costs:
|
|
152
|
+
prompt_cost = token_usage["prompt"] * costs["input_cost_per_token"]
|
|
153
|
+
completion_cost = token_usage["completion"] * costs["output_cost_per_token"]
|
|
154
|
+
total_cost = float(prompt_cost + completion_cost)
|
|
155
|
+
msg = "Cost calculation - prompt: $%.6f, completion: $%.6f, total: $%.6f"
|
|
156
|
+
logger.debug(msg, prompt_cost, completion_cost, total_cost)
|
|
157
|
+
return total_cost
|
|
158
|
+
logger.debug("No costs found for model")
|
|
159
|
+
return None
|
|
File without changes
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Tokonomics types."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TypedDict
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ModelCosts(TypedDict):
|
|
9
|
+
"""Cost information for a model."""
|
|
10
|
+
|
|
11
|
+
input_cost_per_token: float
|
|
12
|
+
output_cost_per_token: float
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class TokenUsage(TypedDict):
|
|
16
|
+
"""Token usage statistics from model responses."""
|
|
17
|
+
|
|
18
|
+
total: int
|
|
19
|
+
"""Total tokens used"""
|
|
20
|
+
prompt: int
|
|
21
|
+
"""Tokens used in the prompt"""
|
|
22
|
+
completion: int
|
|
23
|
+
"""Tokens used in the completion"""
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Test suite for tokonomics core functionality."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import shutil
|
|
7
|
+
|
|
8
|
+
import diskcache
|
|
9
|
+
import httpx
|
|
10
|
+
from platformdirs import user_data_dir
|
|
11
|
+
import pytest
|
|
12
|
+
import respx
|
|
13
|
+
|
|
14
|
+
from tokonomics import calculate_token_cost, get_model_costs
|
|
15
|
+
from tokonomics.toko_types import TokenUsage
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
SAMPLE_PRICING_DATA = {
|
|
19
|
+
"gpt-4": {
|
|
20
|
+
"input_cost_per_token": 0.03,
|
|
21
|
+
"output_cost_per_token": 0.06,
|
|
22
|
+
},
|
|
23
|
+
"gpt-3.5-turbo": {
|
|
24
|
+
"input_cost_per_token": 0.001,
|
|
25
|
+
"output_cost_per_token": 0.002,
|
|
26
|
+
},
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
SAMPLE_TOKEN_USAGE = TokenUsage(
|
|
30
|
+
prompt=10,
|
|
31
|
+
completion=20,
|
|
32
|
+
total=30,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
# Use a test-specific cache directory
|
|
36
|
+
TEST_CACHE_DIR = Path(user_data_dir("tokonomics", "tokonomics")) / "pricing"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@pytest.fixture(autouse=True)
|
|
40
|
+
def setup_teardown():
|
|
41
|
+
"""Setup and teardown for each test."""
|
|
42
|
+
# Setup: ensure clean cache directory
|
|
43
|
+
import tokonomics.core
|
|
44
|
+
|
|
45
|
+
if hasattr(tokonomics.core, "_cost_cache"):
|
|
46
|
+
tokonomics.core._cost_cache.close()
|
|
47
|
+
|
|
48
|
+
if TEST_CACHE_DIR.exists():
|
|
49
|
+
shutil.rmtree(TEST_CACHE_DIR)
|
|
50
|
+
TEST_CACHE_DIR.mkdir(parents=True)
|
|
51
|
+
|
|
52
|
+
# Point the cache to our test directory
|
|
53
|
+
tokonomics.core._cost_cache = diskcache.Cache(str(TEST_CACHE_DIR))
|
|
54
|
+
|
|
55
|
+
yield
|
|
56
|
+
|
|
57
|
+
# Teardown: clean up
|
|
58
|
+
tokonomics.core._cost_cache.close()
|
|
59
|
+
if TEST_CACHE_DIR.exists():
|
|
60
|
+
shutil.rmtree(TEST_CACHE_DIR)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@pytest.fixture
|
|
64
|
+
def mock_litellm_api():
|
|
65
|
+
"""Mock LiteLLM API responses."""
|
|
66
|
+
with respx.mock(assert_all_mocked=True, assert_all_called=True) as respx_mock:
|
|
67
|
+
route = respx_mock.get(
|
|
68
|
+
"https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"
|
|
69
|
+
)
|
|
70
|
+
route.mock(return_value=httpx.Response(200, json=SAMPLE_PRICING_DATA))
|
|
71
|
+
yield respx_mock
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@pytest.mark.asyncio
|
|
75
|
+
async def test_get_model_costs_success(mock_litellm_api):
|
|
76
|
+
"""Test successful model cost retrieval."""
|
|
77
|
+
costs = await get_model_costs("gpt-4", cache_timeout=1)
|
|
78
|
+
assert costs is not None
|
|
79
|
+
assert costs["input_cost_per_token"] == 0.03 # noqa: PLR2004
|
|
80
|
+
assert costs["output_cost_per_token"] == 0.06 # noqa: PLR2004
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@pytest.mark.asyncio
|
|
84
|
+
async def test_get_model_costs_case_insensitive(mock_litellm_api):
|
|
85
|
+
"""Test that model name matching is case insensitive."""
|
|
86
|
+
# First call to populate cache
|
|
87
|
+
await get_model_costs("gpt-4", cache_timeout=1)
|
|
88
|
+
# Second call with different case
|
|
89
|
+
costs = await get_model_costs("GPT-4", cache_timeout=1)
|
|
90
|
+
assert costs is not None
|
|
91
|
+
assert costs["input_cost_per_token"] == 0.03 # noqa: PLR2004
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@pytest.mark.asyncio
|
|
95
|
+
async def test_get_model_costs_provider_format(mock_litellm_api):
|
|
96
|
+
"""Test that provider:model format works."""
|
|
97
|
+
# First call to populate cache
|
|
98
|
+
await get_model_costs("gpt-4", cache_timeout=1)
|
|
99
|
+
# Second call with provider format
|
|
100
|
+
costs = await get_model_costs("openai:gpt-4", cache_timeout=1)
|
|
101
|
+
assert costs is not None
|
|
102
|
+
assert costs["input_cost_per_token"] == 0.03 # noqa: PLR2004
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@pytest.mark.asyncio
|
|
106
|
+
async def test_get_model_costs_unknown_model(mock_litellm_api):
|
|
107
|
+
"""Test behavior with unknown model."""
|
|
108
|
+
costs = await get_model_costs("unknown-model", cache_timeout=1)
|
|
109
|
+
assert costs is None
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
@pytest.mark.asyncio
|
|
113
|
+
async def test_calculate_token_cost_success(mock_litellm_api):
|
|
114
|
+
"""Test successful token cost calculation."""
|
|
115
|
+
cost = await calculate_token_cost("gpt-4", SAMPLE_TOKEN_USAGE, cache_timeout=1)
|
|
116
|
+
assert cost is not None
|
|
117
|
+
# 10 tokens * 0.03 + 20 tokens * 0.06 = 1.5
|
|
118
|
+
assert cost == 1.5 # noqa: PLR2004
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@pytest.mark.asyncio
|
|
122
|
+
async def test_calculate_token_cost_unknown_model(mock_litellm_api):
|
|
123
|
+
"""Test token cost calculation with unknown model."""
|
|
124
|
+
cost = await calculate_token_cost(
|
|
125
|
+
"unknown-model", SAMPLE_TOKEN_USAGE, cache_timeout=1
|
|
126
|
+
)
|
|
127
|
+
assert cost is None
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@pytest.mark.asyncio
|
|
131
|
+
async def test_api_error(mock_litellm_api):
|
|
132
|
+
"""Test behavior when API request fails."""
|
|
133
|
+
mock_litellm_api.get(
|
|
134
|
+
"https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"
|
|
135
|
+
).mock(return_value=httpx.Response(500))
|
|
136
|
+
costs = await get_model_costs("gpt-4", cache_timeout=1)
|
|
137
|
+
assert costs is None
|