跳转至

API reference

Generated from the apogee-ai-cost source with mkdocstrings. Every symbol below is exported from apogee_ai_cost, so it is part of the supported public surface.

Application · DTOs

BenchDTO dataclass

Python
BenchDTO(calls: int = 1000)

calls class-attribute instance-attribute

Python
calls: int = 1000

BudgetDTO dataclass

Python
BudgetDTO(tenant_id: str, limit_usd: float, alert_at_pct: float = 0.8)

tenant_id instance-attribute

Python
tenant_id: str

limit_usd instance-attribute

Python
limit_usd: float

alert_at_pct class-attribute instance-attribute

Python
alert_at_pct: float = 0.8

CountDTO dataclass

Python
CountDTO(text: str, model: str = '')

text instance-attribute

Python
text: str

model class-attribute instance-attribute

Python
model: str = ''

EstimateDTO dataclass

Python
EstimateDTO(model: str, prompt_tokens: int = 0, completion_tokens: int = 0)

model instance-attribute

Python
model: str

prompt_tokens class-attribute instance-attribute

Python
prompt_tokens: int = 0

completion_tokens class-attribute instance-attribute

Python
completion_tokens: int = 0

RecordDTO dataclass

Python
RecordDTO(model: str, amount_usd: float, tenant_id: str | None = None, prompt_tokens: int = 0, completion_tokens: int = 0)

model instance-attribute

Python
model: str

amount_usd instance-attribute

Python
amount_usd: float

tenant_id class-attribute instance-attribute

Python
tenant_id: str | None = None

prompt_tokens class-attribute instance-attribute

Python
prompt_tokens: int = 0

completion_tokens class-attribute instance-attribute

Python
completion_tokens: int = 0

ReportDTO dataclass

Python
ReportDTO(tenant_id: str | None = None, format: str = 'json')

tenant_id class-attribute instance-attribute

Python
tenant_id: str | None = None

format class-attribute instance-attribute

Python
format: str = 'json'

Application · Use cases

BenchPricingUseCase

Synthetic pricing-loop benchmark across the builtin table.

execute async

Python
execute(calls: int) -> dict[str, float]
Source code in apogee_ai_cost/application/use_cases/bench_pricing_use_case.py
Python
async def execute(self, calls: int) -> dict[str, float]:
    if calls <= 0:
        raise ValueError("calls must be positive")
    table = PricingTable.builtin()
    use_case = EstimateCostUseCase(table)
    models = [e.model for e in table.list() if e.prompt_per_1k_usd > 0]
    if not models:
        raise RuntimeError("no priced models in builtin table")
    start = time.perf_counter()
    for i in range(calls):
        await use_case.execute(TokenUsage(
            model=models[i % len(models)],
            prompt_tokens=1000,
            completion_tokens=200,
        ))
    elapsed = (time.perf_counter() - start) * 1000.0
    return {
        "calls": float(calls),
        "elapsed_ms": elapsed,
        "calls_per_second": (calls / elapsed * 1000.0) if elapsed > 0 else 0.0,
    }

CheckBudgetUseCase

Python
CheckBudgetUseCase(tracker)
Source code in apogee_ai_cost/application/use_cases/check_budget_use_case.py
Python
def __init__(self, tracker) -> None:
    self._tracker = tracker

execute async

Python
execute(tenant_id: str) -> Budget
Source code in apogee_ai_cost/application/use_cases/check_budget_use_case.py
Python
async def execute(self, tenant_id: str) -> Budget:
    return await self._tracker.get(tenant_id)

CountTokensUseCase

Python
CountTokensUseCase(counter)
Source code in apogee_ai_cost/application/use_cases/count_tokens_use_case.py
Python
def __init__(self, counter) -> None:
    self._counter = counter

execute async

Python
execute(text: str, model: str = '') -> int
Source code in apogee_ai_cost/application/use_cases/count_tokens_use_case.py
Python
async def execute(self, text: str, model: str = "") -> int:
    return await self._counter.count(text, model=model)

