Class: Ask::TokenUsage::Activity

Inherits:
Object
  • Object
show all
Defined in:
lib/ask/token_usage/activity.rb

Overview

A named activity with a token cost.

Ask::TokenUsage.activity(:document_render, cost: 10)
Ask::TokenUsage.activity(:chat_message) do |params|
Ask::TokenUsage.count_tokens(params[:input]) + ...
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, cost: nil, &block) ⇒ Activity

Returns a new instance of Activity.

Raises:

  • (ArgumentError)


15
16
17
18
19
20
21
# File 'lib/ask/token_usage/activity.rb', line 15

def initialize(name, cost: nil, &block)
  raise ArgumentError, "activity #{name.inspect} needs a cost or a block" if cost.nil? && block.nil?

  @name = name.to_sym
  @cost = cost
  @block = block
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



13
14
15
# File 'lib/ask/token_usage/activity.rb', line 13

def name
  @name
end

Instance Method Details

#cost(params = {}) ⇒ Object

The token cost of running this activity with params. Always returns an Integer, rounded per configuration. A fixed cost ignores params; a block receives them (zero-arity blocks are called with no arguments).



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/ask/token_usage/activity.rb', line 26

def cost(params = {})
  raw = if @block
          @block.arity.zero? ? @block.call : @block.call(params)
        elsif @cost.respond_to?(:call)
          @cost.arity.zero? ? @cost.call : @cost.call(params)
        else
          @cost
        end

  Ask::TokenUsage.config.round(raw)
end

#inspectObject



42
43
44
# File 'lib/ask/token_usage/activity.rb', line 42

def inspect
  to_s
end

#to_sObject



38
39
40
# File 'lib/ask/token_usage/activity.rb', line 38

def to_s
  "Activity(#{@name})"
end