Skip to content

automaton.usage

WARNING

This documentation is almost entirely "vibe coded"; while a helpful resource for humans and agents to understand this codebase, it should not be considered a source of ground truth in the way documentation normally is, and the user is responsible for verifying that all instructions given here are safe.

automaton.usage

Usage normalization, accounting, and aggregation for Automaton.

normalize_usage

normalize_usage(endpoint: str, response_json: dict[str, Any]) -> dict[str, Any] | None

Normalize a provider's usage object into Automaton's token buckets.

The API shape is selected from the request path, ignoring any query string. Four shapes are recognized:

  • OpenAI Responses (/responses) and Chat Completions (/chat/completions). Cache reads are counted inside the prompt token total, so they are subtracted to get the uncached remainder.
  • Anthropic Messages (/messages). Cache reads and writes are reported as buckets separate from input_tokens, so they are added instead. There is no total, so it is derived; thinking tokens are a subset of output_tokens, matching how they are billed. The cache-write TTL is inferred from the per-window cache_creation breakdown when unambiguous, since the windows are priced differently.
  • Bedrock-style camelCase (inputTokens/outputTokens), matched on the payload shape rather than the path.

Parameters:

Name Type Description Default
endpoint str

Request path as seen by the proxy, e.g. /v1/messages?beta=true.

required
response_json dict[str, Any]

Parsed response body, or for a streamed response the payload assembled by the proxy's event-stream decoder.

required

Returns:

Type Description
dict[str, Any] | None

Normalized token buckets, or None when the response carries no usage object or the shape is not recognized (accounted as not_applicable rather than as an error).

Raises:

Type Description
ValueError

If a usage object is present but internally inconsistent, e.g. missing required counts, negative counts, or cache reads exceeding the input.

Examples:

