Skip to main content
Glama

tokentoll

Erkennen Sie Änderungen der LLM-Kosten im Code-Review. Infracost für LLM-Ausgaben.

CI PyPI version GitHub Marketplace License: MIT Python 3.10+

Ein CLI-Tool und eine GitHub-Action, die Ihren Code statisch auf LLM-API-Aufrufe analysiert, deren Kosten schätzt und Ihnen die Kostenauswirkungen jeder Änderung in Ihrem Terminal oder als PR-Kommentar anzeigt. Keine Laufzeitabhängigkeiten.

Das Problem

Ein einziger Modellwechsel von gpt-4o-mini zu gpt-4o erhöht die Kosten um das 15-fache. Ein neuer API-Aufruf in einem kritischen Pfad kann Ihre Rechnung um 10.000 $/Monat erhöhen. Diese Änderungen verstecken sich im normalen Code-Review.

tokentoll findet LLM-API-Aufrufe in Ihrem Code, schätzt deren Kosten und zeigt Ihnen die Kostenauswirkungen jeder Änderung, bevor sie in die Produktion gelangt.

Related MCP server: ModelCostSaver

Schnellstart

pip install tokentoll

# Scan current directory for LLM API calls and their costs
tokentoll scan .

# Show cost impact of your last commit
tokentoll diff HEAD~1

# Compare two branches
tokentoll diff main..feature-branch

GitHub Action

name: LLM Cost Diff
on:
  pull_request:
    paths:
      - "**.py"

permissions:
  pull-requests: write

jobs:
  cost-diff:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - uses: Jwrede/tokentoll@v0.6.1

Was es erkennt

SDK

Muster

Status

OpenAI

chat.completions.create, responses.create

Unterstützt

Anthropic

messages.create, messages.stream

Unterstützt

Google GenAI

models.generate_content

Unterstützt

LiteLLM

completion, acompletion

Unterstützt

LangChain

ChatOpenAI, ChatAnthropic, init_chat_model

Unterstützt

Zhipu AI

ZhipuAiClient, ZhipuAI (GLM-Modelle)

Unterstützt

JS/TS SDKs

Geplant

Beispielausgabe

tokentoll scan

LLM API Calls Detected
============================================================

File: src/agents/summarizer.py
  Line 42: openai client.chat.completions.create
           Model: gpt-4o | Max tokens: 4096
           Est. cost/call: $0.03 | Monthly (1000 calls/month per call site): $26.50

  Line 78: openai client.chat.completions.create
           Model: gpt-4o-mini | Max tokens: 1000
           Est. cost/call: $0.000301 | Monthly (1000 calls/month per call site): $0.30

--
Total estimated monthly cost: $26.80
  1000 calls/month per call site

tokentoll diff

LLM Cost Diff: main..feature-branch
============================================================

+ ADDED    src/agents/rewriter.py:35
           openai | Model: gpt-4o
           Est. cost/call: $0.03 | Monthly: +$26.50

~ MODIFIED src/agents/summarizer.py:42
           openai | Model: gpt-4o -> gpt-4o-mini
           Est. cost/call: $0.03 -> $0.000301 | Monthly: -$26.20

--
Monthly cost impact: +$0.30
  Added: 1 | Changed: 1 | Removed: 0
  1000 calls/month per call site

Funktionsweise

  Source Code (.py files)
         |
         v
  +-------------+     +------------------+
  | AST Scanner |---->| SDK Detectors    |
  | (ast.parse) |     | OpenAI, Anthropic|
  +-------------+     | Google, LiteLLM  |
                       | LangChain        |
                       +------------------+
                              |
                              v
                       +------------------+
                       | Pricing Engine   |
                       | 2200+ models     |
                       | Auto-cached      |
                       +------------------+
                              |
                  +-----------+-----------+
                  |                       |
                  v                       v
           +------------+         +-------------+
           | Scan Report|         | Diff Engine  |
           | (costs)    |         | (old vs new) |
           +------------+         +-------------+
                  |                       |
                  v                       v
           +------------+         +-------------+
           | Table/JSON |         | Table/JSON/  |
           |            |         | PR Comment   |
           +------------+         +-------------+
  1. Analysiert Python-Dateien mithilfe des ast-Moduls, um LLM-API-Aufrufe zu finden

  2. Multi-Pass-Konstanten-Propagierung löst Modellnamen über Variablen, os.getenv()-Fallbacks, Klassenattribute, Konstruktor-Argumente, Dict-Inhalte und **kwargs-Entpackung auf

  3. Sucht Preise aus einem lokalen Cache (bezogen von LiteLLM, über 2200 Modelle)

  4. Für den Diff-Modus: Vergleicht Aufrufe zwischen zwei Git-Refs und berechnet die Kostendifferenz

  5. Gibt einen Kostenbericht als Tabelle, JSON oder GitHub-PR-Kommentar aus

