Class: Brute::Middleware::Loop

Inherits:
Object
  • Object
show all
Defined in:
lib/brute/middleware/006_loop.rb

Overview

Re-invokes the inner stack as long as a condition holds — a generic loop over a turn. The condition is a proc or block that receives env and returns truthy to send control back down the chain again, falsy to stop.

The inner app always runs at least once; the condition is checked after each pass (do-while).

# loop while the last message is a tool result (see Loop::ToolResult):
use Brute::Middleware::Loop, ->(env) { env[:messages].last&.role == :tool }

# block form — e.g. bump an iteration counter and stop on should_exit:
use Brute::Middleware::Loop do |env|
env[:current_iteration] += 1
!env[:should_exit] && env[:messages].last&.role == :tool
end

Defined Under Namespace

Classes: ToolResult

Instance Method Summary collapse

Constructor Details

#initialize(app, condition = nil, &block) ⇒ Loop

Returns a new instance of Loop.



25
26
27
28
29
30
31
# File 'lib/brute/middleware/006_loop.rb', line 25

def initialize(app, condition = nil, &block)
  @app       = app
  @condition = condition || block
  unless @condition.respond_to?(:call)
    raise ArgumentError, "Brute::Middleware::Loop requires a proc or block condition"
  end
end

Instance Method Details

#call(env) ⇒ Object



33
34
35
36
37
38
39
# File 'lib/brute/middleware/006_loop.rb', line 33

def call(env)
  loop do
    @app.call(env)
    break unless @condition.call(env)
  end
  env
end