EstimateCostUseCase

Python
EstimateCostUseCase(pricing_table)
Source code in apogee_ai_cost/application/use_cases/estimate_cost_use_case.py
Python
def __init__(self, pricing_table) -> None:
    self._table = pricing_table

execute async

Python
execute(usage: TokenUsage) -> CostEstimate
Source code in apogee_ai_cost/application/use_cases/estimate_cost_use_case.py
Python
async def execute(self, usage: TokenUsage) -> CostEstimate:
    entry = self._table.get(usage.model)
    prompt_cost = (usage.prompt_tokens / 1000.0) * entry.prompt_per_1k_usd
    completion_cost = (usage.completion_tokens / 1000.0) * entry.completion_per_1k_usd
    embedding_cost = (usage.embedding_tokens / 1000.0) * entry.embedding_per_1k_usd
    cache_read_cost = (usage.cache_read_tokens / 1000.0) * entry.cache_read_per_1k_usd
    cache_write_cost = (usage.cache_write_tokens / 1000.0) * entry.cache_write_per_1k_usd
    total = (
        prompt_cost
        + completion_cost
        + embedding_cost
        + cache_read_cost
        + cache_write_cost
    )
    return CostEstimate(
        model=usage.model,
        amount_usd=total,
        breakdown={
            "prompt": prompt_cost,
            "completion": completion_cost,
            "embedding": embedding_cost,
            "cache_read": cache_read_cost,
            "cache_write": cache_write_cost,
        },
    )

GetReportUseCase

Python
GetReportUseCase(repository)
Source code in apogee_ai_cost/application/use_cases/get_report_use_case.py
Python
def __init__(self, repository) -> None:
    self._repo = repository

execute async

Python
execute(tenant_id: str | None = None, fmt: str = 'json') -> str
Source code in apogee_ai_cost/application/use_cases/get_report_use_case.py
Python
async def execute(self, tenant_id: str | None = None, fmt: str = "json") -> str:
    entries = await self._repo.list_by_tenant(tenant_id)
    report = CostReport(entries)
    if fmt == "json":
        return JsonReportFormatter().format(report)
    if fmt == "markdown":
        return MarkdownReportFormatter().format(report)
    raise ValueError(f"unknown report format: {fmt!r}")

RecordUsageUseCase

Python
RecordUsageUseCase(pricing_table, repository, budget_tracker=None)

Records token usage: estimates cost, persists entry, updates budget.

Source code in apogee_ai_cost/application/use_cases/record_usage_use_case.py
Python
def __init__(self, pricing_table, repository, budget_tracker=None) -> None:
    from .estimate_cost_use_case import EstimateCostUseCase

    self._table = pricing_table
    self._repo = repository
    self._tracker = budget_tracker
    self._estimate = EstimateCostUseCase(pricing_table)

execute async

Python
execute(usage: TokenUsage) -> CostEntry
Source code in apogee_ai_cost/application/use_cases/record_usage_use_case.py
Python
async def execute(self, usage: TokenUsage) -> CostEntry:
    estimate = await self._estimate.execute(usage)
    entry = CostEntry(
        model=usage.model,
        tenant_id=usage.tenant_id,
        amount_usd=estimate.amount_usd,
        prompt_tokens=usage.prompt_tokens,
        completion_tokens=usage.completion_tokens,
        metadata={
            "embedding_tokens": str(usage.embedding_tokens),
        },
    )
    await self._repo.add(entry)
    if self._tracker is not None and usage.tenant_id is not None:
        await self._tracker.record_spend(usage.tenant_id, estimate.amount_usd)
    return entry

Domain

Budget dataclass

Python
Budget(tenant_id: str, limit_usd: float, spent_usd: float = 0.0, currency: Currency = USD, alert_at_pct: float = 0.8)

tenant_id instance-attribute