CLI-Referenz

tokentoll scan [PATH...] [--format table|json|markdown] [--calls-per-month N] [--config PATH]
tokentoll diff [REF] [--base REF] [--head REF] [--format table|json|markdown|github-comment] [--config PATH]
tokentoll update    # Update bundled pricing data

MCP-Server

tokentoll enthält einen MCP-Server (Model Context Protocol), mit dem Claude Code und andere MCP-Hosts die Kostenauswirkungen von LLM-Codeänderungen direkt aus einem Agenten-Gespräch heraus überprüfen können.

Installation

pip install tokentoll[mcp]

Registrierung bei Claude Code

claude mcp add --transport stdio tokentoll -- tokentoll-mcp

Tools

Tool

Beschreibung

scan

Findet LLM-API-Aufrufe in einem Verzeichnis und schätzt die monatlichen Kosten. Akzeptiert einen Pfad und optional calls_per_month.

diff

Vergleicht LLM-Kosten zwischen zwei Git-Refs. Akzeptiert base_ref und optional head_ref (Standard ist HEAD).

Beide Tools geben eine JSON-Ausgabe zurück.

Beispiel-Anwendungsfall

Claude Code kann die Kostenauswirkungen seiner eigenen Änderungen vor dem Commit überprüfen. Zum Beispiel kann der Agent nach dem Wechsel eines Modells von gpt-4o zu gpt-4o-mini das diff-Tool gegen HEAD aufrufen, um die Kostenreduzierung vor dem Erstellen des Commits zu verifizieren.

Preisdaten

Preisdaten sind gebündelt und funktionieren offline. Um auf die neuesten Preise zu aktualisieren:

tokentoll update

Die Preisdaten stammen aus der model_prices_and_context_window.json von LiteLLM und decken über 300 Modelle von OpenAI, Anthropic, Google, AWS Bedrock, Azure und mehr ab.

Dynamische Modell-Standardwerte

Wenn tokentoll auf einen Aufruf stößt, bei dem der Modellname eine Variable ist, die nicht aufgelöst werden kann, wendet es einen sinnvollen SDK-spezifischen Standardwert an, damit Sie dennoch Kostenschätzungen erhalten:

SDK

Standardmodell

OpenAI

gpt-4o

Anthropic

claude-sonnet-4-20250514

Google GenAI

gemini-2.0-flash

LiteLLM

gpt-4o

LangChain

gpt-4o

Zhipu AI

zai/glm-4.6

Diese Standardwerte werden in der Scan-Ausgabe als gpt-4o (default) angezeigt. Sie können diese pro Projekt oder pro Pfad mithilfe einer .tokentoll.yml-Konfigurationsdatei überschreiben (siehe unten).

Konfiguration

Erstellen Sie eine .tokentoll.yml in Ihrem Projektstammverzeichnis, um das Verhalten anzupassen. tokentoll findet diese Datei automatisch, indem es vom gescannten Verzeichnis aus nach oben sucht.

# Default model for all dynamic (unresolved) calls
default_model: gpt-4o

# Per-SDK defaults (override the built-in defaults above)
default_models:
  openai: gpt-4o-mini
  anthropic: claude-haiku-3-20240307

# Assumed calls per month per call site
calls_per_month: 5000

# Skip cost estimation entirely for dynamic (unresolved) models. When true,
# calls whose model name cannot be resolved statically are reported with no
# cost rather than priced against a default. Useful for projects that prefer
# silence over a guess.
skip_dynamic_models: false

# Exclude paths from scanning (prefix match or glob pattern)
exclude:
  - tests/
  - examples/
  - docs/
  - "*_test.py"

# Per-path overrides (longest prefix match)
overrides:
  - path: src/agents/
    default_model: gpt-4o
    calls_per_month: 10000
  - path: src/azure/
    skip_dynamic_models: true

Auflösungsreihenfolge für dynamische Modell-Standardwerte: SDK-spezifische Konfiguration (default_models) > generische Konfiguration (default_model) > integrierte SDK-Standardwerte.

Sie können auch --config path/to/.tokentoll.yml übergeben, um eine bestimmte Konfigurationsdatei zu verwenden.

Tokenschätzung

Standardmäßig schätzt tokentoll die Token-Anzahl mithilfe einer Zeichen/4-Heuristik. Für genauere Schätzungen installieren Sie tiktoken:

pip install tiktoken

