Module: RubyLLM::Toolbox::DataPath

Defined in:
lib/ruby_llm/toolbox/data_path.rb

Overview

Shared path-navigation for the structured-data tools (json_query, yaml_query). Path syntax: dot-separated keys, [n] for array indices, and

to map a field across an array. Examples:

users[0].name        users[].email        config.server.port

Defined Under Namespace

Classes: Error

Class Method Summary collapse

Class Method Details

.apply(data, tokens) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/ruby_llm/toolbox/data_path.rb', line 33

def apply(data, tokens)
  return data if tokens.empty? || data.nil?

  token, *rest = tokens
  case token
  when :map
    raise Error, "[] expects an array, got #{data.class}" unless data.is_a?(Array)

    data.map { |element| apply(element, rest) }
  when Integer
    raise Error, "index [#{token}] expects an array, got #{data.class}" unless data.is_a?(Array)

    apply(data[token], rest)
  else
    raise Error, "key '#{token}' expects an object, got #{data.class}" unless data.is_a?(Hash)

    apply(data[token], rest)
  end
end

.parse(path) ⇒ Object

Raises:



18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/ruby_llm/toolbox/data_path.rb', line 18

def parse(path)
  cleaned = path.to_s.strip.sub(/\A\$?\.?/, "")
  tokens = []
  cleaned.scan(/[^.\[\]]+|\[\d+\]|\[\]/) do |match|
    tokens << case match
              when "[]" then :map
              when /\A\[(\d+)\]\z/ then Regexp.last_match(1).to_i
              else match
              end
  end
  raise Error, "could not parse path: #{path.inspect}" if tokens.empty?

  tokens
end

.query(data, path) ⇒ Object



14
15
16
# File 'lib/ruby_llm/toolbox/data_path.rb', line 14

def query(data, path)
  apply(data, parse(path))
end