Python
tenant_id: str

limit_usd instance-attribute

Python
limit_usd: float

spent_usd class-attribute instance-attribute

Python
spent_usd: float = 0.0

currency class-attribute instance-attribute

Python
currency: Currency = USD

alert_at_pct class-attribute instance-attribute

Python
alert_at_pct: float = 0.8

remaining_usd property

Python
remaining_usd: float

utilization property

Python
utilization: float

exceeded property

Python
exceeded: bool

warning property

Python
warning: bool

CostEntry dataclass

Python
CostEntry(model: str, tenant_id: str | None = None, amount_usd: float = 0.0, currency: Currency = USD, prompt_tokens: int = 0, completion_tokens: int = 0, timestamp_s: float = time(), id: str = (lambda: f'e-{hex[:8]}')(), metadata: dict[str, str] = dict())

Persisted record of a single chargeable event.

model instance-attribute

Python
model: str

tenant_id class-attribute instance-attribute

Python
tenant_id: str | None = None

amount_usd class-attribute instance-attribute

Python
amount_usd: float = 0.0

currency class-attribute instance-attribute

Python
currency: Currency = USD

prompt_tokens class-attribute instance-attribute

Python
prompt_tokens: int = 0

completion_tokens class-attribute instance-attribute

Python
completion_tokens: int = 0

timestamp_s class-attribute instance-attribute

Python
timestamp_s: float = field(default_factory=time)

id class-attribute instance-attribute

Python
id: str = field(default_factory=lambda: f'e-{hex[:8]}')

metadata class-attribute instance-attribute

Python
metadata: dict[str, str] = field(default_factory=dict)

CostEstimate dataclass

Python
CostEstimate(model: str, amount_usd: float = 0.0, currency: Currency = USD, breakdown: dict[str, float] = dict())

model instance-attribute

Python
model: str

amount_usd class-attribute instance-attribute

Python
amount_usd: float = 0.0

currency class-attribute instance-attribute

Python
currency: Currency = USD

breakdown class-attribute instance-attribute

Python
breakdown: dict[str, float] = field(default_factory=dict)

Currency

Bases: str, Enum

USD class-attribute instance-attribute

Python
USD = 'USD'

EUR class-attribute instance-attribute

Python
EUR = 'EUR'

BRL class-attribute instance-attribute

Python
BRL = 'BRL'

Money dataclass

Python
Money(amount: float, currency: Currency = USD)

amount instance-attribute

Python
amount: float

currency class-attribute instance-attribute

Python
currency: Currency = USD

PricingEntry dataclass

Python
PricingEntry(model: str, provider: Provider = UNKNOWN, prompt_per_1k_usd: float = 0.0, completion_per_1k_usd: float = 0.0, embedding_per_1k_usd: float = 0.0, cache_read_per_1k_usd: float = 0.0, cache_write_per_1k_usd: float = 0.0)

Pricing for one model. Rates expressed in USD per 1k tokens.

model instance-attribute

Python
model: str

provider class-attribute instance-attribute

Python
provider: Provider = UNKNOWN

prompt_per_1k_usd class-attribute instance-attribute

Python
prompt_per_1k_usd: float = 0.0

completion_per_1k_usd class-attribute instance-attribute

Python
completion_per_1k_usd: float = 0.0

embedding_per_1k_usd class-attribute instance-attribute

Python
embedding_per_1k_usd: float = 0.0

cache_read_per_1k_usd class-attribute instance-attribute

Python
cache_read_per_1k_usd: float = 0.0

cache_write_per_1k_usd class-attribute instance-attribute

Python
cache_write_per_1k_usd: float = 0.0

Provider

Bases: str, Enum

ANTHROPIC class-attribute instance-attribute

Python
ANTHROPIC = 'anthropic'

OPENAI class-attribute instance-attribute

Python
OPENAI = 'openai'

COHERE class-attribute instance-attribute

