Skip to content

armgit / burr

Public Imported from GitHub
0

Build applications that make decisions (chatbots, agents, simulations, etc...). Monitor, trace, persist, and execute on your own infrastructure.

Adds a state.extend operation for efficient updating of list items in state

elijahbenizzyd90534178986
diff --git a/burr/core/state.py b/burr/core/state.py
index 67037b9f..e8cf03f4 100644
--- a/burr/core/state.py
+++ b/burr/core/state.py
@@ -158,6 +158,42 @@ class AppendFields(StateDelta):
)
+class ExtendFields(StateDelta):
+ """State delta that extends fields in the state"""
+
+ values: Mapping[str, list[Any]]
+
+ @classmethod
+ def name(cls) -> str:
+ return "extend"
+
+ def reads(self) -> list[str]:
+ return list(self.values.keys())
+
+ def writes(self) -> list[str]:
+ return list(self.values.keys())
+
+ def apply_mutate(self, inputs: dict):
+ for key, value in self.values.items():
+ if key not in inputs:
+ inputs[key] = []
+ if not isinstance(inputs[key], list):
+ raise ValueError(f"Cannot extend non-list value {key}={inputs[key]}")
+ inputs[key].extend(value)
+
+ def validate(self, input_state: Dict[str, Any]):
+ incorrect_types = {}
+ for write_key in self.writes():
+ if write_key in input_state and not hasattr(input_state[write_key], "extend"):
+ incorrect_types[write_key] = type(input_state[write_key])
+ if incorrect_types:
+ raise ValueError(
+ f"Cannot extend non-extendable values: {incorrect_types}. "
+ f"Please ensure that all fields are list-like."
+ )
+
+
@dataclasses.dataclass
class IncrementFields(StateDelta):
values: Mapping[str, int]
@@ -325,6 +361,24 @@ class State(Mapping, Generic[StateType]):
return self.apply_operation(AppendFields(updates))
+ def extend(self, **updates: list[Any]) -> "State[StateType]":
+ """Extends the state with a set of key-value pairs. Each one
+ must correspond to a list-like object, or an error will be raised.
+
+ This is an upsert operation, meaning that if the key does not
+ exist, a new list will be created and extended with the values.
+
+ .. code-block:: python
+
+ state = State({"a": [1]})
+ state.extend(a=[2, 3]) # State({"a": [1, 2, 3]})
+
+ :param updates: updates to apply
+ :return: new state object
+ """
+
+ return self.apply_operation(ExtendFields(updates))
+
def increment(self, **updates: int) -> "State[StateType]":
"""Increments the state with a set of key-value pairs. Each one
must correspond to an integer, or an error will be raised.
diff --git a/tests/core/test_state.py b/tests/core/test_state.py
index 30374d2a..01a871f3 100644
--- a/tests/core/test_state.py
+++ b/tests/core/test_state.py
@@ -63,6 +63,24 @@ def test_state_append():
assert appended.get_all() == {"foo": ["bar", "baz"]}
+def test_state_extend():
+ state = State({"foo": ["bar"]})
+ extended = state.extend(foo=["baz", "qux"])
+ assert extended.get_all() == {"foo": ["bar", "baz", "qux"]}
+
+
+def test_state_append_multiple_keys():
+ state = State({"foo": ["bar"], "baz": [1]})
+ appended = state.append(foo="baz", baz=2)
+ assert appended.get_all() == {"foo": ["bar", "baz"], "baz": [1, 2]}
+
+
+def test_state_extend_multiple_keys():
+ state = State({"foo": ["bar"], "baz": [1]})
+ extended = state.extend(foo=["baz"], baz=[2, 3])
+ assert extended.get_all() == {"foo": ["bar", "baz"], "baz": [1, 2, 3]}
+
+
def test_state_update():
state = State({"foo": "bar", "baz": "qux"})
updated = state.update(foo="baz")
@@ -92,6 +110,12 @@ def test_state_append_validate_failure():
state.append(foo="baz", bar="qux")
+def test_state_extend_validate_failure():
+ state = State({"foo": "bar"})
+ with pytest.raises(ValueError, match="non-extendable"):
+ state.extend(foo=["baz", "qux"], bar=["quux"])
+
+
def test_state_increment():
state = State({"foo": 1})
incremented = state.increment(foo=2, bar=5)