class RubyLLM::ActiveRecord::Usage
One provider attempt in RubyLLM’s usage ledger, the ruby_llm_usages table. RubyLLM writes a row for every billable attempt, including retries, cancelled streams, and one-shot operations without a chat. A write that fails is logged and skipped, so it never breaks the operation.
chat.ruby_llm_usages.sum(:total_cost) RubyLLM::ActiveRecord::Usage.where(owner: current_user).group(:operation).sum(:total_cost)
Each row has optional polymorphic chat, message, and owner associations. The chronological scope orders rows oldest first. Its columns:
operation-
What ran:
"chat","embedding","image","speech","transcription", and so on. provider-
The provider’s slug.
model-
The model the provider ran, or its own resource identifier.
status-
"pending","succeeded","failed", or"cancelled". input_tokens,output_tokens,cache_read_tokens,cache_write_tokens,thinking_tokens-
Token counts, in the bucket the provider bills each at.
characters,audio_seconds,search_units-
Units billed instead of tokens.
server_tool_use-
Counts of provider-run tool calls, as a Hash.
input_cost,output_cost,cache_read_cost,cache_write_cost,thinking_cost-
The cost of each token bucket, frozen when the attempt finished.
characters_cost,audio_seconds_cost,search_units_cost-
The cost of each unit.
total_cost-
The attempt’s total cost, or
nilwhen it is unknown. workflow_id,workflow_name,workflow_step_id,workflow_step_name-
The workflow and step that made the attempt, if any.
RubyLLM writes these rows. Read and query them, and add scopes and columns of your own, but do not create or update them.
Public Instance Methods
Source
# File lib/ruby_llm/active_record/usage.rb, line 131 def cost recorded = { input: input_cost, output: output_cost, cache_read: cache_read_cost, cache_write: cache_write_cost, thinking: thinking_cost, **recorded_units(suffix: '_cost'), total: total_cost }.compact RubyLLM::Cost.from_h(recorded, tokens: tokens) end
Returns the attempt’s frozen cost as RubyLLM::Cost.
Source
# File lib/ruby_llm/active_record/usage.rb, line 118 def tokens RubyLLM::Tokens.new( input: input_tokens, output: output_tokens, cache_read: cache_read_tokens, cache_write: cache_write_tokens, thinking: thinking_tokens, **recorded_units, server_tool_use: (self[:server_tool_use] if has_attribute?(:server_tool_use)) ) end
Returns the attempt’s counts as RubyLLM::Tokens.