TokenLens

repository·main·Indexed 42 days ago

https://github.com/xn1cklas/tokenlens

A utility library for managing AI model metadata, context window limits, and cost estimation. It provides tools to fetch model catalogs from models.dev, resolve model aliases via a registry, and calculate token costs and context caps using packages like @tokenlens/core, @tokenlens/fetch, @tokenlens/helpers, and @tokenlens/models.

Tokens
20.8K
Snippets
72
Records
96
Agent score
53%

What's inside TokenLens

  1. Quick Start with TokenLens

    main

    TokenLens provides utilities to manage model metadata, context limits, and cost estimation. You can fetch model providers and then use helpers to calculate context caps, costs, or combined usage data.

    Note that ID normalization is automatic: you can use provider/model, provider:id, or just the model name. Version dots are automatically normalized to dashes (e.g., claude-3.5-haiku becomes claude-3-5-haiku).

    import { fetchModels } from 'tokenlens';
    import { getContext, getTokenCosts, getUsage } from '@tokenlens/helpers';
    
    // 1) Get providers
    const openai = await fetchModels('openai');
    
    // 2) Define model and usage
    const modelId = 'openai/gpt-4o-mini';
    const usage = { prompt_tokens: 3200, completion_tokens: 400 };
    
    // Context caps
    const { maxInput, maxOutput, maxTotal } = getContext(modelId, openai);
    
    // Cost breakdown
    const { 
      inputUSD, 
      outputUSD, 
      totalUSD 
    } = getTokenCosts(modelId, usage, openai);
    
    // Or both together
    const usageData = getUsage(modelId, usage, openai);
    
    console.log({ maxInput, maxOutput, maxTotal, inputUSD, outputUSD, totalUSD, usageData });
  2. Use @tokenlens/helpers for context and cost estimation

    main

    The @tokenlens/helpers package provides utilities for calculating context window limits and estimating token costs.

    Dependency Injection Pattern: These helpers are DI-first. You must pass a providers object to the functions. You can obtain this object by calling fetchModels() from the tokenlens package (for dynamic provider data) or getModels() (for a static set).

    Core Functions:

    • getContext({ modelId, providers }): Returns context window limits.
    • getTokenCosts({ modelId, usage, providers }): Returns estimated costs for input, output, reasoning, and caching.
    • getUsage({ modelId, usage, providers, reserveOutput? }): Returns a combined usage summary.

    Model ID Formats: Model IDs can be specified as provider/model, provider:id, or a providerless model. Note that version dots (e.g., 1.5) are normalized to dashes (e.g., 1-5) in the model segment.

    import { fetchModels } from 'tokenlens';
    import { getContext, getTokenCosts, getUsage } from '@tokenlens/helpers';
    
    const openai = await fetchModels('openai');
    const modelId = 'openai/gpt-4o-mini';
    const usage = { prompt_tokens: 1000, completion_tokens: 500 };
    
    // Get context window limits
    const { maxInput, maxOutput, maxTotal } = getContext(modelId, openai);
    
    // Get estimated costs
    const {
      inputUSD,
      outputUSD,
      reasoningUSD,
      cacheReadUSD,
      cacheWriteUSD,
      totalUSD,
    } = getTokenCosts(modelId, usage, openai);
    
    // Get combined usage summary
    const summary = getUsage(modelId, usage, openai);
  3. Install @tokenlens/models

    main

    You can install the @tokenlens/models package using your preferred package manager. This package provides tree-shakeable static exports of the models.dev catalog, organized by provider.

    npm i @tokenlens/models
    # or
    pnpm add @tokenlens/models
    # or
    yarn add @tokenlens/models
  4. Use the tokenlens package as a unified entrypoint

    main

    The tokenlens package acts as an aggregator for the TokenLens ecosystem. It re-exports the core logic from @tokenlens/core and @tokenlens/fetch, provides utility builders from @tokenlens/helpers, and includes convenience wrappers for managing context, conversations, and sources.

    For most use cases, you can import everything you need from the single tokenlens entrypoint. However, advanced users can still import directly from the scoped packages (like @tokenlens/helpers) to avoid name conflicts or to access utilities not exposed via the tokenlens wrappers.

  5. Normalize token usage data

    main

    TokenLens provides types to handle usage data from various SDKs and providers. You can work with raw usage shapes or normalized structures.

    • UsageLike: A partial record of common token field names (e.g., prompt_tokens, completionTokens, totalTokens) used to ingest data from different provider SDKs.
    • NormalizedUsage: A provider-agnostic structure used by helpers, containing input, output, and an optional total.
    • TokenBreakdown: An extended version of NormalizedUsage that includes cacheReads, cacheWrites, and reasoningTokens for more granular analysis.
    export type UsageLike = Partial<
      Record<
        | "prompt_tokens"
        | "completion_tokens"
        | "total_tokens"
        | "input_tokens"
        | "output_tokens"
        | "reasoning_tokens"
        | "promptTokens"
        | "completionTokens"
        | "totalTokens"
        | "reasoningTokens",
        number
      >
    >;
    
    export type NormalizedUsage = {
      input: number;
      output: number;
      total?: number;
    };
    
    export type TokenBreakdown = NormalizedUsage & {
      cacheReads?: number;
      cacheWrites?: number;
      reasoningTokens?: number;
    };
  6. How to manage model catalogs in TokenLens

    main

    TokenLens uses a ModelCatalog to understand model capabilities like context windows and token costs. While the tokenlens package provides a defaultCatalog for backwards compatibility, you should explicitly pass a catalog to ensure accuracy and avoid relying on bundled defaults.

    To get the most accurate results, use one of the following methods to obtain a catalog:

    • Live Catalog: Fetch a live catalog using fetchModels() from @tokenlens/fetch.
    • Static Catalog: Build a static catalog using getModels() from @tokenlens/models.

    When calling core functions like getContext, getUsage, or getTokenCosts, pass this catalog via the providers or catalog option.