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.

Fixes __context for classed based actions

Stefan Krawczyk2bfe88ba7f1e
diff --git a/burr/core/application.py b/burr/core/application.py
index f312af72..183dec9a 100644
--- a/burr/core/application.py
+++ b/burr/core/application.py
@@ -103,6 +103,31 @@ def _adjust_single_step_output(
_raise_fn_return_validation_error(output, action_name)
+def _remap_context_variable(run_method: Callable, inputs: Dict[str, Any]) -> dict:
+ """This is a utility function to remap the __context variable to the mangled variable in the function signature.
+
+ Python mangles the variable name in the function signature, so we need to remap it to the correct variable name.
+
+ :param run_method: the run method to inspect.
+ :param inputs: the inputs to inspect
+ :return: potentially new dict with the remapped variable, else the original dict.
+ """
+ # Get the signature of the method being run. This should be Function.run() or similar.
+ signature = inspect.signature(run_method)
+ # Find the name-mangled __context variable
+ mangled_context_name = None
+ for param in signature.parameters.values():
+ if param.name.endswith("__context"):
+ mangled_context_name = param.name
+ break
+
+ # If a mangled __context variable is found, remap the value in inputs
+ if mangled_context_name and "__context" in inputs:
+ inputs = inputs.copy()
+ inputs[mangled_context_name] = inputs.pop("__context")
+ return inputs
+
+
def _run_function(function: Function, state: State, inputs: Dict[str, Any], name: str) -> dict:
"""Runs a function, returning the result of running the function.
Note this restricts the keys in the state to only those that the
@@ -121,6 +146,9 @@ def _run_function(function: Function, state: State, inputs: Dict[str, Any], name
)
state_to_use = state.subset(*function.reads)
function.validate_inputs(inputs)
+ if "__context" in inputs:
+ # potentially need to remap the __context variable
+ inputs = _remap_context_variable(function.run, inputs)
result = function.run(state_to_use, **inputs)
_validate_result(result, name)
return result
diff --git a/docs/concepts/actions.rst b/docs/concepts/actions.rst
index f43b47f2..d871f5ef 100644
--- a/docs/concepts/actions.rst
+++ b/docs/concepts/actions.rst
@@ -108,6 +108,21 @@ Will require the inputs to be passed in at runtime. See below for how to do that
This means that the application does not *need* the inputs to be set.
+Note: to access ``app_id`` and ``partition_key`` in your running application, you can have the :py:class:`ApplicationContext <burr.core.application.ApplicationContext>`
+injected into your Burr Actions. This is done by adding ``__context`` to the action signature:
+
+.. code-block:: python
+
+ from burr.core import action, State, ApplicationContext
+
+ @action(reads=[...], writes=[...])
+ def my_action(state: State, __context: ApplicationContext) -> State:
+ app_id = __context.app_id
+ partition_key = __context.partition_key
+ ...
+
+
+
-------------------
Class-Based Actions
-------------------
@@ -184,7 +199,40 @@ of (required, optional) inputs. For example:
Note your code will have to handle the case where ``optional_input`` is not passed in (e.g. by setting the appropriate kwargs to the `run(...)` method.
-Refer to :ref:`actions <actions>` for more documentation.
+If your action needs to know the current `partition_key`, `app_id`, or `sequence_id`, you can request the `__context` variable
+be injected into the action. This is done by adding `__context` to the `inputs` property as well as the run method:
+
+.. code-block:: python
+
+ from burr.core import Action, State, ApplicationContext
+
+ class Counter(Action):
+ @property
+ def reads(self) -> list[str]:
+ return ["counter"]
+
+ def run(self,
+ state: State,
+ increment_by: int,
+ # add __context here
+ __context: ApplicationContext) -> dict:
+ # can access the app_id from the __context
+ print(__context.app_id, __context.partition_key, __context.sequence_id)
+ return {"counter": state["counter"] + increment_by}
+
+ @property
+ def writes(self) -> list[str]:
+ return ["counter"]
+
+ def update(self, result: dict, state: State) -> State:
+ return state.update(**result)
+
+ @property
+ def inputs(self) -> list[str]:
+ # add __context here
+ return ["increment_by", "__context"]
+
+Refer to :py:class:`Action <burr.core.action.Action>` for more documentation.
.. _inputref:
diff --git a/examples/hello-world-counter/README.md b/examples/hello-world-counter/README.md
index 33810b9e..89d4a258 100644
--- a/examples/hello-world-counter/README.md
+++ b/examples/hello-world-counter/README.md
@@ -26,3 +26,6 @@ streamlit run streamlit_app.py
This will open a chrome window and print out the URL. The state machine this encapsulates takes the following form:
![State Machine](statemachine.png)
+
+Note: if you are looking for an example of the class based action API, then
+take a look at `application_classbased.py`.
diff --git a/examples/hello-world-counter/application_classbased.py b/examples/hello-world-counter/application_classbased.py
new file mode 100644
index 00000000..84220f47
--- /dev/null
+++ b/examples/hello-world-counter/application_classbased.py
@@ -0,0 +1,90 @@
+"""
+Class based action example.
+"""
+import logging
+from typing import List, Optional
+
+import burr.core
+from burr.core import Action, Application, ApplicationContext, Result, State, default, expr
+from burr.core.persistence import SQLLitePersister
+from burr.lifecycle import LifecycleAdapter
+
+logger = logging.getLogger(__name__)
+
+
+class Counter(Action):
+ @property
+ def reads(self) -> list[str]:
+ return ["counter"]
+
+ def run(self, state: State, increment_by: int, __context: ApplicationContext) -> dict:
+ # can access the app_id from the __context
+ print(__context.app_id)
+ return {"counter": state["counter"] + increment_by}
+
+ # alternate way via **kwargs
+ # def run(self,
+ # state: State,
+ # increment_by: int,
+ # **kwargs) -> dict:
+ # # can access the app_id from the __context via kwargs
+ # print(kwargs["__context"].app_id)
+ # return {"counter": state["counter"] + increment_by}
+
+ @property
+ def writes(self) -> list[str]:
+ return ["counter"]
+
+ def update(self, result: dict, state: State) -> State:
+ return state.update(**result)
+
+ @property
+ def inputs(self) -> list[str]:
+ # to get __context injected you must declare it here.
+ return ["increment_by", "__context"]
+
+
+def application(
+ count_up_to: int = 10,
+ partition_key: str = "demo-user",
+ app_id: Optional[str] = None,
+ storage_dir: Optional[str] = "~/.burr",
+ hooks: Optional[List[LifecycleAdapter]] = None,
+) -> Application:
+ persister = SQLLitePersister("demos.db", "counter", connect_kwargs={"check_same_thread": False})
+ persister.initialize()
+ logger.info(
+ f"{partition_key} has these prior invocations: {persister.list_app_ids(partition_key)}"
+ )
+ return (
+ burr.core.ApplicationBuilder()
+ .with_actions(counter=Counter(), result=Result("counter"))
+ .with_transitions(
+ ("counter", "counter", expr(f"counter < {count_up_to}")),
+ ("counter", "result", default),
+ )
+ .with_identifiers(partition_key=partition_key, app_id=app_id)
+ .initialize_from(
+ persister,
+ resume_at_next_action=True,
+ default_state={"counter": 0},
+ default_entrypoint="counter",
+ )
+ .with_state_persister(persister)
+ .with_tracker(project="demo_counter", params={"storage_dir": storage_dir})
+ .with_hooks(*hooks if hooks else [])
+ .build()
+ )
+
+
+if __name__ == "__main__":
+ logging.basicConfig(level=logging.INFO)
+ app = application() # app_id="a7c8e525-58f9-4e84-b4b3-f5b80b5b0d0e")
+ action, result, state = app.run(halt_after=["result"], inputs={"increment_by": 1})
+ app.visualize(
+ output_file_path="statemachine_classbased.png",
+ include_conditions=True,
+ view=False,
+ format="png",
+ )
+ print(state["counter"])
diff --git a/examples/test-case-creation/test_application.py b/examples/test-case-creation/test_application.py
index d29f9089..0d207eaa 100644
--- a/examples/test-case-creation/test_application.py
+++ b/examples/test-case-creation/test_application.py
@@ -51,7 +51,7 @@ def test_prompt_for_more():
@pytest.mark.file_name("prompt_for_more.json")
-def test_prompt_for_more_from_file(input_state, expected_state):
+def test_prompt_for_more_from_file(input_state, expected_state, results_bag):
"""Function for testing the action"""
input_state = state.State.deserialize(input_state)
expected_state = state.State.deserialize(expected_state)
@@ -65,3 +65,15 @@ def test_prompt_for_more_from_file(input_state, expected_state):
# or, have an LLM Grade things -- you need to create the llm_evaluator function:
# assert llm_evaluator("are these two equivalent responses. Respond with Y for yes, N for no",
# output_state["response"]["content"], expected_state["response"]["content"]) == "Y"
+ results_bag.input_state = input_state
+ results_bag.expected_state = expected_state
+ results_bag.output_state = output_state
+ results_bag.foo = "bar"
+
+
+def test_print_results(module_results_df):
+ print(module_results_df.columns)
+ print(module_results_df.head())
+ # save to CSV
+ # upload to google sheets
+ # compute statistics
diff --git a/tests/core/test_application.py b/tests/core/test_application.py
index aa332bf7..997ff9ea 100644
--- a/tests/core/test_application.py
+++ b/tests/core/test_application.py
@@ -4,7 +4,7 @@ import datetime
import logging
import typing
import uuid
-from typing import Any, Awaitable, Callable, Dict, Generator, Literal, Optional, Tuple
+from typing import Any, Awaitable, Callable, Dict, Generator, Literal, Optional, Tuple, Union
import pytest
@@ -34,6 +34,7 @@ from burr.core.application import (
_arun_multi_step_streaming_action,
_arun_single_step_action,
_arun_single_step_streaming_action,
+ _remap_context_variable,
_run_function,
_run_multi_step_streaming_action,
_run_reducer,
@@ -3330,3 +3331,65 @@ def test_with_state_persister_is_initialized_not_implemented():
persister = FakePersister()
# Add the persister to the builder, expecting no exceptions
builder.with_state_persister(persister)
+
+
+class TestActionWithoutContext(Action):
+ def run(self, other_param, foo):
+ pass
+
+ @property
+ def reads(self) -> list[str]:
+ pass
+
+ @property
+ def writes(self) -> list[str]:
+ pass
+
+ def update(self, result: dict, state: State) -> State:
+ pass
+
+ def inputs(self) -> Union[list[str], tuple[list[str], list[str]]]:
+ return ["other_param", "foo"]
+
+
+class TestActionWithContext(TestActionWithoutContext):
+ def run(self, __context, other_param, foo):
+ pass
+
+ def inputs(self) -> Union[list[str], tuple[list[str], list[str]]]:
+ return ["other_param", "foo", "__context"]
+
+
+class TestActionWithKwargs(TestActionWithoutContext):
+ def run(self, other_param, foo, **kwargs):
+ pass
+
+ def inputs(self) -> Union[list[str], tuple[list[str], list[str]]]:
+ return ["other_param", "foo", "__context"]
+
+
+def test_remap_context_variable_with_mangled_context_kwargs():
+ _action = TestActionWithKwargs()
+
+ inputs = {"__context": "context_value", "other_key": "other_value", "foo": "foo_value"}
+ expected = {"__context": "context_value", "other_key": "other_value", "foo": "foo_value"}
+ assert _remap_context_variable(_action.run, inputs) == expected
+
+
+def test_remap_context_variable_with_mangled_context():
+ _action = TestActionWithContext()
+
+ inputs = {"__context": "context_value", "other_key": "other_value", "foo": "foo_value"}
+ expected = {
+ f"_{TestActionWithContext.__name__}__context": "context_value",
+ "other_key": "other_value",
+ "foo": "foo_value",
+ }
+ assert _remap_context_variable(_action.run, inputs) == expected
+
+
+def test_remap_context_variable_without_mangled_context():
+ _action = TestActionWithoutContext()
+ inputs = {"__context": "context_value", "other_key": "other_value", "foo": "foo_value"}
+ expected = {"__context": "context_value", "other_key": "other_value", "foo": "foo_value"}
+ assert _remap_context_variable(_action.run, inputs) == expected