Python
COHERE = 'cohere'

MISTRAL class-attribute instance-attribute

Python
MISTRAL = 'mistral'

GOOGLE class-attribute instance-attribute

Python
GOOGLE = 'google'

LOCAL class-attribute instance-attribute

Python
LOCAL = 'local'

UNKNOWN class-attribute instance-attribute

Python
UNKNOWN = 'unknown'

TokenUsage dataclass

Python
TokenUsage(model: str, prompt_tokens: int = 0, completion_tokens: int = 0, embedding_tokens: int = 0, cache_read_tokens: int = 0, cache_write_tokens: int = 0, tenant_id: str | None = None)

model instance-attribute

Python
model: str

prompt_tokens class-attribute instance-attribute

Python
prompt_tokens: int = 0

completion_tokens class-attribute instance-attribute

Python
completion_tokens: int = 0

embedding_tokens class-attribute instance-attribute

Python
embedding_tokens: int = 0

cache_read_tokens class-attribute instance-attribute

Python
cache_read_tokens: int = 0

cache_write_tokens class-attribute instance-attribute

Python
cache_write_tokens: int = 0

tenant_id class-attribute instance-attribute

Python
tenant_id: str | None = None

total property

Python
total: int

Domain · Enums

TokenKind

Bases: str, Enum

PROMPT class-attribute instance-attribute

Python
PROMPT = 'prompt'

COMPLETION class-attribute instance-attribute

Python
COMPLETION = 'completion'

EMBEDDING class-attribute instance-attribute

Python
EMBEDDING = 'embedding'

CACHE_READ class-attribute instance-attribute

Python
CACHE_READ = 'cache_read'

CACHE_WRITE class-attribute instance-attribute

Python
CACHE_WRITE = 'cache_write'

Domain · Exceptions

BudgetExceededException

Python
BudgetExceededException(tenant: str, limit_usd: float, spent_usd: float)

Bases: CostError

Source code in apogee_ai_cost/domain/exceptions/cost_exceptions.py
Python
def __init__(self, tenant: str, limit_usd: float, spent_usd: float) -> None:
    super().__init__(
        f"Budget exceeded for {tenant!r}: ${spent_usd:.4f} / ${limit_usd:.4f}"
    )
    self.tenant = tenant
    self.limit_usd = limit_usd
    self.spent_usd = spent_usd

tenant instance-attribute

Python
tenant = tenant

limit_usd instance-attribute

Python
limit_usd = limit_usd

spent_usd instance-attribute

Python
spent_usd = spent_usd

CostError

Bases: Exception

Base for apogee-ai-cost errors.

PricingNotFoundException

Python
PricingNotFoundException(model: str)

Bases: CostError

Source code in apogee_ai_cost/domain/exceptions/cost_exceptions.py
Python
def __init__(self, model: str) -> None:
    super().__init__(f"No pricing entry for model {model!r}")
    self.model = model

model instance-attribute

Python
model = model

Domain · Protocols (ports)

IBudgetTracker

Bases: Protocol

set_budget async

Python
set_budget(tenant_id: str, limit_usd: float, alert_at_pct: float = 0.8) -> Budget
Source code in apogee_ai_cost/domain/services/i_budget_tracker.py
Python
async def set_budget(self, tenant_id: str, limit_usd: float, alert_at_pct: float = 0.8) -> Budget: ...

record_spend async

Python
record_spend(tenant_id: str, amount_usd: float) -> Budget
Source code in apogee_ai_cost/domain/services/i_budget_tracker.py
Python
async def record_spend(self, tenant_id: str, amount_usd: float) -> Budget: ...

get async

Python
get(tenant_id: str) -> Budget
Source code in apogee_ai_cost/domain/services/i_budget_tracker.py
Python
async def get(self, tenant_id: str) -> Budget: ...

ICostRepository

Bases: Protocol

add async

