Class: LangGraphRB::State

Inherits:
Hash
  • Object
show all
Defined in:
lib/langgraph_rb/state.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schema = {}, reducers = {}) ⇒ State

Returns a new instance of State.



5
6
7
8
9
# File 'lib/langgraph_rb/state.rb', line 5

def initialize(schema = {}, reducers = {})
  @reducers = reducers || {}
  super()
  merge!(schema) if schema.is_a?(Hash)
end

Instance Attribute Details

#reducersObject (readonly)

Returns the value of attribute reducers.



3
4
5
# File 'lib/langgraph_rb/state.rb', line 3

def reducers
  @reducers
end

Class Method Details

.add_messagesObject

Common reducer for adding messages to an array



39
40
41
42
43
44
45
# File 'lib/langgraph_rb/state.rb', line 39

def self.add_messages
  ->(old_value, new_value) do
    old_array = old_value || []
    new_array = new_value.is_a?(Array) ? new_value : [new_value]
    old_array + new_array
  end
end

.append_stringObject

Common reducer for appending strings



48
49
50
51
52
# File 'lib/langgraph_rb/state.rb', line 48

def self.append_string
  ->(old_value, new_value) do
    (old_value || "") + new_value.to_s
  end
end

.merge_hashObject

Common reducer for merging hashes



55
56
57
58
59
60
# File 'lib/langgraph_rb/state.rb', line 55

def self.merge_hash
  ->(old_value, new_value) do
    old_hash = old_value || {}
    old_hash.merge(new_value || {})
  end
end

Instance Method Details

#inspectObject



66
67
68
# File 'lib/langgraph_rb/state.rb', line 66

def inspect
  "#<#{self.class.name} #{super}>"
end

#merge_delta(delta) ⇒ Object

Merge a delta (partial state update) using reducers



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/langgraph_rb/state.rb', line 12

def merge_delta(delta)
  return self if delta.nil? || delta.empty?
  
  new_state = self.class.new({}, @reducers)
  new_state.merge!(self)
  
  delta.each do |key, value|
    key = key.to_sym
    
    if @reducers[key]
      # Use the reducer function to combine old and new values
      new_state[key] = @reducers[key].call(self[key], value)
    else
      # Simple replacement
      new_state[key] = value
    end
  end
  
  new_state
end

#to_hObject



62
63
64
# File 'lib/langgraph_rb/state.rb', line 62

def to_h
  Hash[self]
end

#with_reducers(new_reducers) ⇒ Object

Create a new state with additional reducers



34
35
36
# File 'lib/langgraph_rb/state.rb', line 34

def with_reducers(new_reducers)
  self.class.new(self, @reducers.merge(new_reducers))
end