Skip to content

Usage

Sub classes

Name Children Inherits
ClaudeUsage
clawd_code_sdk.storage.models
Token usage from Claude API response, with additional storage fields.

    Base classes

    Name Children Inherits
    BaseModel
    pydantic.main
    !!! abstract "Usage Documentation"

    â‹” Inheritance diagram

    graph TD
      2143730855["usage.Usage"]
      3879467795["main.BaseModel"]
      2751680898["builtins.object"]
      3879467795 --> 2143730855
      2751680898 --> 3879467795

    🛈 DocStrings

    Bases: BaseModel

    Token usage counters.

    Used both for per-turn snapshots (on ResultMessage) and as an accumulator (on ClaudeSDKClient.query_usage / session_usage).

    Source code in src/clawd_code_sdk/models/usage.py
    class Usage(BaseModel):
        """Token usage counters.
    
        Used both for per-turn snapshots (on ResultMessage) and as an accumulator
        (on ClaudeSDKClient.query_usage / session_usage).
        """
    
        input_tokens: int = 0
        """The number of input tokens which were used."""
        output_tokens: int = 0
        """The number of output tokens which were used."""
        cache_creation_input_tokens: int = 0
        """The number of input tokens used to create the cache entry."""
        cache_read_input_tokens: int = 0
        """The number of input tokens read from the cache."""
        cache_creation: CacheCreationUsage | None = None
        """Cache-write tokens split by TTL."""
        server_tool_use: AgentServerToolUse | None = None
        """Server-side tool usage counters."""
        output_tokens_details: OutputTokensDetails | None = None
        """Breakdown of output tokens."""
        service_tier: str | None = None
        """Service tier the request was served on (e.g. "standard")."""
        inference_geo: str | None = None
        """Inference geography (e.g. "global")."""
        speed: str | None = None
        """Speed mode (e.g. "standard", "fast")."""
        iterations: list[UsageIteration] | None = None
        """Per-iteration usage for the turn."""
        fallback_credit: Any = None
        """Fallback credit info (may be null)."""
        model_config = ConfigDict(extra="forbid" if IS_DEV else "ignore", use_attribute_docstrings=True)
    
        @property
        def total_tokens(self) -> int:
            """Sum of all token fields."""
            return (
                self.input_tokens
                + self.output_tokens
                + self.cache_creation_input_tokens
                + self.cache_read_input_tokens
            )
    
        def accumulate(self, usage: Usage) -> None:
            """Add another Usage's values to this one."""
            self.input_tokens += usage.input_tokens
            self.output_tokens += usage.output_tokens
            self.cache_creation_input_tokens += usage.cache_creation_input_tokens
            self.cache_read_input_tokens += usage.cache_read_input_tokens
    
        def reset(self) -> None:
            """Reset all counters to zero."""
            self.input_tokens = 0
            self.output_tokens = 0
            self.cache_creation_input_tokens = 0
            self.cache_read_input_tokens = 0
    
        def to_otel(self, *, partial: bool = False) -> dict[str, int]:
            """Extract usage metrics from a Claude usage object or dict.
    
            Args:
                usage: A usage object or dict from the SDK.
                partial: If True, prefix attribute names with ``gen_ai.usage.partial.``
                    instead of ``gen_ai.usage.``. Used for chat spans where per-message
                    usage from the SDK is unreliable.
            """
            prefix = "gen_ai.usage.partial." if partial else "gen_ai.usage."
            result: dict[str, int] = {}
            # input_tokens is the *total* input token count.
            # The Anthropic API's input_tokens only counts uncached tokens,
            # so we sum input + cache_read + cache_creation to get the actual total.
            input_tokens = self.input_tokens
            cache_read = self.cache_read_input_tokens
            cache_creation = self.cache_creation_input_tokens
            if total_input := (input_tokens + cache_read + cache_creation):
                result[f"{prefix}input_tokens"] = total_input
    
            result[f"{prefix}output_tokens"] = self.output_tokens
    
            if cache_read:
                result[f"{prefix}cache_read.input_tokens"] = cache_read
            if cache_creation:
                result[f"{prefix}cache_creation.input_tokens"] = cache_creation
    
            return result
    

    cache_creation class-attribute instance-attribute

    cache_creation: CacheCreationUsage | None = None
    

    Cache-write tokens split by TTL.

    cache_creation_input_tokens class-attribute instance-attribute

    cache_creation_input_tokens: int = 0
    

    The number of input tokens used to create the cache entry.

    cache_read_input_tokens class-attribute instance-attribute

    cache_read_input_tokens: int = 0
    

    The number of input tokens read from the cache.

    fallback_credit class-attribute instance-attribute

    fallback_credit: Any = None
    

    Fallback credit info (may be null).

    inference_geo class-attribute instance-attribute

    inference_geo: str | None = None
    

    Inference geography (e.g. "global").

    input_tokens class-attribute instance-attribute

    input_tokens: int = 0
    

    The number of input tokens which were used.

    iterations class-attribute instance-attribute

    iterations: list[UsageIteration] | None = None
    

    Per-iteration usage for the turn.

    output_tokens class-attribute instance-attribute

    output_tokens: int = 0
    

    The number of output tokens which were used.

    output_tokens_details class-attribute instance-attribute

    output_tokens_details: OutputTokensDetails | None = None
    

    Breakdown of output tokens.

    server_tool_use class-attribute instance-attribute

    server_tool_use: AgentServerToolUse | None = None
    

    Server-side tool usage counters.

    service_tier class-attribute instance-attribute

    service_tier: str | None = None
    

    Service tier the request was served on (e.g. "standard").

    speed class-attribute instance-attribute

    speed: str | None = None
    

    Speed mode (e.g. "standard", "fast").

    total_tokens property

    total_tokens: int
    

    Sum of all token fields.

    accumulate

    accumulate(usage: Usage) -> None
    

    Add another Usage's values to this one.

    Source code in src/clawd_code_sdk/models/usage.py
    def accumulate(self, usage: Usage) -> None:
        """Add another Usage's values to this one."""
        self.input_tokens += usage.input_tokens
        self.output_tokens += usage.output_tokens
        self.cache_creation_input_tokens += usage.cache_creation_input_tokens
        self.cache_read_input_tokens += usage.cache_read_input_tokens
    

    reset

    reset() -> None
    

    Reset all counters to zero.

    Source code in src/clawd_code_sdk/models/usage.py
    def reset(self) -> None:
        """Reset all counters to zero."""
        self.input_tokens = 0
        self.output_tokens = 0
        self.cache_creation_input_tokens = 0
        self.cache_read_input_tokens = 0
    

    to_otel

    to_otel(*, partial: bool = False) -> dict[str, int]
    

    Extract usage metrics from a Claude usage object or dict.

    Parameters:

    Name Type Description Default
    usage

    A usage object or dict from the SDK.

    required
    partial bool

    If True, prefix attribute names with gen_ai.usage.partial. instead of gen_ai.usage.. Used for chat spans where per-message usage from the SDK is unreliable.

    False
    Source code in src/clawd_code_sdk/models/usage.py
    def to_otel(self, *, partial: bool = False) -> dict[str, int]:
        """Extract usage metrics from a Claude usage object or dict.
    
        Args:
            usage: A usage object or dict from the SDK.
            partial: If True, prefix attribute names with ``gen_ai.usage.partial.``
                instead of ``gen_ai.usage.``. Used for chat spans where per-message
                usage from the SDK is unreliable.
        """
        prefix = "gen_ai.usage.partial." if partial else "gen_ai.usage."
        result: dict[str, int] = {}
        # input_tokens is the *total* input token count.
        # The Anthropic API's input_tokens only counts uncached tokens,
        # so we sum input + cache_read + cache_creation to get the actual total.
        input_tokens = self.input_tokens
        cache_read = self.cache_read_input_tokens
        cache_creation = self.cache_creation_input_tokens
        if total_input := (input_tokens + cache_read + cache_creation):
            result[f"{prefix}input_tokens"] = total_input
    
        result[f"{prefix}output_tokens"] = self.output_tokens
    
        if cache_read:
            result[f"{prefix}cache_read.input_tokens"] = cache_read
        if cache_creation:
            result[f"{prefix}cache_creation.input_tokens"] = cache_creation
    
        return result
    

    :fa-brands-github: Show source on GitHub