Python
add(entry: CostEntry) -> None
Source code in apogee_ai_cost/domain/services/i_cost_repository.py
Python
async def add(self, entry: CostEntry) -> None: ...

list_by_tenant async

Python
list_by_tenant(tenant_id: str | None = None) -> Iterable[CostEntry]
Source code in apogee_ai_cost/domain/services/i_cost_repository.py
Python
async def list_by_tenant(self, tenant_id: str | None = None) -> Iterable[CostEntry]: ...

total_usd async

Python
total_usd(tenant_id: str | None = None) -> float
Source code in apogee_ai_cost/domain/services/i_cost_repository.py
Python
async def total_usd(self, tenant_id: str | None = None) -> float: ...

IPricingTable

Bases: Protocol

get

Python
get(model: str) -> PricingEntry
Source code in apogee_ai_cost/domain/services/i_pricing_table.py
Python
def get(self, model: str) -> PricingEntry: ...

list

Python
list() -> list[PricingEntry]
Source code in apogee_ai_cost/domain/services/i_pricing_table.py
Python
def list(self) -> list[PricingEntry]: ...

ITokenCounter

Bases: Protocol

name instance-attribute

Python
name: str

count async

Python
count(text: str, model: str = '') -> int
Source code in apogee_ai_cost/domain/services/i_token_counter.py
Python
async def count(self, text: str, model: str = "") -> int: ...

Infrastructure

CostReport

Python
CostReport(entries: Iterable[CostEntry])

Aggregates a list of CostEntry into a tenant/model summary.

Source code in apogee_ai_cost/infrastructure/reports/cost_report.py
Python
def __init__(self, entries: Iterable[CostEntry]) -> None:
    self._entries = list(entries)

summarise

Python
summarise() -> dict
Source code in apogee_ai_cost/infrastructure/reports/cost_report.py
Python
def summarise(self) -> dict:
    by_tenant: dict[str, float] = defaultdict(float)
    by_model: dict[str, float] = defaultdict(float)
    for e in self._entries:
        by_tenant[e.tenant_id or "<anonymous>"] += e.amount_usd
        by_model[e.model] += e.amount_usd
    return {
        "total_usd": sum(e.amount_usd for e in self._entries),
        "entries": len(self._entries),
        "by_tenant": dict(by_tenant),
        "by_model": dict(by_model),
    }

InMemoryBudgetTracker

Python
InMemoryBudgetTracker(raise_on_exceed: bool = True)
Source code in apogee_ai_cost/infrastructure/budgets/in_memory_budget_tracker.py
Python
def __init__(self, raise_on_exceed: bool = True) -> None:
    self._budgets: dict[str, Budget] = {}
    self._raise_on_exceed = raise_on_exceed

name class-attribute instance-attribute

Python
name = 'in_memory'

set_budget async

Python
set_budget(tenant_id: str, limit_usd: float, alert_at_pct: float = 0.8) -> Budget
Source code in apogee_ai_cost/infrastructure/budgets/in_memory_budget_tracker.py
Python
async def set_budget(
    self, tenant_id: str, limit_usd: float, alert_at_pct: float = 0.8
) -> Budget:
    existing = self._budgets.get(tenant_id)
    spent = existing.spent_usd if existing else 0.0
    budget = Budget(
        tenant_id=tenant_id,
        limit_usd=limit_usd,
        spent_usd=spent,
        alert_at_pct=alert_at_pct,
    )
    self._budgets[tenant_id] = budget
    return budget

record_spend async