Wenn tiktoken verfügbar ist, verwendet tokentoll die korrekte Tokenizer-Kodierung für jedes Modell. Unbekannte Modelle fallen auf cl100k_base zurück. Tiktoken wird bei Bedarf geladen und Encoder werden zwischengespeichert, sodass kein Start-Performanceverlust entsteht, wenn Sie es nicht benötigen.

Intelligente Variablenauflösung

Echte Codebasen übergeben Modellnamen selten als String-Literale. Die Multi-Pass-Konstanten-Propagierungs-Engine von tokentoll folgt:

DEFAULT_MODEL = os.getenv("MODEL", "gpt-4o")

class Config:
    model: str = DEFAULT_MODEL

config = Config()
kwargs = {"model": config.model, "max_tokens": 2000}
client.chat.completions.create(**kwargs)
# tokentoll resolves: model="gpt-4o", max_tokens=2000
  • Variablenzuweisungen (MODEL = "gpt-4o")

  • os.getenv() / os.environ.get() Fallback-Werte

  • Standardparameter von Funktionen

  • Standardwerte von Klassenattributen

  • Konstruktor-Argument-Propagierung

  • Dict-Literal- und Subskript-Inhalte

  • **kwargs-Entpackung

Roadmap

  • Kontextbewusste Aufrufhäufigkeit (geplant): Schätzung der Aufrufe/Monat aus dem umgebenden Code (FastAPI-Routen-Handler = hoher Datenverkehr, Skripte = niedrig, Schleifen = multipliziert), anstatt ein einheitliches Volumen über alle Aufrufstellen hinweg anzunehmen.

  • JS/TS-Unterstützung (geplant): Erkennung von LLM-Aufrufen in JavaScript- und TypeScript-Dateien.

  • Kostenwarnungen: Konfigurierbare Schwellenwerte, die CI fehlschlagen lassen, wenn ein PR eine Kostendifferenz überschreitet.

Einschränkungen

  • Kann Modelle, die zur Laufzeit aus externen Konfigurationsdateien oder Datenbanken geladen werden, nicht auflösen. Diese Aufrufe verwenden SDK-spezifische Standardwerte (konfigurierbar über .tokentoll.yml).

  • Token-Schätzungen verwenden eine Zeichen/4-Heuristik, sofern nicht tiktoken installiert ist.

  • Monatliche Schätzungen gehen von einem einheitlichen Aufrufvolumen pro Aufrufstelle aus (konfigurierbar über --calls-per-month, .tokentoll.yml oder Pfad-spezifische Überschreibungen). Verwenden Sie die exclude-Option, um Test- und Beispieldateien zu überspringen.

  • Derzeit nur Python (JS/TS-Unterstützung geplant).

Lizenz

MIT

Available Tools

2 tools
diffA

Compare LLM costs between two git refs.

Shows which LLM call sites were added, removed, or changed between the base and head refs, along with the cost impact of those changes.

Args: base_ref: The base git ref (branch, tag, or commit) to compare from. head_ref: The head git ref to compare to. Defaults to HEAD.

Returns: JSON string with the diff results including cost changes.

Inputs: base_ref (required), head_ref. Returns: result

scanA

Scan a directory for LLM API calls and estimate monthly costs.

Finds all LLM API call sites (OpenAI, Anthropic, etc.) in the given path and produces a cost estimate based on token counts and pricing.

Args: path: Directory or file path to scan. Defaults to current directory. calls_per_month: Assumed monthly call volume per call site. If not provided, the CLI default (1000) is used.

Returns: JSON string with the scan results including call sites and cost estimates.

Inputs: path, calls_per_month. Returns: result

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.2/5.0

    Scored across 2 tools

    Disambiguation5/5

    The two tools, diff and scan, have clearly distinct purposes: scan finds LLM call sites and estimates costs, while diff compares costs between git refs. No overlap or ambiguity.

    Naming Consistency4/5

    Both tool names are single verbs ('diff', 'scan'), which is consistent in style. While not a verb_noun pattern, the naming is uniform and intuitive for the domain.

    Tool Count3/5

    With only 2 tools, the server is very focused. This can be appropriate for a narrow utility, but it feels thin for a full server. A few more tools (e.g., pricing config) might improve scope.

    Completeness3/5

    The tools cover two core operations: scanning and diffing. However, there is no tool for managing pricing configurations or listing assumptions, which could be gaps for advanced use.

    Maintenance

    ActivityNo data
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Estimates, compares, and controls LLM API costs before agents spend tokens, with tools for cost estimation, model comparison, and budget checking.
      59 npm
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables exact Claude API cost estimation from token counts with correct prompt-cache economics, plus cache break-even analysis showing whether and at which TTL reusing a prefix pays off. It also scans source code for tiktoken-based token counting used alongside Claude models and points to the correct fix.
      MIT