Module: LlmCostTracker::Integrations::Anthropic

Extended by:
Base
Defined in:
lib/llm_cost_tracker/integrations/anthropic.rb

Defined Under Namespace

Modules: MessagesPatch

Class Method Summary collapse

Methods included from Base

active?, constant, elapsed_ms, enforce_budget!, install, record_safely, request_params, status

Class Method Details

.hidden_output_tokens(usage) ⇒ Object



52
53
54
55
56
57
# File 'lib/llm_cost_tracker/integrations/anthropic.rb', line 52

def hidden_output_tokens(usage)
  ObjectReader.integer(
    ObjectReader.first(usage, :thinking_tokens, :thinking_output_tokens) ||
    ObjectReader.nested(usage, :output_tokens_details, :reasoning_tokens)
  )
end

.integration_nameObject



11
# File 'lib/llm_cost_tracker/integrations/anthropic.rb', line 11

def integration_name = :anthropic

.record_message(message, request:, latency_ms:) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/llm_cost_tracker/integrations/anthropic.rb', line 20

def record_message(message, request:, latency_ms:)
  return unless active?

  record_safely do
    usage = ObjectReader.first(message, :usage)
    next unless usage

    input_tokens = ObjectReader.first(usage, :input_tokens)
    output_tokens = ObjectReader.first(usage, :output_tokens)
    next if input_tokens.nil? && output_tokens.nil?

    LlmCostTracker::Tracker.record(
      provider: "anthropic",
      model: ObjectReader.first(message, :model) || request[:model],
      input_tokens: ObjectReader.integer(input_tokens),
      output_tokens: ObjectReader.integer(output_tokens),
      latency_ms: latency_ms,
      usage_source: :sdk_response,
      provider_response_id: ObjectReader.first(message, :id),
      metadata: (usage)
    )
  end
end

.target_patchesObject



13
14
15
16
17
18
# File 'lib/llm_cost_tracker/integrations/anthropic.rb', line 13

def target_patches
  [
    [constant("Anthropic::Resources::Messages"), MessagesPatch],
    [constant("Anthropic::Resources::Beta::Messages"), MessagesPatch]
  ]
end

.usage_metadata(usage) ⇒ Object



44
45
46
47
48
49
50
# File 'lib/llm_cost_tracker/integrations/anthropic.rb', line 44

def (usage)
  {
    cache_read_input_tokens: ObjectReader.integer(ObjectReader.first(usage, :cache_read_input_tokens)),
    cache_write_input_tokens: ObjectReader.integer(ObjectReader.first(usage, :cache_creation_input_tokens)),
    hidden_output_tokens: hidden_output_tokens(usage)
  }
end