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::COMPACT_DURATION_EVENT, Hooks::COMPACT_END_EVENT, Hooks::COMPACT_FAILURE_EVENT, Hooks::COMPACT_START_EVENT, Hooks::CONTENT_EVENT, Hooks::FARADAY_ERROR_EVENT, Hooks::LLM_DURATION_EVENT, Hooks::LLM_END_EVENT, Hooks::LLM_FAILURE_EVENT, Hooks::LLM_START_EVENT, Hooks::MIDDLEWARE_ADDED_EVENT, Hooks::MIDDLEWARE_DURATION_EVENT, Hooks::MIDDLEWARE_END_EVENT, Hooks::MIDDLEWARE_FAILURE_EVENT, Hooks::MIDDLEWARE_START_EVENT, Hooks::OPEN_ROUTER_SERVER_ERROR_EVENT, Hooks::REASONING_EVENT, Hooks::STANDARD_ERROR_EVENT, Hooks::TOOL_APPROVE_EVENT, Hooks::TOOL_CALLS_EVENT, Hooks::TOOL_DURATION_EVENT, Hooks::TOOL_END_EVENT, Hooks::TOOL_FAILURE_EVENT, Hooks::TOOL_START_EVENT, Hooks::TURN_DURATION_EVENT, Hooks::TURN_END_EVENT, Hooks::TURN_FAILURE_EVENT, Hooks::TURN_START_EVENT

Instance Method Summary collapse

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