{"id":50472441,"url":"https://github.com/semcod/costs","last_synced_at":"2026-06-01T11:03:35.212Z","repository":{"id":347745752,"uuid":"1195137309","full_name":"semcod/costs","owner":"semcod","description":" Track AI costs for your projects - This tool helps developers monitor AI usage costs across git commits.  Zero-config AI cost calculator per commit/model with liteLLM integration.","archived":false,"fork":false,"pushed_at":"2026-05-13T15:09:14.000Z","size":1698,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-05-13T17:16:25.421Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"HTML","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/semcod.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-03-29T09:20:03.000Z","updated_at":"2026-05-13T15:30:46.000Z","dependencies_parsed_at":null,"dependency_job_id":"2df4587c-3134-4da9-bf74-4b9559006753","html_url":"https://github.com/semcod/costs","commit_stats":null,"previous_names":["semcod/cost"],"tags_count":39,"template":false,"template_full_name":null,"purl":"pkg:github/semcod/costs","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/semcod%2Fcosts","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/semcod%2Fcosts/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/semcod%2Fcosts/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/semcod%2Fcosts/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/semcod","download_url":"https://codeload.github.com/semcod/costs/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/semcod%2Fcosts/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33771630,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-01T02:00:06.963Z","response_time":115,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-06-01T11:03:35.143Z","updated_at":"2026-06-01T11:03:35.205Z","avatar_url":"https://github.com/semcod.png","language":"HTML","funding_links":[],"categories":[],"sub_categories":[],"readme":"## AI Cost Tracking\n\n![PyPI](https://img.shields.io/badge/pypi-costs-blue) ![Version](https://img.shields.io/badge/version-0.1.31-blue) ![Python](https://img.shields.io/badge/python-3.9+-blue) ![License](https://img.shields.io/badge/license-Apache--2.0-green)\n![AI Cost](https://img.shields.io/badge/AI%20Cost-$1.59-orange) ![Human Time](https://img.shields.io/badge/Human%20Time-9.4h-blue) ![Model](https://img.shields.io/badge/Model-openrouter%2Fqwen%2Fqwen3--coder--next-lightgrey)\n\n- 🤖 **LLM usage:** $1.5920 (51 commits)\n- 👤 **Human dev:** ~$938 (9.4h @ $100/h, 30min dedup)\n\nGenerated on 2026-05-13 using [openrouter/qwen/qwen3-coder-next](https://openrouter.ai/qwen/qwen3-coder-next)\n\n---\n\nTrack AI usage costs across your git commits with three flexible usage modes - no initial configuration required.\n\n## Features\n\n- **liteLLM Integration** - Support for 100+ AI providers via liteLLM\n- **Default: Qwen3 Coder Next** - Pre-configured with openrouter/qwen/qwen3-coder-next\n- **Zero Config** - Works out of the box, reads from `.env` file\n- **Smart Token Estimation** - Accurate cost calculation using tiktoken (OpenAI) and Anthropic tokenizer\n- **ROI Calculation** - Track value generated vs AI costs\n- **Date Filtering** - Analyze specific days, date ranges, or full history\n- **Auto Badges** - Automatically generate and update cost badges in README\n- **Rich Reports** - Markdown and HTML reports with visualizations\n- **All Commits Support** - Analyze all commits with `--all` flag (not just AI-tagged)\n\n## Tokenization\n\nThe tool uses accurate tokenization for precise cost estimation:\n\n| Model | Tokenizer | Accuracy |\n|-------|-----------|----------|\n| OpenAI GPT-4/4o | tiktoken (cl100k_base) | ~99% |\n| Anthropic Claude | Anthropic SDK (local) | 100% |\n| OpenRouter/Other | tiktoken fallback | ~95% |\n\n### Token Counting Examples\n\n```python\nfrom costs.tokenizers import count_tokens, Tokenizer\n\n# Count tokens for any model\ntext = \"def hello(): print('world')\"\ntokens = count_tokens(text, \"claude-3.5-sonnet\")  # 10 tokens\ntokens = count_tokens(text, \"gpt-4o\")             # 10 tokens\n\n# Use tokenizer directly\ntokenizer = Tokenizer()\ninput_tokens = tokenizer.count_tokens(prompt, model)\n```\n\n## Installation\n\n```bash\npip install costs\n```\n\n# Edit .env file to add your OpenRouter API key\necho \"OPENROUTER_API_KEY=YOUR_KEY\" \u003e\u003e .env\n```\n\n# Uses defaults from .env (Qwen3 Coder Next)\ncosts analyze --repo .\n\n# Or specify directly\ncosts analyze --repo . --model openrouter/qwen/qwen3-coder-next --api-key YOUR_KEY\n\n# Analyze all commits (not just AI-tagged)\ncosts analyze --repo . --all\n```\n\n## Configuration\n\nCreate a `.env` file in your project root:\n\n```bash\n# Required: OpenRouter API key (https://openrouter.ai/keys)\nOPENROUTER_API_KEY=YOUR_KEY\nLLM_MODEL=openrouter/qwen/qwen3-coder-next\n```\n\nOr use the built-in init command:\n\n```bash\ncosts init\n```\n\n### Option 1: BYOK (Bring Your Own Key) - Free\n\nUse your own API key via OpenRouter. Costs calculated locally with real provider pricing.\n\n```bash\n# With OpenRouter key (default from .env)\ncosts analyze --repo .\n\n# Explicit key\ncosts analyze --repo . --api-key YOUR_KEY\n```\n\n**Supported models via liteLLM:**\n- `openrouter/qwen/qwen3-coder-next` (default)\n- `anthropic/claude-4-sonnet`\n- `anthropic/claude-3.5-sonnet`\n- `anthropic/claude-3.5-haiku`\n- `openai/gpt-4o`\n- `openai/gpt-5.4-mini`\n- 100+ more via liteLLM\n\n### Option 2: Local/Ollama - Zero API Costs\n\nNo API key needed. Estimates based on diff size using local pricing.\n\n```bash\ncosts --repo . --mode local\n```\n\n**Estimation formula:** `diff_chars / 4 * 0.0001$/M tokens`\n\n## Date Filtering\n\nAnalyze commits for specific time periods:\n\n```bash\n# Analyze specific day\ncosts analyze --repo . --date 2024-03-15\n\n# Analyze date range\ncosts analyze --repo . --since 2024-01-01 --until 2024-03-31\n\n# Analyze all commits since repository creation\ncosts analyze --repo . --full-history\n\n# Analyze only AI-tagged commits (default)\ncosts analyze --repo . --ai-only\n\n# Analyze all commits (not just AI-tagged)\ncosts analyze --repo . --all\n```\n\n## Badge Generation\n\nGenerate and update cost badges in your README:\n\n```bash\n# Generate badge based on pyproject.toml configuration (AI commits only)\ncosts auto-badge --repo .\n\n# Generate badge for all commits (not just AI-tagged)\ncosts auto-badge --repo . --all\n\n# Manual badge generation\ncosts badge --repo . --model openrouter/qwen/qwen3-coder-next\n\n# Manual badge for all commits\ncosts badge --repo . --all\n```\n\nThis adds a badge section to README showing total cost, AI commits, and model used.\n\n# Generate markdown report with charts\ncosts report --repo . --format markdown\n\n# Generate HTML report\ncosts report --repo . --format html\n\n# Generate both and update README\ncosts report --repo . --format both --update-readme\n```\n\n## Python API\n\nUse the calculator directly in your code:\n\n```python\nfrom costs.calculator import ai_cost, estimate_tokens, calculate_cost\n\n# Calculate complete cost with ROI\nresult = ai_cost(commit_diff, model=\"claude-3.5-sonnet\")\nprint(f\"Cost: {result['cost_formatted']}\")\nprint(f\"Tokens: {result['tokens']['total']}\")\nprint(f\"ROI: {result['roi_formatted']}\")\n\n# Estimate tokens only\ntokens = estimate_tokens(diff, model=\"gpt-4o\")\nprint(f\"Input: {tokens['input']}, Output: {tokens['output']}\")\n\n# Calculate cost from tokens\ncost = calculate_cost(tokens, \"openrouter/qwen/qwen3-coder-next\")\n```\n\nSee `examples/` directory for more usage patterns.\n\n## How It Works\n\n1. **Parse git history** - Analyzes commits with optional `[ai:model]` tags\n2. **Estimate tokens** - Uses tiktoken for OpenAI models, Anthropic tokenizer for Claude, with accurate diff parsing\n3. **Calculate cost** - Multiplies tokens × model price\n4. **Generate ROI** - Estimates time saved (100 LOC/h × $100/h)\n\nBy default, only commits with `[ai:]` tags are analyzed. Use `--all` to analyze all commits.\n\n## Why liteLLM?\n\n- **Universal API** - Jedna składnia dla 100+ providerów\n- **Automatic routing** - Fallback między providerami\n- **Cost tracking** - Wbudowane liczenie tokenów\n- **OpenRouter** - Dostęp do najnowszych modeli bez kont premium\n\n### Option 3: SaaS Subscription - Managed\n\nEnterprise managed solution with dashboard and invoicing.\n\n```bash\ncosts --repo . --saas-token PLACEHOLDER\n```\n\n# Analyze last 50 commits (uses .env defaults)\ncosts analyze --repo . -n 50\n\n# Use specific model via liteLLM\ncosts analyze --repo . --model anthropic/claude-3.5-sonnet\n\n# Analyze all commits (not just AI-tagged)\ncosts analyze --repo . --all\n\n# Analyze with date filtering\ncosts analyze --repo . --since 2024-01-01 --until 2024-03-31\n\n# Export to custom file\ncosts analyze --repo . --output my_costs.csv\n\n# Show repository statistics\ncosts stats --repo .\n\n# Generate reports\ncosts report --repo . --format both --update-readme\n\n# Generate badge for all commits\ncosts badge --repo . --all\n\n# Auto-badge with pyproject.toml config\ncosts auto-badge --repo . --all\n\n# Estimate single diff\ncosts estimate my_changes.patch\n\n# Read diff from stdin\ngit diff HEAD~1 | costs estimate -\n```\n\n## Tagging AI Commits\n\nTag commits with `[ai:model]` for automatic tracking:\n\n```bash\ngit commit -m \"[ai:openrouter/qwen/qwen3-coder-next] Refactor authentication\"\ngit commit -m \"[ai:anthropic/claude-3.5-sonnet] Add payment integration\"\n```\n\n## Sample Output\n\n```\n🔍 Analyzing 100 commits from my-project...\n🤖 Model: openrouter/qwen/qwen3-coder-next | Mode: byok\n\n==================================================\n📊 AI COST ANALYSIS - openrouter/qwen/qwen3-coder-next\n==================================================\n   Commits analyzed: 42\n   Total cost:       $12.34\n   Hours saved:      15.3h\n   Value generated:  $1530.00\n   ROI:              124x\n==================================================\n📁 Results saved to: ai_costs.csv\n\n💡 Recent AI commits:\n   a1b2c3d4 | $0.32 | [ai:qwen3-coder-next] Refactor...\n   e5f6g7h8 | $0.45 | [ai:qwen3-coder-next] Add feature...\n```\n\n## CSV Export Format\n\n| Column | Description |\n|--------|-------------|\n| `commit_hash` | Short commit SHA |\n| `commit_message` | Full commit message |\n| `author` | Commit author name |\n| `date` | ISO format datetime |\n| `cost` | Calculated cost in USD |\n| `cost_formatted` | Formatted cost string |\n| `model` | AI model used |\n| `mode` | Calculation mode (byok/local/saas) |\n| `tokens_input` | Estimated input tokens |\n| `tokens_output` | Estimated output tokens |\n| `hours_saved` | Estimated hours saved |\n| `roi` | ROI multiplier |\n\n## Pricing Reference\n\n| Model | Input | Output | Tokenizer |\n|-------|-------|--------|-----------|\n| anthropic/claude-4-sonnet | $3/M | $15/M | Anthropic |\n| anthropic/claude-3.5-sonnet | $3/M | $15/M | Anthropic |\n| anthropic/claude-3.5-haiku | $0.8/M | $4/M | Anthropic |\n| openai/gpt-4o | $5/M | $15/M | tiktoken |\n| openai/gpt-5.4-mini | $0.15/M | $0.6/M | tiktoken |\n| openrouter/qwen/qwen3-coder-next | $0.50/M | $1.50/M | tiktoken |\n| ollama/* | ~$0.0001/M | ~$0.0001/M | tiktoken |\n\n## Business Model\n\n| Tier | Price | Features |\n|------|-------|----------|\n| **BYOK** | Free | Use your own OpenRouter API key |\n| **SaaS** | $9/month | Unlimited, managed keys, dashboard, EU invoicing |\n\n# Run CLI\npoetry run costs analyze --repo ..\n\n# Publish to PyPI\npoetry publish --build\n```\n\n## PHP Badge Service\n\nStandalone PHP service for generating badges:\n\n```bash\ncd services/badge-service\ncomposer install\nphp -S localhost:8080\n```\n\nGenerate badges via API:\n```bash\ncurl \"http://localhost:8080/badge.php?cost=12.34\u0026model=claude-4\u0026commits=42\"\n```\n\n## Automatic Cost Calculation\n\nThe tool can automatically calculate costs and update badges on every commit and during test runs.\n\n### Pre-commit Hook\n\nInstall the pre-commit hook to automatically update the badge before each commit:\n\n```bash\n# Copy hook to git hooks\ncp hooks/pre-commit .git/hooks/pre-commit\nchmod +x .git/hooks/pre-commit\n\n# Or use project.sh (includes hook installation)\nbash project.sh\n```\n\nThe hook will:\n1. Detect `costs` in global PATH or virtualenv\n2. Run `costs auto-badge` if `[tool.costs]` is configured in `pyproject.toml`\n3. Stage updated README.md (interactive prompt in terminal)\n\n### Pytest Integration\n\nTests automatically validate the cost calculation pipeline:\n\n```bash\n# Run all tests including auto-badge test\npytest tests/test_cost.py -v\n\n### GitHub Actions\n\nThe repository includes a workflow that runs on push/PR:\n\n```yaml\n## CLI Commands\n\n| Command | Description | Key Options |\n|---------|-------------|-------------|\n| `costs init` | Initialize `.env` configuration | `--force` - overwrite existing |\n| `costs analyze` | Analyze repository commits | `--repo`, `--model`, `--api-key`, `--all`, `--since`, `--until`, `--date`, `--full-history`, `--max-commits`, `--output` |\n| `costs stats` | Show repository statistics | `--repo` |\n| `costs report` | Generate markdown/HTML reports | `--repo`, `--model`, `--format`, `--output`, `--update-readme` |\n| `costs badge` | Generate cost badge | `--repo`, `--model`, `--all` |\n| `costs auto-badge` | Auto-generate badge from pyproject.toml | `--repo`, `--all` |\n| `costs estimate` | Estimate cost for single diff | `--model` |\n\n📖 **Automatic Badge Generation**: See [docs/AUTO_BADGE.md](docs/AUTO_BADGE.md) for GitHub Actions, pre-commit hooks, and CI/CD integration.\n\n## Environment Variables\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `OPENROUTER_API_KEY` | OpenRouter API key | (required for BYOK) |\n| `LLM_MODEL` | Default model for calculations | `openrouter/qwen/qwen3-coder-next` |\n\n## License\n\nLicensed under Apache-2.0.\n## Status\n\n_Last updated by [taskill](https://github.com/oqlos/taskill) at 2026-04-25 13:37 UTC_\n\n| Metric | Value |\n|---|---|\n| HEAD | `ffe3cf2` |\n| Coverage | — |\n| Failing tests | — |\n| Commits in last cycle | 50 |\n\n\u003e Large set of feature and documentation commits were made: configuration management, a deep code-analysis engine, CLI improvements, a commit-message generator, multi-language documentation, and new API capabilities, along with various refactors and formatting improvements.\n\n\u003c!-- taskill:status:end --\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsemcod%2Fcosts","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsemcod%2Fcosts","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsemcod%2Fcosts/lists"}