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
Allows wiring through of application context with context manager
elijahbenizzy6dcd43be2037
diff --git a/burr/core/__init__.py b/burr/core/__init__.pyindex 3445bdff..3d61c144 100644--- a/burr/core/__init__.py+++ b/burr/core/__init__.py@@ -1,5 +1,10 @@from burr.core.action import Action, Condition, Result, action, default, expr, when-from burr.core.application import Application, ApplicationBuilder, ApplicationGraph+from burr.core.application import (+ Application,+ ApplicationBuilder,+ ApplicationContext,+ ApplicationGraph,+)from burr.core.state import State__all__ = [@@ -8,6 +13,7 @@ __all__ = ["Application","ApplicationBuilder","ApplicationGraph",+ "ApplicationContext","Condition","default","expr",diff --git a/burr/core/application.py b/burr/core/application.pyindex 552fa267..f103add7 100644--- a/burr/core/application.py+++ b/burr/core/application.py@@ -1,10 +1,12 @@import collections+import contextvarsimport dataclassesimport functoolsimport inspectimport loggingimport pprintimport uuid+from contextlib import AbstractContextManagerfrom typing import (TYPE_CHECKING,Any,@@ -393,12 +395,41 @@ class ApplicationGraph:@dataclasses.dataclass-class ApplicationContext:+class ApplicationContext(AbstractContextManager):+ """Application context. This is anything your node might need to know about the application.+ Often used for recursive tracking.++ Note this is also a context manager (allowing you to pass context to sub-applications).+ """+app_id: strpartition_key: Optional[str]sequence_id: Optional[int]tracker: Optional["TrackingClient"]+ @staticmethod+ def get() -> Optional["ApplicationContext"]:+ """Provides the context-local application context.+ You can use this instead of declaring `__context` in an application.+ You really should only be using this if you're wiring through multiple layers of abstraction+ and want to connect two applications.++ :return: The ApplicationContext you'll want to use+ """+ return _application_context.get()++ def __enter__(self) -> "ApplicationContext":+ _application_context.set(self)+ return self++ def __exit__(self, __exc_type, __exc_value, __traceback):+ _application_context.set(None)+++_application_context = contextvars.ContextVar[Optional[ApplicationContext]](+ "application_context", default=None+)+class Application:def __init__(@@ -498,53 +529,56 @@ class Application:) -> Optional[Tuple[Action, dict, State]]:"""Internal-facing version of step. This is the same as step, but with an additionalparameter to hide hook execution so async can leverage it."""- next_action = self.get_next_action()- if next_action is None:- return None- if inputs is None:- inputs = {}- action_inputs = self._process_inputs(inputs, next_action)- if _run_hooks:- self._adapter_set.call_all_lifecycle_hooks_sync(- "pre_run_step",- action=next_action,- state=self._state,- inputs=action_inputs,- sequence_id=self.sequence_id,- app_id=self._uid,- partition_key=self._partition_key,- )- exc = None- result = None- new_state = self._state- try:- if next_action.single_step:- result, new_state = _run_single_step_action(next_action, self._state, action_inputs)- else:- result = _run_function(- next_action, self._state, action_inputs, name=next_action.name- )- new_state = _run_reducer(next_action, self._state, result, next_action.name)-- new_state = self._update_internal_state_value(new_state, next_action)- self._set_state(new_state)- except Exception as e:- exc = e- logger.exception(_format_error_message(next_action, self._state, inputs))- raise e- finally:+ with self.context:+ next_action = self.get_next_action()+ if next_action is None:+ return None+ if inputs is None:+ inputs = {}+ action_inputs = self._process_inputs(inputs, next_action)if _run_hooks:self._adapter_set.call_all_lifecycle_hooks_sync(- "post_run_step",- app_id=self._uid,- partition_key=self._partition_key,+ "pre_run_step",action=next_action,- state=new_state,- result=result,+ state=self._state,+ inputs=action_inputs,sequence_id=self.sequence_id,- exception=exc,+ app_id=self._uid,+ partition_key=self._partition_key,)- return next_action, result, new_state+ exc = None+ result = None+ new_state = self._state+ try:+ if next_action.single_step:+ result, new_state = _run_single_step_action(+ next_action, self._state, action_inputs+ )+ else:+ result = _run_function(+ next_action, self._state, action_inputs, name=next_action.name+ )+ new_state = _run_reducer(next_action, self._state, result, next_action.name)++ new_state = self._update_internal_state_value(new_state, next_action)+ self._set_state(new_state)+ except Exception as e:+ exc = e+ logger.exception(_format_error_message(next_action, self._state, inputs))+ raise e+ finally:+ if _run_hooks:+ self._adapter_set.call_all_lifecycle_hooks_sync(+ "post_run_step",+ app_id=self._uid,+ partition_key=self._partition_key,+ action=next_action,+ state=new_state,+ result=result,+ sequence_id=self.sequence_id,+ exception=exc,+ )+ return next_action, result, new_statedef reset_to_entrypoint(self) -> None:"""Resets the state machine to the entrypoint action."""@@ -626,64 +660,65 @@ class Application:async def _astep(self, inputs: Optional[Dict[str, Any]], _run_hooks: bool = True):# we want to increment regardless of failure- next_action = self.get_next_action()- if next_action is None:- return None- if inputs is None:- inputs = {}- action_inputs = self._process_inputs(inputs, next_action)- if _run_hooks:- await self._adapter_set.call_all_lifecycle_hooks_sync_and_async(- "pre_run_step",- action=next_action,- state=self._state,- inputs=action_inputs,- sequence_id=self.sequence_id,- app_id=self._uid,- partition_key=self._partition_key,- )- exc = None- result = None- new_state = self._state- try:- if not next_action.is_async():- # we can just delegate to the synchronous version, it will block the event loop,- # but that's safer than assuming its OK to launch a thread- # TODO -- add an option/configuration to launch a thread (yikes, not super safe, but for a pure function- # which this is supposed to be its OK).- # this delegates hooks to the synchronous version, so we'll call all of them as well- return self._step(- inputs=action_inputs, _run_hooks=False- ) # Skip hooks as we already ran all of them/will run all of them in this function's finally- if next_action.single_step:- result, new_state = await _arun_single_step_action(- next_action, self._state, inputs=action_inputs- )- else:- result = await _arun_function(- next_action, self._state, inputs=action_inputs, name=next_action.name- )- new_state = _run_reducer(next_action, self._state, result, next_action.name)- new_state = self._update_internal_state_value(new_state, next_action)- self._set_state(new_state)- except Exception as e:- exc = e- logger.exception(_format_error_message(next_action, self._state, inputs))- raise e- finally:+ with self.context:+ next_action = self.get_next_action()+ if next_action is None:+ return None+ if inputs is None:+ inputs = {}+ action_inputs = self._process_inputs(inputs, next_action)if _run_hooks:await self._adapter_set.call_all_lifecycle_hooks_sync_and_async(- "post_run_step",+ "pre_run_step",action=next_action,- state=new_state,- result=result,+ state=self._state,+ inputs=action_inputs,sequence_id=self.sequence_id,- exception=exc,app_id=self._uid,partition_key=self._partition_key,)+ exc = None+ result = None+ new_state = self._state+ try:+ if not next_action.is_async():+ # we can just delegate to the synchronous version, it will block the event loop,+ # but that's safer than assuming its OK to launch a thread+ # TODO -- add an option/configuration to launch a thread (yikes, not super safe, but for a pure function+ # which this is supposed to be its OK).+ # this delegates hooks to the synchronous version, so we'll call all of them as well+ return self._step(+ inputs=action_inputs, _run_hooks=False+ ) # Skip hooks as we already ran all of them/will run all of them in this function's finally+ if next_action.single_step:+ result, new_state = await _arun_single_step_action(+ next_action, self._state, inputs=action_inputs+ )+ else:+ result = await _arun_function(+ next_action, self._state, inputs=action_inputs, name=next_action.name+ )+ new_state = _run_reducer(next_action, self._state, result, next_action.name)+ new_state = self._update_internal_state_value(new_state, next_action)+ self._set_state(new_state)+ except Exception as e:+ exc = e+ logger.exception(_format_error_message(next_action, self._state, inputs))+ raise e+ finally:+ if _run_hooks:+ await self._adapter_set.call_all_lifecycle_hooks_sync_and_async(+ "post_run_step",+ action=next_action,+ state=new_state,+ result=result,+ sequence_id=self.sequence_id,+ exception=exc,+ app_id=self._uid,+ partition_key=self._partition_key,+ )- return next_action, result, new_state+ return next_action, result, new_statedef _clean_iterate_params(self,diff --git a/docs/concepts/recursion.rst b/docs/concepts/recursion.rstindex 16422923..323cfeee 100644--- a/docs/concepts/recursion.rst+++ b/docs/concepts/recursion.rst@@ -78,7 +78,7 @@ Parallel and delayed functions, but you can use whatever tooling you want (multiApplicationBuilder().with_actions(...).with_transitions(...)- .with_tracker(__context.tracker.copy())+ .with_tracker(__context.tracker.copy() if __context.tracker is not None else None).with_spawning_parent(__context.app_id,__context.sequence_id,@@ -111,6 +111,43 @@ When you track in the UI, you will see the following (in this example we're gene.. image:: ../_static/recursive_steps.png:align: center+Alternatives+------------++If, for some reason, you want to run a Burr application inside a burr application but can't effectively wire through the tracker/context+(say, for instance, that it's run through levels of other frameworks), you can get access to the active context and tracker by using the following:++.. code-block:: python++ from burr import get_active_context, get_active_tracker, ApplicationContext++ @action(reads=["parameters_to_map"], writes=["joined_results"])+ def my_action(state: State) -> State:+ context = ApplicationContext.get()+ def run_subapp(parameter_set):+ subapp = (+ ApplicationBuilder()+ .with_actions(...)+ .with_transitions(...)+ .with_tracker(context.tracker.copy() if context.tracker is not None else None)+ .with_spawning_parent(+ context.app_id,+ context.sequence_id,+ context.partition_key,+ )+ .with_entrypoint(...)+ .with_state(...)+ .build()+ )+ return subapp.run(...)++ results = Parallel(n_jobs=-1)(delayed(run_subapp)(parameter_set) for parameter_set in state["parameters_to_map"])+ joined = _join(results)++ # do something with the context and tracker++ return state+-------------------Future Improvements-------------------diff --git a/docs/reference/application.rst b/docs/reference/application.rstindex 21aa7399..0a1fac54 100644--- a/docs/reference/application.rst+++ b/docs/reference/application.rst@@ -18,3 +18,6 @@ and not the ``Application`` class directly... autoclass:: burr.core.application.ApplicationGraph:members:++.. autoclass:: burr.core.application.ApplicationContext+ :members:diff --git a/tests/core/test_application.py b/tests/core/test_application.pyindex 31faa15d..34cca0f4 100644--- a/tests/core/test_application.py+++ b/tests/core/test_application.py@@ -2395,6 +2395,58 @@ def test_application_exposes_app_context():assert context.tracker.unique_id == "unique_tracker_name"+def test_application_exposes_app_context_through_context_manager_sync():+ """Tests that we can get the context from the application correctly"""++ @action(reads=["count"], writes=["count"])+ def counter(state: State) -> State:+ app_context = ApplicationContext.get()+ assert app_context is not None+ assert app_context.tracker is not None # NoOpTracker is used+ assert isinstance(app_context.sequence_id, int)+ assert app_context.app_id == "test123"+ return state.update(count=state["count"] + 1)++ result_action = Result("count").with_name("result")+ app = (+ ApplicationBuilder()+ .with_actions(result_action, counter=counter)+ .with_transitions(("counter", "result", default))+ .with_tracker(NoOpTracker("unique_tracker_name"))+ .with_identifiers(app_id="test123", partition_key="user123", sequence_id=5)+ .with_entrypoint("counter")+ .with_state(count=0)+ .build()+ )+ app.run(halt_after=["result"])+++async def test_application_exposes_app_context_through_context_manager_async():+ """Tests that we can get the context from the application correctly"""++ @action(reads=["count"], writes=["count"])+ async def counter(state: State) -> State:+ app_context = ApplicationContext.get()+ assert app_context is not None+ assert app_context.tracker is not None # NoOpTracker is used+ assert isinstance(app_context.sequence_id, int)+ assert app_context.app_id == "test123"+ return state.update(count=state["count"] + 1)++ result_action = Result("count").with_name("result")+ app = (+ ApplicationBuilder()+ .with_actions(result_action, counter=counter)+ .with_transitions(("counter", "result", default))+ .with_tracker(NoOpTracker("unique_tracker_name"))+ .with_identifiers(app_id="test123", partition_key="user123", sequence_id=5)+ .with_entrypoint("counter")+ .with_state(count=0)+ .build()+ )+ await app.arun(halt_after=["result"])++def test_application_passes_context_when_declared():"""Tests that the context is passed to the function correctly"""context_list = []