Python
record_spend(tenant_id: str, amount_usd: float) -> Budget
Source code in apogee_ai_cost/infrastructure/budgets/in_memory_budget_tracker.py
Python
async def record_spend(self, tenant_id: str, amount_usd: float) -> Budget:
    if amount_usd < 0:
        raise ValueError("amount_usd must be non-negative")
    if tenant_id not in self._budgets:
        # Untracked tenants accumulate without limit until set_budget.
        self._budgets[tenant_id] = Budget(
            tenant_id=tenant_id, limit_usd=float("inf"), spent_usd=amount_usd,
        )
        return self._budgets[tenant_id]
    b = self._budgets[tenant_id]
    new_spent = b.spent_usd + amount_usd
    updated = replace(b, spent_usd=new_spent)
    self._budgets[tenant_id] = updated
    if updated.exceeded and self._raise_on_exceed and updated.limit_usd != float("inf"):
        raise BudgetExceededException(
            tenant=tenant_id,
            limit_usd=updated.limit_usd,
            spent_usd=updated.spent_usd,
        )
    return updated

get async

Python
get(tenant_id: str) -> Budget
Source code in apogee_ai_cost/infrastructure/budgets/in_memory_budget_tracker.py
Python
async def get(self, tenant_id: str) -> Budget:
    if tenant_id not in self._budgets:
        return Budget(tenant_id=tenant_id, limit_usd=float("inf"))
    return self._budgets[tenant_id]

InMemoryCostRepository

Python
InMemoryCostRepository()
Source code in apogee_ai_cost/infrastructure/registries/in_memory_cost_repository.py
Python
def __init__(self) -> None:
    self._entries: list[CostEntry] = []

name class-attribute instance-attribute

Python
name = 'in_memory'

add async

Python
add(entry: CostEntry) -> None
Source code in apogee_ai_cost/infrastructure/registries/in_memory_cost_repository.py
Python
async def add(self, entry: CostEntry) -> None:
    self._entries.append(entry)

list_by_tenant async

Python
list_by_tenant(tenant_id: str | None = None) -> Iterable[CostEntry]
Source code in apogee_ai_cost/infrastructure/registries/in_memory_cost_repository.py
Python
async def list_by_tenant(self, tenant_id: str | None = None) -> Iterable[CostEntry]:
    if tenant_id is None:
        return list(self._entries)
    return [e for e in self._entries if e.tenant_id == tenant_id]

total_usd async

Python
total_usd(tenant_id: str | None = None) -> float
Source code in apogee_ai_cost/infrastructure/registries/in_memory_cost_repository.py
Python
async def total_usd(self, tenant_id: str | None = None) -> float:
    if tenant_id is None:
        return sum(e.amount_usd for e in self._entries)
    return sum(e.amount_usd for e in self._entries if e.tenant_id == tenant_id)

JsonPricingLoader

Loads a pricing table from a JSON file with a list of entries.

name class-attribute instance-attribute

Python
name = 'json'

load

Python
load(path: str | Path) -> PricingTable
Source code in apogee_ai_cost/infrastructure/pricing/json_pricing_loader.py
Python
def load(self, path: str | Path) -> PricingTable:
    path = Path(path)
    payload = json.loads(path.read_text(encoding="utf-8"))
    entries: list[PricingEntry] = []
    for item in payload:
        entries.append(
            PricingEntry(
                model=item["model"],
                provider=Provider(item.get("provider", "unknown")),
                prompt_per_1k_usd=float(item.get("prompt_per_1k_usd", 0.0)),
                completion_per_1k_usd=float(item.get("completion_per_1k_usd", 0.0)),
                embedding_per_1k_usd=float(item.get("embedding_per_1k_usd", 0.0)),
                cache_read_per_1k_usd=float(item.get("cache_read_per_1k_usd", 0.0)),
                cache_write_per_1k_usd=float(item.get("cache_write_per_1k_usd", 0.0)),
            )
        )
    return PricingTable(entries)

JsonReportFormatter

name class-attribute instance-attribute

Python
name = 'json'

format

Python
format(report: CostReport) -> str
Source code in apogee_ai_cost/infrastructure/reports/cost_report.py
Python
def format(self, report: CostReport) -> str:
    return json.dumps(report.summarise(), indent=2, default=str)

MarkdownReportFormatter

name class-attribute instance-attribute

