Class: TurnKit::Budget

Inherits:
Object
  • Object
show all
Defined in:
lib/turnkit/budget.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max_iterations:, timeout:, max_depth:, max_tool_executions:, cost_limit: nil, root_started_at: Clock.now) ⇒ Budget

Returns a new instance of Budget.



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/turnkit/budget.rb', line 7

def initialize(max_iterations:, timeout:, max_depth:, max_tool_executions:, cost_limit: nil, root_started_at: Clock.now)
  @root_started_at = root_started_at
  @max_iterations = max_iterations
  @timeout = timeout
  @max_depth = max_depth
  @max_tool_executions = max_tool_executions
  @cost_limit = cost_limit
  @iterations = 0
  @tool_executions = 0
  @cost = 0
  @mutex = Mutex.new
end

Instance Attribute Details

#cost_limitObject (readonly)

Returns the value of attribute cost_limit.



5
6
7
# File 'lib/turnkit/budget.rb', line 5

def cost_limit
  @cost_limit
end

#max_depthObject (readonly)

Returns the value of attribute max_depth.



5
6
7
# File 'lib/turnkit/budget.rb', line 5

def max_depth
  @max_depth
end

#max_iterationsObject (readonly)

Returns the value of attribute max_iterations.



5
6
7
# File 'lib/turnkit/budget.rb', line 5

def max_iterations
  @max_iterations
end

#max_tool_executionsObject (readonly)

Returns the value of attribute max_tool_executions.



5
6
7
# File 'lib/turnkit/budget.rb', line 5

def max_tool_executions
  @max_tool_executions
end

#root_started_atObject (readonly)

Returns the value of attribute root_started_at.



5
6
7
# File 'lib/turnkit/budget.rb', line 5

def root_started_at
  @root_started_at
end

#timeoutObject (readonly)

Returns the value of attribute timeout.



5
6
7
# File 'lib/turnkit/budget.rb', line 5

def timeout
  @timeout
end

Instance Method Details

#add_usage!(usage) ⇒ Object



34
35
36
37
38
39
40
41
# File 'lib/turnkit/budget.rb', line 34

def add_usage!(usage)
  return unless usage&.cost && cost_limit

  @mutex.synchronize do
    @cost += usage.cost.to_f
    raise Error, "cost limit reached" if @cost > cost_limit
  end
end

#check!(depth:) ⇒ Object

Raises:



43
44
45
46
# File 'lib/turnkit/budget.rb', line 43

def check!(depth:)
  raise Error, "maximum sub-agent depth reached" if max_depth && depth > max_depth
  raise Error, "turn timed out" if timeout && Clock.now >= root_started_at + timeout
end

#count_iteration!Object



20
21
22
23
24
25
# File 'lib/turnkit/budget.rb', line 20

def count_iteration!
  @mutex.synchronize do
    @iterations += 1
    raise Error, "maximum iterations reached" if max_iterations && @iterations > max_iterations
  end
end

#count_tool_execution!Object



27
28
29
30
31
32
# File 'lib/turnkit/budget.rb', line 27

def count_tool_execution!
  @mutex.synchronize do
    @tool_executions += 1
    raise Error, "maximum tool executions reached" if max_tool_executions && @tool_executions > max_tool_executions
  end
end