Class: Typesafe::Usage

Inherits:
Object
  • Object
show all
Defined in:
lib/typesafe/usage.rb

Overview

Token usage for one evaluation request.

Typesafe::Usage.new(input_tokens: 296, output_tokens: 20)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input_tokens:, output_tokens:) ⇒ Usage

Returns a new instance of Usage.

Parameters:

  • input_tokens (Integer)

    the number of input tokens.

  • output_tokens (Integer)

    the number of output tokens.

Raises:

  • (ArgumentError)

    if a token count is not a non-negative Integer.



17
18
19
20
21
# File 'lib/typesafe/usage.rb', line 17

def initialize(input_tokens:, output_tokens:)
  @input_tokens = validate_token_count(input_tokens, "input_tokens")
  @output_tokens = validate_token_count(output_tokens, "output_tokens")
  freeze
end

Instance Attribute Details

#input_tokensInteger (readonly)

Returns the number of input tokens.

Returns:

  • (Integer)

    the number of input tokens.



9
10
11
# File 'lib/typesafe/usage.rb', line 9

def input_tokens
  @input_tokens
end

#output_tokensInteger (readonly)

Returns the number of output tokens.

Returns:

  • (Integer)

    the number of output tokens.



12
13
14
# File 'lib/typesafe/usage.rb', line 12

def output_tokens
  @output_tokens
end

Class Method Details

.from_h(hash) ⇒ Usage

Parameters:

  • hash (Hash)

    a usage entry from the API response, with String or Symbol keys.

Returns:

Raises:

  • (ArgumentError)

    if hash is not a Hash or a token count is missing or invalid.



28
29
30
31
32
33
34
35
36
37
# File 'lib/typesafe/usage.rb', line 28

def self.from_h(hash)
  unless hash.is_a?(Hash)
    raise ArgumentError, "usage must be a Hash, got #{hash.inspect}"
  end

  new(
    input_tokens: hash["input_tokens"] || hash[:input_tokens],
    output_tokens: hash["output_tokens"] || hash[:output_tokens]
  )
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?

Usages compare equal when their token counts match.



45
46
47
# File 'lib/typesafe/usage.rb', line 45

def ==(other)
  other.class == self.class && other.to_h == to_h
end

#hashObject



50
51
52
# File 'lib/typesafe/usage.rb', line 50

def hash
  [self.class, to_h].hash
end

#to_hHash

Returns the usage shape returned by the TypeSafe API.

Returns:

  • (Hash)

    the usage shape returned by the TypeSafe API.



40
41
42
# File 'lib/typesafe/usage.rb', line 40

def to_h
  { input_tokens: input_tokens, output_tokens: output_tokens }
end