Module: OllamaAgent::LLM::FirstJsonObject

Defined in:
lib/ollama_agent/llm/first_json_object.rb

Overview

Finds the first top-level balanced ‘{ … }` slice, respecting string escapes.

Class Method Summary collapse

Class Method Details

.extract(text) ⇒ Object

rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity – brace depth + string escape scanner



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/ollama_agent/llm/first_json_object.rb', line 10

def extract(text)
  start_idx = text.index("{")
  return nil unless start_idx

  depth = 0
  in_string = false
  escape = false
  (start_idx...text.length).each do |i|
    c = text[i]
    if in_string
      if escape
        escape = false
      elsif c == "\\"
        escape = true
      elsif c == '"'
        in_string = false
      end
    elsif c == '"'
      in_string = true
    elsif c == "{"
      depth += 1
    elsif c == "}"
      depth -= 1
      return text[start_idx..i] if depth.zero?
    end
  end
  nil
end