>>> normalize_usage(
...     "/v1/messages",
...     {"usage": {"input_tokens": 10, "output_tokens": 4}},
... )["total_tokens"]
14
Source code in automaton/usage.py
def normalize_usage(endpoint: str, response_json: dict[str, Any]) -> dict[str, Any] | None:
    """Normalize a provider's usage object into Automaton's token buckets.

    The API shape is selected from the request path, ignoring any query string.
    Four shapes are recognized:

    - **OpenAI Responses** (``/responses``) and **Chat Completions**
      (``/chat/completions``). Cache reads are counted *inside* the prompt token
      total, so they are subtracted to get the uncached remainder.
    - **Anthropic Messages** (``/messages``). Cache reads and writes are
      reported as buckets *separate* from ``input_tokens``, so they are added
      instead. There is no total, so it is derived; thinking tokens are a subset
      of ``output_tokens``, matching how they are billed. The cache-write TTL is
      inferred from the per-window ``cache_creation`` breakdown when
      unambiguous, since the windows are priced differently.
    - **Bedrock-style camelCase** (``inputTokens``/``outputTokens``), matched on
      the payload shape rather than the path.

    Parameters
    ----------
    endpoint : str
        Request path as seen by the proxy, e.g. ``/v1/messages?beta=true``.
    response_json : dict[str, Any]
        Parsed response body, or for a streamed response the payload assembled
        by the proxy's event-stream decoder.

    Returns
    -------
    dict[str, Any] | None
        Normalized token buckets, or ``None`` when the response carries no
        usage object or the shape is not recognized (accounted as
        ``not_applicable`` rather than as an error).

    Raises
    ------
    ValueError
        If a usage object is present but internally inconsistent, e.g. missing
        required counts, negative counts, or cache reads exceeding the input.

    Examples
    --------
    >>> normalize_usage(
    ...     "/v1/messages",
    ...     {"usage": {"input_tokens": 10, "output_tokens": 4}},
    ... )["total_tokens"]
    14
    """
    usage = response_json.get("usage")
    if not usage:
        return None
    if not isinstance(usage, dict):
        raise ValueError("malformed usage object: usage must be a mapping")

    cache_write_ttl = _extract_cache_write_ttl(response_json, usage)
    endpoint_path = _endpoint_path(endpoint)

    if endpoint_path.endswith("/responses"):
        input_tokens = _coerce_int(usage.get("input_tokens"))
        output_tokens = _coerce_int(usage.get("output_tokens"))
        total_tokens = _coerce_int(usage.get("total_tokens"))
        input_details = usage.get("input_tokens_details") or {}
        output_details = usage.get("output_tokens_details") or {}
        cache_read_tokens = _coerce_int(input_details.get("cached_tokens"), default=0)
        cache_write_tokens = _coerce_int(input_details.get("cache_write_tokens"), default=0)
        reasoning_tokens = _coerce_int(output_details.get("reasoning_tokens"), default=0)

        # OpenAI counts cache reads inside `input_tokens`, so the uncached
        # remainder is the difference.
        input_tokens_standard = input_tokens - cache_read_tokens
        total_input_tokens = input_tokens + cache_write_tokens
        cache_keys_reported = "cached_tokens" in input_details or "cache_write_tokens" in input_details
    elif endpoint_path.endswith("/chat/completions"):
        input_tokens = _coerce_int(usage.get("prompt_tokens"))
        output_tokens = _coerce_int(usage.get("completion_tokens"))
        total_tokens = _coerce_int(usage.get("total_tokens"))
        input_details = usage.get("prompt_tokens_details") or {}
        output_details = usage.get("completion_tokens_details") or {}
        cache_read_tokens = _coerce_int(input_details.get("cached_tokens"), default=0)
        cache_write_tokens = _coerce_int(input_details.get("cache_write_tokens"), default=0)
        reasoning_tokens = _coerce_int(output_details.get("reasoning_tokens"), default=0)

        input_tokens_standard = input_tokens - cache_read_tokens
        total_input_tokens = input_tokens + cache_write_tokens
        cache_keys_reported = "cached_tokens" in input_details or "cache_write_tokens" in input_details
    elif endpoint_path.endswith("/messages"):
        # Anthropic Messages API. Unlike OpenAI, `input_tokens` counts only the
        # uncached prompt: cache reads and cache writes are reported as separate,
        # non-overlapping buckets, so they are added rather than subtracted.
        # There is no `total_tokens` field, so it is derived.
        input_tokens_standard = _coerce_int(usage.get("input_tokens"))
        cache_read_tokens = _coerce_int(usage.get("cache_read_input_tokens"), default=0)
        cache_write_tokens = _coerce_int(usage.get("cache_creation_input_tokens"), default=0)
        output_tokens = _coerce_int(usage.get("output_tokens"))
        output_details = usage.get("output_tokens_details") or {}
        # Extended thinking is billed as output; Anthropic reports it as a
        # subset of `output_tokens` rather than as an extra bucket.
        reasoning_tokens = _coerce_int(output_details.get("thinking_tokens"), default=0)

        total_input_tokens = input_tokens_standard + cache_read_tokens + cache_write_tokens
        total_tokens = total_input_tokens + output_tokens
        cache_keys_reported = (
            "cache_read_input_tokens" in usage or "cache_creation_input_tokens" in usage
        )
        if cache_write_ttl is None:
            cache_write_ttl = _infer_anthropic_cache_write_ttl(usage)
    elif all(key in usage for key in ["inputTokens", "outputTokens"]):
        input_tokens_standard = _coerce_int(usage.get("inputTokens"))
        cache_read_tokens = _coerce_int(usage.get("cacheReadInputTokens"), default=0)
        cache_write_tokens = _coerce_int(usage.get("cacheWriteInputTokens"), default=0)
        output_tokens = _coerce_int(usage.get("outputTokens"))
        total_input_tokens = input_tokens_standard + cache_read_tokens + cache_write_tokens
        total_tokens = _coerce_int(usage.get("totalTokens"), default=total_input_tokens + output_tokens)
        reasoning_tokens = _coerce_int(usage.get("reasoningTokens"), default=0)
        cache_keys_reported = False
    else:
        return None

    if input_tokens_standard < 0:
        raise ValueError("malformed usage object: cached input exceeds input")

    normalized = {
        "input_tokens_standard": input_tokens_standard,
        "input_tokens_cache_read": cache_read_tokens,
        "input_tokens_cache_write": cache_write_tokens,
        "output_tokens": output_tokens,
        "reasoning_tokens": reasoning_tokens,
        "total_input_tokens": total_input_tokens,
        "total_tokens": total_tokens,
        "raw_usage": usage,
        "cache_write_ttl": cache_write_ttl,
        "schema_anomaly": total_tokens != total_input_tokens + output_tokens,
        "cache_detail_available": (
            cache_read_tokens > 0
            or cache_write_tokens > 0
            or cache_keys_reported
            or "cacheWriteInputTokens" in usage
            or "cacheReadInputTokens" in usage
        ),
    }

    for key in TOKEN_KEYS:
        if normalized[key] < 0:
            raise ValueError("malformed usage object: negative token counts")
    if normalized["reasoning_tokens"] > normalized["output_tokens"]:
        raise ValueError("malformed usage object: reasoning exceeds output")

    return normalized