Class: LLM::LoopGuard

Inherits:
Object
  • Object
show all
Defined in:
lib/llm/loop_guard.rb

Overview

LLM::LoopGuard is the built-in implementation of llm.rb's guard capability.

A guard is a context-level supervisor for agentic execution. It can inspect the current runtime state and return a warning string when pending tool work should be blocked before the loop keeps going.

LLM::LoopGuard detects when a context is repeating the same tool-call pattern instead of making progress.

The public interface is intentionally small:

  • call(ctx) returns nil when no intervention is needed
  • call(ctx) returns a warning string when pending tool execution should be blocked

LLM::Context can use that warning to return in-band LLM::GuardError tool errors, and LLM::Agent enables this guard by default through its wrapped context.

Constant Summary collapse

DEFAULT_THRESHOLD =

The default number of repeated tool-call patterns required before the guard intervenes.

Returns:

  • (Integer)
3

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config = {}) ⇒ LoopGuard

Returns a new instance of LoopGuard.

Parameters:

  • config (Hash) (defaults to: {})

Options Hash (config):

  • :threshold (Integer)

    How many repeated tool-call patterns must appear at the tail of the sequence before the guard returns a warning.



40
41
42
# File 'lib/llm/loop_guard.rb', line 40

def initialize(config = {})
  @threshold = config.fetch(:threshold, DEFAULT_THRESHOLD)
end

Instance Attribute Details

#thresholdInteger (readonly)

Returns the repetition threshold.

Returns:

  • (Integer)


33
34
35
# File 'lib/llm/loop_guard.rb', line 33

def threshold
  @threshold
end

Instance Method Details

#call(ctx) ⇒ String?

Checks the current context for repeated tool-call patterns.

This method inspects assistant tool calls only. It reduces each call to a [tool_name, arguments] signature and checks whether the tail of the sequence is repeating.

Parameters:

Returns:

  • (String, nil)

    Returns a warning string when pending tool execution should be blocked, or nil when execution should continue.



55
56
57
58
# File 'lib/llm/loop_guard.rb', line 55

def call(ctx)
  repetitions = detect(ctx.messages.to_a)
  repetitions ? warning(repetitions) : nil
end