Python
name = 'markdown'

format

Python
format(report: CostReport) -> str
Source code in apogee_ai_cost/infrastructure/reports/cost_report.py
Python
def format(self, report: CostReport) -> str:
    s = report.summarise()
    lines = ["# Cost Report", ""]
    lines.append(f"- **Total**: ${s['total_usd']:.6f}")
    lines.append(f"- **Entries**: {s['entries']}")
    lines.append("")
    lines.append("## By tenant")
    lines.append("")
    for tenant, amount in sorted(s["by_tenant"].items(), key=lambda kv: -kv[1]):
        lines.append(f"- `{tenant}`: ${amount:.6f}")
    lines.append("")
    lines.append("## By model")
    lines.append("")
    for model, amount in sorted(s["by_model"].items(), key=lambda kv: -kv[1]):
        lines.append(f"- `{model}`: ${amount:.6f}")
    return "\n".join(lines)

PricingTable

Python
PricingTable(entries: Iterable[PricingEntry] = ())
Source code in apogee_ai_cost/infrastructure/pricing/pricing_table.py
Python
def __init__(self, entries: Iterable[PricingEntry] = ()) -> None:
    self._entries: dict[str, PricingEntry] = {e.model: e for e in entries}

builtin classmethod

Python
builtin() -> 'PricingTable'
Source code in apogee_ai_cost/infrastructure/pricing/pricing_table.py
Python
@classmethod
def builtin(cls) -> "PricingTable":
    return cls(builtin_entries())

register

Python
register(entry: PricingEntry) -> None
Source code in apogee_ai_cost/infrastructure/pricing/pricing_table.py
Python
def register(self, entry: PricingEntry) -> None:
    self._entries[entry.model] = entry

get

Python
get(model: str) -> PricingEntry
Source code in apogee_ai_cost/infrastructure/pricing/pricing_table.py
Python
def get(self, model: str) -> PricingEntry:
    if model not in self._entries:
        raise PricingNotFoundException(model)
    return self._entries[model]

list

Python
list() -> list[PricingEntry]
Source code in apogee_ai_cost/infrastructure/pricing/pricing_table.py
Python
def list(self) -> list[PricingEntry]:
    return list(self._entries.values())

TiktokenCounter

Python
TiktokenCounter(default_encoding: str = 'cl100k_base')

Lazy tiktoken adapter — install via extras=tiktoken.

Source code in apogee_ai_cost/infrastructure/counters/tiktoken_counter.py
Python
def __init__(self, default_encoding: str = "cl100k_base") -> None:
    self._default_encoding = default_encoding
    self._cache: dict[str, object] = {}

name class-attribute instance-attribute

Python
name = 'tiktoken'

count async

Python
count(text: str, model: str = '') -> int
Source code in apogee_ai_cost/infrastructure/counters/tiktoken_counter.py
Python
async def count(self, text: str, model: str = "") -> int:
    if not text:
        return 0
    encoder = self._get_encoder(model)
    return len(encoder.encode(text))  # type: ignore[no-any-return]

WhitespaceTokenCounter

CI-safe heuristic. Splits on whitespace and applies a 0.75 BPE adjustment.

Real tokenizers (tiktoken) cost network/dependency. This is good enough for budgeting estimates within ~10-20%.

name class-attribute instance-attribute

Python
name = 'whitespace'

count async

Python
count(text: str, model: str = '') -> int
Source code in apogee_ai_cost/infrastructure/counters/whitespace_counter.py
Python
async def count(self, text: str, model: str = "") -> int:
    if not text:
        return 0
    words = len(_WS.findall(text))
    return max(1, int(round(words / 0.75)))

builtin_entries

Python
builtin_entries() -> tuple[PricingEntry, ...]
Source code in apogee_ai_cost/infrastructure/pricing/builtin_pricing.py
Python
def builtin_entries() -> tuple[PricingEntry, ...]:
    return _BUILTIN