Build applications that make decisions (chatbots, agents, simulations, etc...). Monitor, trace, persist, and execute on your own infrastructure.
Python aiburrchatbot-frameworkdagsgenerative-aigraphshacktoberfestllmopsllmsmlopspersistent-data-structurestate-machinestate-managementvisibility
Adds state incrementing + a little more state docs
elijahbenizzyad13f57d046b
diff --git a/burr/core/state.py b/burr/core/state.pyindex eeee65ea..2598de63 100644--- a/burr/core/state.py+++ b/burr/core/state.py@@ -115,6 +115,39 @@ class AppendFields(StateDelta):)+class IncrementFields(StateDelta):+ values: Mapping[str, int]++ @classmethod+ def name(cls) -> str:+ return "increment"++ def reads(self) -> list[str]:+ return list(self.values.keys())++ def writes(self) -> list[str]:+ return list(self.values.keys())++ def validate(self, input_state: Dict[str, Any]):+ incorrect_types = {}+ for write_key in self.writes():+ if write_key in input_state and not isinstance(input_state[write_key], int):+ incorrect_types[write_key] = type(input_state[write_key])+ if incorrect_types:+ raise ValueError(+ f"Cannot increment non-integer values: {incorrect_types}. "+ f"Please ensure that all fields are integers."+ )++ def apply_mutate(self, inputs: dict):+ for key, value in self.values.items():+ if key not in inputs:+ inputs[key] = value+ else:+ inputs[key] += value++@dataclasses.dataclassclass DeleteField(StateDelta):"""State delta that deletes fields from the state"""@@ -137,13 +170,7 @@ class DeleteField(StateDelta):class State(Mapping):- """An immutable state object. Things to consider:- 1. Adding hooks on change- 2. Pulling/pushing to external places- 3. Simultaneous writes/reads in the case of parallelism- 4. Schema enforcement -- how to specify/manage? Should this be a- dataclass when implemented?- """+ """An immutable state object. This is the only way to interact with state in Burr."""def __init__(self, initial_values: Dict[str, Any] = None):if initial_values is None:@@ -164,22 +191,55 @@ class State(Mapping):return dict(self)def update(self, **updates: Any) -> "State":- """Updates the state with a set of key-value pairs"""+ """Updates the state with a set of key-value pairs+ Does an upsert operation (if the keys exist their value will be overwritten,+ otherwise they will be created)++ .. code-block:: python++ state = State({"a": 1})+ state.update(a=2, b=3) # State({"a": 2, "b": 3})++ :param updates: Updates to apply+ :return: A new state with the updates applied+ """return self.apply_operation(SetFields(updates))def append(self, **updates: Any) -> "State":- """For each pair specified, appends to a list in state."""+ """Appends to 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 with the value in it.++ .. code-block:: python++ state = State({"a": [1]})+ state.append(a=2) # State({"a": [1, 2]})++ :param updates: updates to apply+ :return: new state object+ """return self.apply_operation(AppendFields(updates))+ def increment(self, **updates: int) -> "State":+ """Increments the state with a set of key-value pairs. Each one+ must correspond to an integer, or an error will be raised.++ :param updates: updates to apply+ :return: new state object+ """ ""+ return self.apply_operation(IncrementFields(updates))+def wipe(self, delete: list[str] = None, keep: list[str] = None):"""Wipes the state, either by deleting the keys in delete and keeping everything elseor keeping the keys in keep. and deleting everything else. If you pass nothing init will delete the whole thing.- :param delete:- :param keep:- :return:+ :param delete: Keys to delete+ :param keep: Keys to keep+ :return: A new state object"""if delete is not None and keep is not None:raise ValueError(diff --git a/docs/concepts/state.rst b/docs/concepts/state.rstindex 883e2348..9da634fc 100644--- a/docs/concepts/state.rst+++ b/docs/concepts/state.rst@@ -12,15 +12,21 @@ StateThe ``State`` class provides the ability to manipulate state for a given action. It is entirely immutable,meaning that you can only create new states from old ones, not modify them in place.+State manipulation is done through calling methods on the ``State`` class. The most common write are:.. code-block:: pythonstate.update(foo=bar) # update the state with the key "foo" set to "bar"state.append(foo=bar) # append "bar" to the list at "foo"+ state.increment(foo=1) # increment the value at "foo" by 1state.wipe(keep=["foo", "bar"]) # remove all keys except "foo" and "bar"state.wipe(delete=["foo", "bar"]) # remove "foo" and "bar" from the state+.. warning::++ The ``State`` object can only be treated immutably! Calling ``state.update(foo=bar)`` will do nothing if you don't use the value returned by the call.+The read operations extend from those in the `Mapping <https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping>`_interface, but there are a few extra:diff --git a/tests/core/test_state.py b/tests/core/test_state.pyindex e51f9357..b66eb5cf 100644--- a/tests/core/test_state.py+++ b/tests/core/test_state.py@@ -82,7 +82,19 @@ def test_state_wipe_keep():assert wiped.get_all() == {"foo": "bar"}-def test_append_validate():+def test_state_append_validate_failure():state = State({"foo": "bar"})with pytest.raises(ValueError, match="non-appendable"):state.append(foo="baz", bar="qux")+++def test_state_increment():+ state = State({"foo": 1})+ incremented = state.increment(foo=2, bar=5)+ assert incremented.get_all() == {"foo": 3, "bar": 5}+++def test_state_increment_validate_failure():+ state = State({"foo": "bar"})+ with pytest.raises(ValueError, match="non-integer"):+ state.increment(foo="baz", bar="qux")