33 lines
1.5 KiB
Python
33 lines
1.5 KiB
Python
"""The tokens a message's usage counts, by kind."""
|
|
import dataclasses
|
|
|
|
from claude_code.entries import usage_count
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Tokens:
|
|
"""Raw token counts by kind. Claude Code's usage doesn't count thinking apart from output, so output holds both."""
|
|
input: int = 0
|
|
write_5m: int = 0
|
|
write_1h: int = 0
|
|
read: int = 0
|
|
output: int = 0
|
|
|
|
def context(self) -> int:
|
|
"""The tokens of the prompt the message answered: its context."""
|
|
return self.input + self.write_5m + self.write_1h + self.read
|
|
|
|
def plus(self, other: "Tokens") -> "Tokens":
|
|
return Tokens(*(mine + theirs for mine, theirs in zip(dataclasses.astuple(self), dataclasses.astuple(other))))
|
|
|
|
|
|
# {"input_tokens": 2, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 25919}, "cache_read_input_tokens": 10365, "output_tokens": 193, ...}
|
|
def tokens_of(usage: object) -> Tokens:
|
|
"""The tokens of one message's usage, or of a json reply's; none where it is no object."""
|
|
if not isinstance(usage, dict):
|
|
return Tokens()
|
|
written = usage.get("cache_creation")
|
|
# A write without the split by lifetime counts as a five-minute one.
|
|
five, hour = (usage_count(written, "ephemeral_5m_input_tokens"), usage_count(written, "ephemeral_1h_input_tokens")) if isinstance(written, dict) else (usage_count(usage, "cache_creation_input_tokens"), 0)
|
|
return Tokens(usage_count(usage, "input_tokens"), five, hour, usage_count(usage, "cache_read_input_tokens"), usage_count(usage, "output_tokens"))
|