Class: Ollama::HistorySanitizer

Inherits:
Object
  • Object
show all
Defined in:
lib/ollama/history_sanitizer.rb

Overview

Strips reasoning/thought content from assistant responses before they are stored in conversation history, preventing thought leakage into subsequent prompt turns.

Gemma 4 and other reasoning models require that prior turns contain only the final response — not the thought content.

Usage:

sanitizer = HistorySanitizer.for(profile)
sanitizer.add(response, messages: conversation)

Trace store example (persist thoughts separately):

traces = []
sanitizer = HistorySanitizer.new(policy: :exclude_thoughts, trace_store: traces)

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(policy: :exclude_thoughts, trace_store: nil) ⇒ HistorySanitizer

Returns a new instance of HistorySanitizer.

Parameters:

  • policy (:exclude_thoughts, :none) (defaults to: :exclude_thoughts)
  • trace_store (Array, nil) (defaults to: nil)

    optional sink for reasoning traces



21
22
23
24
# File 'lib/ollama/history_sanitizer.rb', line 21

def initialize(policy: :exclude_thoughts, trace_store: nil)
  @policy = policy
  @trace_store = trace_store
end

Class Method Details

.for(profile, trace_store: nil) ⇒ HistorySanitizer

Build a sanitizer appropriate for a model profile.

Parameters:

Returns:



30
31
32
# File 'lib/ollama/history_sanitizer.rb', line 30

def self.for(profile, trace_store: nil)
  new(policy: profile.history_policy, trace_store: trace_store)
end

Instance Method Details

#add(response, messages:) ⇒ Hash

Append a response to the messages array, sanitized per policy. Returns the appended message hash.

Parameters:

Returns:

  • (Hash)

    the appended message



39
40
41
42
43
44
45
46
47
# File 'lib/ollama/history_sanitizer.rb', line 39

def add(response, messages:)
  case @policy
  when :exclude_thoughts
    store_trace(response)
  end
  msg = { role: "assistant", content: response.content.to_s }
  messages << msg
  msg
end