Metadata-Version: 2.4
Name: tokenetc
Version: 0.1.3
Summary: Auto-track AI SDK token usage with cost calculation and statistics
Author: likun.pm
License-Expression: MIT
Project-URL: Homepage, https://github.com/likunpm/tokenetc
Project-URL: Repository, https://github.com/likunpm/tokenetc
Keywords: openai,anthropic,gemini,token,cost,tracking,llm,ai
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"

# tokenetc

自动追踪 OpenAI / Anthropic / Gemini SDK 的 token 用量，支持成本计算与多渠道、多项目统计。

## 安装

```bash
pip install tokenetc
```

## 快速上手

```python
import tokenetc

# 一行 patch，自动追踪所有已安装 SDK 的调用（同步 + 异步 + 流式）
tokenetc.patch()

# 之后正常使用 openai / anthropic / gemini，用量自动记录，无需改动业务代码
import openai
client = openai.OpenAI()
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "hello"}],
)

# 查询统计（默认最近 1 天）
stats = tokenetc.stats(days=7)
print(stats["total_tokens"])   # 总 token 数
print(stats["cost_usd"])       # 估算费用（USD）
print(stats["by_channel"])     # 按渠道（openai / anthropic / ollama …）
print(stats["by_model"])       # 按模型
print(stats["by_tag"])         # 按项目标签
```

## 多脚本 / 多项目区分

同一台机器上所有脚本共用同一个本地数据库。使用 `tag` 参数区分不同脚本或项目：

```python
# script_a.py
tokenetc.patch(tag="data-pipeline")

# notebook_b.ipynb
tokenetc.patch(tag="research")
```

查询时按标签过滤或汇总：

```python
# 只看某个项目
tokenetc.stats(days=7, tag="data-pipeline")

# 所有项目汇总，by_tag 自动分组
s = tokenetc.stats(days=30)
print(s["by_tag"])
# {
#   "data-pipeline": {"total_tokens": 50000, "cost_usd": 0.12, ...},
#   "research":      {"total_tokens": 20000, "cost_usd": 0.05, ...},
#   "(untagged)":    {"total_tokens": 5000,  "cost_usd": 0.01, ...}
# }
```

## 手动录入

Cursor、网页版 ChatGPT / Gemini 等无法自动追踪的渠道，可手动录入：

```python
tokenetc.record(
    channel="cursor",
    model="claude-sonnet-4",
    tag="work",           # 可选标签
    input_tokens=3000,
    output_tokens=500,
)
```

## 成本计算

```python
cost = tokenetc.cost("gpt-4o", input_tokens=1000, output_tokens=500)
print(f"${cost:.6f}")  # $0.007500

# 查看所有支持的模型价格
tokenetc.list_models()
```

## 统计查询参数

```python
tokenetc.stats(
    days=7,            # 最近 N 天（与 start/end 互斥）
    channel="openai",  # 过滤渠道（可选）
    model="gpt-4o",    # 过滤模型（可选）
    tag="research",    # 过滤标签/项目（可选）
)
```

返回结构包含：`total_tokens`、`input_tokens`、`output_tokens`、`cost_usd`、`count`、`by_channel`、`by_model`、`by_tag`、`daily`、`period`。

## 跳过某个 SDK

```python
tokenetc.patch(gemini=False)   # 不追踪 Gemini
tokenetc.patch(openai=False)   # 不追踪 OpenAI
```

## 数据存储

数据保存在 `~/.tokenetc/data.db`（SQLite，本地只读，无需联网）。

自定义路径：

```bash
TOKENETC_DB=~/my_project/tokens.db python my_script.py
```

## 支持的 SDK

| SDK | 版本要求 | 同步 | 异步 | 流式 |
|-----|---------|------|------|------|
| openai | >= 1.0 | ✅ | ✅ | ✅ |
| anthropic | >= 0.20 | ✅ | ✅ | ✅ |
| google-generativeai | >= 0.5 | ✅ | ✅ | — |

本地模型（Ollama 等，`base_url` 含 `localhost`）自动识别为零成本。
