Class: Brute::Middleware::MaxIterations

Inherits:
Base
  • Object
show all
Defined in:
lib/brute/middleware/010_max_iterations.rb

Overview

Guards against runaway tool loops by capping the number of iterations.

When the limit is reached, injects a user message into the session stating that maximum iterations have been reached. This causes Loop::ToolResult to exit its loop naturally (last message is not :tool).

Constant Summary collapse

DEFAULT_MAX_ITERATIONS =
100

Constants included from Hooks

Hooks::AFTER_LLM_EVENT, Hooks::AFTER_TOOL_EVENT, Hooks::APPROVE_TOOL_EVENT, Hooks::BEFORE_LLM_EVENT, Hooks::BEFORE_TOOL_EVENT, Hooks::COMPACTED_EVENT, Hooks::COMPACT_DURATION_EVENT, Hooks::DURATION_EVENT, Hooks::ENTER_EVENT, Hooks::EXIT_EVENT, Hooks::FARADAY_ERROR_EVENT, Hooks::LLM_DURATION_EVENT, Hooks::LLM_FAILURE_EVENT, Hooks::MIDDLEWARE_ADDED_EVENT, Hooks::OPEN_ROUTER_SERVER_ERROR_EVENT, Hooks::STANDARD_ERROR_EVENT, Hooks::TOOL_DURATION_EVENT, Hooks::TURN_DURATION_EVENT, Hooks::TURN_END_EVENT, Hooks::TURN_START_EVENT

Instance Method Summary collapse

Methods included from Hooks

new

Constructor Details

#initialize(app, max_iterations: DEFAULT_MAX_ITERATIONS) ⇒ MaxIterations

Returns a new instance of MaxIterations.



18
19
20
21
# File 'lib/brute/middleware/010_max_iterations.rb', line 18

def initialize(app, max_iterations: DEFAULT_MAX_ITERATIONS)
  @app = app
  @max_iterations = max_iterations
end

Instance Method Details

#call(env) ⇒ Object



23
24
25
26
27
28
29
30
31
32
# File 'lib/brute/middleware/010_max_iterations.rb', line 23

def call(env)
  if max_iterations_reached?(env)
    env[:messages] << Brute::Message.new(
      role: :user,
      content: "Maximum iterations reached.",
    )
  else
    @app.call(env)
  end
end