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 hooks for application interface calls
elijahbenizzy99dc0d75f15a
diff --git a/burr/core/application.py b/burr/core/application.pyindex e6774fff..92826625 100644--- a/burr/core/application.py+++ b/burr/core/application.py@@ -1,6 +1,7 @@import contextvarsimport dataclassesimport functools+import inspectimport loggingimport pprintimport uuid@@ -17,6 +18,7 @@ from typing import (Optional,Set,Tuple,+ TypeVar,Union,cast,)@@ -40,7 +42,7 @@ from burr.core.graph import Graph, GraphBuilderfrom burr.core.persistence import BaseStateLoader, BaseStateSaverfrom burr.core.state import Statefrom burr.core.validation import BASE_ERROR_MESSAGE-from burr.lifecycle.base import LifecycleAdapter+from burr.lifecycle.base import ExecuteMethod, LifecycleAdapterfrom burr.lifecycle.internal import LifecycleAdapterSetif TYPE_CHECKING:@@ -409,6 +411,94 @@ _application_context = contextvars.ContextVar[Optional[ApplicationContext]]("application_context", default=None)+_run_call_var = contextvars.ContextVar[Optional[object]]("run_call_var", default=None)++CallableT = TypeVar("CallableT")+++class _call_execute_method_pre_post:+ """Wrapper class to ensure that the lifecycle hooks are called before/after application calls.+ This is not called for streaming as there is special logic involved "post-return" that we need to handle.+ We will likely add additional hooks for streaming as well, but for now these just decorate the function.+ This is not a publicly exposed API -- it is used internally to ensure that the lifecycle hooks are called.+ """++ def __init__(self, method: ExecuteMethod):+ self.method = method+ self.sentinel = object() # unique object to ensure we only call once++ def call_pre(self, app) -> bool:+ if should_run_hooks := (_run_call_var.get() is None):+ _run_call_var.set(self.sentinel)+ app._adapter_set.call_all_lifecycle_hooks_sync(+ "pre_run_execute_call",+ app_id=app._uid,+ partition_key=app._partition_key,+ state=app.state,+ method=self.method,+ )+ return should_run_hooks++ def call_post(self, app, exc) -> bool:+ if should_run_hooks := (_run_call_var.get() is self.sentinel):+ app._adapter_set.call_all_lifecycle_hooks_sync(+ "post_run_execute_call",+ app_id=app._uid,+ partition_key=app._partition_key,+ state=app.state,+ method=self.method,+ exception=exc,+ )+ _run_call_var.set(None)+ return should_run_hooks++ async def acall_pre(self, app) -> bool:+ if should_run_hooks := (_run_call_var.get() is None):+ _run_call_var.set(self.sentinel)+ await app._adapter_set.call_all_lifecycle_hooks_sync_and_async(+ "pre_run_execute_call",+ app_id=app._uid,+ partition_key=app._partition_key,+ state=app.state,+ method=self.method,+ )+ return should_run_hooks++ async def acall_post(self, app, exc) -> bool:+ if should_run_hooks := (_run_call_var.get() is self.sentinel):+ await app._adapter_set.call_all_lifecycle_hooks_sync_and_async(+ "post_run_execute_call",+ app_id=app._uid,+ partition_key=app._partition_key,+ state=app.state,+ method=self.method,+ exception=exc,+ )+ _run_call_var.set(None)+ return should_run_hooks++ def __call__(self, fn: CallableT) -> CallableT:+ @functools.wraps(fn)+ async def wrapper_async(app_self, *args, **kwargs):+ # We only run at the top level, so we decorate it if we're there+ await self.acall_pre(app_self)+ exc = None+ try:+ return await fn(app_self, *args, **kwargs)+ finally:+ await self.acall_post(app_self, exc)++ @functools.wraps(fn)+ def wrapper_sync(app_self, *args, **kwargs):+ self.call_pre(app_self)+ exc = None+ try:+ return fn(app_self, *args, **kwargs)+ finally:+ self.call_post(app_self, exc)++ return wrapper_async if inspect.iscoroutinefunction(fn) else wrapper_sync+class Application:def __init__(@@ -479,6 +569,7 @@ class Application:# @telemetry.capture_function_usage # todo -- capture usage when we break this up into one that isn't called internally# This will be doable when we move sequence ID to the beginning of the function https://github.com/DAGWorks-Inc/burr/pull/73+ @_call_execute_method_pre_post(ExecuteMethod.step)def step(self, inputs: Optional[Dict[str, Any]] = None) -> Optional[Tuple[Action, dict, State]]:"""Performs a single step, advancing the state machine along.This returns a tuple of the action that was run, the result of running@@ -630,6 +721,7 @@ class Application:# @telemetry.capture_function_usage# ditto with step()+ @_call_execute_method_pre_post(ExecuteMethod.astep)async def astep(self, inputs: Dict[str, Any] = None) -> Optional[Tuple[Action, dict, State]]:"""Asynchronous version of step.@@ -791,6 +883,7 @@ class Application:return prior_action, result, self._state@telemetry.capture_function_usage+ @_call_execute_method_pre_post(ExecuteMethod.iterate)def iterate(self,*,@@ -828,6 +921,7 @@ class Application:return self._return_value_iterate(halt_before, halt_after, prior_action, result)@telemetry.capture_function_usage+ @_call_execute_method_pre_post(ExecuteMethod.aiterate)async def aiterate(self,*,@@ -857,6 +951,7 @@ class Application:break@telemetry.capture_function_usage+ @_call_execute_method_pre_post(ExecuteMethod.run)def run(self,*,@@ -878,9 +973,11 @@ class Application:try:next(gen)except StopIteration as e:- return e.value+ result = e.value+ return result@telemetry.capture_function_usage+ @_call_execute_method_pre_post(ExecuteMethod.arun)async def arun(self,*,@@ -896,6 +993,7 @@ class Application::param inputs: Inputs to the action -- this is if this action requires an input that is passed in from the outside world:return: The final state, and the results of running the actions in the order that they were specified."""+prior_action = Noneresult = Nonehalt_before, halt_after, inputs = self._clean_iterate_params(@@ -1015,6 +1113,8 @@ class Application:result, state = output.get()print(format(result['response'], color))"""+ call_execute_method_wrapper = _call_execute_method_pre_post(ExecuteMethod.stream_result)+ call_execute_method_wrapper.call_pre(self)halt_before, halt_after, inputs = self._clean_iterate_params(halt_before, halt_after, inputs)@@ -1035,6 +1135,7 @@ class Application:# For context, this is specifically for the case in which you want to have# multiple terminal points with a unified API, where some are streaming, and some are not.if next_action.name in halt_before and next_action.name not in halt_after:+ call_execute_method_wrapper.call_post(self, None)return next_action, StreamingResultContainer.pass_through(results=results, final_state=state)@@ -1072,6 +1173,7 @@ class Application:sequence_id=self.sequence_id,exception=exc,)+ call_execute_method_wrapper.call_post(self, exc)action_inputs = self._process_inputs(inputs, next_action)if not next_action.streaming:@@ -1088,9 +1190,11 @@ class Application:sequence_id=self.sequence_id,exception=None,)- return action, StreamingResultContainer.pass_through(+ out = action, StreamingResultContainer.pass_through(results=result, final_state=state)+ call_execute_method_wrapper.call_post(self, None)+ return outif next_action.single_step:next_action = cast(SingleStepStreamingAction, next_action)generator = _run_single_step_streaming_action(@@ -1118,6 +1222,7 @@ class Application:sequence_id=self.sequence_id,exception=e,)+ call_execute_method_wrapper.call_post(self, e)raisereturn next_action, StreamingResultContainer(generator, self._state, process_result, callback@@ -1233,6 +1338,8 @@ class Application:result, state = await output.get()print(format(result['response'], color))"""+ call_execute_method_wrapper = _call_execute_method_pre_post(ExecuteMethod.stream_result)+ await call_execute_method_wrapper.acall_pre(self)halt_before, halt_after, inputs = self._clean_iterate_params(halt_before, halt_after, inputs)@@ -1253,6 +1360,7 @@ class Application:# For context, this is specifically for the case in which you want to have# multiple terminal points with a unified API, where some are streaming, and some are not.if next_action.name in halt_before and next_action.name not in halt_after:+ await call_execute_method_wrapper.acall_post(self, None)return next_action, AsyncStreamingResultContainer.pass_through(results=results, final_state=state)@@ -1288,12 +1396,12 @@ class Application:sequence_id=self.sequence_id,exception=exc,)+ await call_execute_method_wrapper.acall_post(self, exc)action_inputs = self._process_inputs(inputs, next_action)if not next_action.streaming:# In this case we are halting at a non-streaming condition# This is allowed as we want to maintain a more consistent API- # TODO -- get this to work with async. Figure out how to run the async step...action, result, state = await self._astep(inputs=inputs, _run_hooks=False)await self._adapter_set.call_all_lifecycle_hooks_sync_and_async("post_run_step",@@ -1305,6 +1413,7 @@ class Application:sequence_id=self.sequence_id,exception=None,)+ await call_execute_method_wrapper.acall_post(self, None)return action, AsyncStreamingResultContainer.pass_through(results=result, final_state=state)@@ -1351,6 +1460,7 @@ class Application:sequence_id=self.sequence_id,exception=e,)+ await call_execute_method_wrapper.acall_post(self, None, e)raisereturn next_action, AsyncStreamingResultContainer(generator, self._state, process_result, callbackdiff --git a/burr/lifecycle/__init__.py b/burr/lifecycle/__init__.pyindex 038416db..ed3567ff 100644--- a/burr/lifecycle/__init__.py+++ b/burr/lifecycle/__init__.py@@ -1,13 +1,13 @@from burr.lifecycle.base import (LifecycleAdapter,PostApplicationCreateHook,+ PostApplicationExecuteCallHook,+ PostApplicationExecuteCallHookAsync,PostEndSpanHook,- PostRunApplicationHook,- PostRunApplicationHookAsync,PostRunStepHook,PostRunStepHookAsync,- PreRunApplicationHook,- PreRunApplicationHookAsync,+ PreApplicationExecuteCallHook,+ PreApplicationExecuteCallHookAsync,PreRunStepHook,PreRunStepHookAsync,PreStartSpanHook,@@ -19,10 +19,10 @@ __all__ = ["PreRunStepHookAsync","PostRunStepHook","PostRunStepHookAsync",- "PreRunApplicationHook",- "PreRunApplicationHookAsync",- "PostRunApplicationHook",- "PostRunApplicationHookAsync",+ "PreApplicationExecuteCallHook",+ "PreApplicationExecuteCallHookAsync",+ "PostApplicationExecuteCallHook",+ "PostApplicationExecuteCallHookAsync","LifecycleAdapter","StateAndResultsFullLogger","PostApplicationCreateHook",diff --git a/burr/lifecycle/base.py b/burr/lifecycle/base.pyindex 39bfa2c9..cca891ba 100644--- a/burr/lifecycle/base.py+++ b/burr/lifecycle/base.py@@ -1,4 +1,5 @@import abc+import enumfrom typing import TYPE_CHECKING, Any, Dict, Optional, Unionimport burr.common.types as burr_types@@ -251,6 +252,8 @@ class PostEndSpanHook(abc.ABC):@lifecycle.base_hook("post_end_span")class PostEndSpanHookAsync(abc.ABC):+ """Hook that runs at the end of an async span"""+@abc.abstractmethodasync def post_end_span(self,@@ -266,53 +269,86 @@ class PostEndSpanHookAsync(abc.ABC):pass-# THESE ARE NOT IN USE-# TODO -- implement/decide how to use them[email protected]_hook("pre_run_application")-class PreRunApplicationHook(abc.ABC):+class ExecuteMethod(enum.Enum):+ """A set of the application methods the user can call.+ These correspond to interface methods in application.py, and+ allow us to say *which* method is being called for the following hooks."""++ step = "step"+ astep = "astep"+ iterate = "iterate"+ aiterate = "aiterate"+ run = "run"+ arun = "arun"+ stream_result = "stream_result"+ astream_result = "astream_result"++[email protected]_hook("pre_run_execute_call")+class PreApplicationExecuteCallHook(abc.ABC):+ """Hook that runs before an application method (step/iterate/run/stream...) is called."""+@abc.abstractmethod- def pre_run_application(- self, *, app_id: str, partition_key: str, state: "State", **future_kwargs: Any+ def pre_run_execute_call(+ self,+ *,+ app_id: str,+ partition_key: str,+ state: "State",+ method: ExecuteMethod,+ **future_kwargs: Any,):pass[email protected]_hook("pre_run_application")-class PreRunApplicationHookAsync(abc.ABC):[email protected]_hook("pre_run_execute_call")+class PreApplicationExecuteCallHookAsync(abc.ABC):+ """Hook that runs before an async application method (step/iterate/run/stream...) is called."""+@abc.abstractmethod- async def pre_run_application(- self, *, app_id: str, partition_key: str, state: "State", **future_kwargs+ async def pre_run_execute_call(+ self,+ *,+ app_id: str,+ partition_key: str,+ state: "State",+ method: ExecuteMethod,+ **future_kwargs,):pass[email protected]_hook("post_run_application")-class PostRunApplicationHook(abc.ABC):[email protected]_hook("post_run_execute_call")+class PostApplicationExecuteCallHook(abc.ABC):+ """Hook that runs after an application method (step/iterate/run/stream...) is called."""+@abc.abstractmethod- def post_run_application(+ def post_run_execute_call(self,*,app_id: str,partition_key: str,state: "State",- until: list[str],- results: list[dict],+ method: ExecuteMethod,+ exception: Optional[Exception],**future_kwargs,):pass[email protected]_hook("post_run_application")-class PostRunApplicationHookAsync(abc.ABC):[email protected]_hook("post_run_execute_call")+class PostApplicationExecuteCallHookAsync(abc.ABC):+ """Hook that runs after an async application method (step/iterate/run/stream...) is called."""+@abc.abstractmethod- async def post_run_application(+ async def post_run_execute_call(self,*,app_id: str,partition_key: str,state: "State",- until: list[str],- results: list[dict],+ method: ExecuteMethod,+ exception: Optional[Exception],**future_kwargs,):pass@@ -325,10 +361,10 @@ LifecycleAdapter = Union[PreRunStepHookAsync,PostRunStepHook,PostRunStepHookAsync,- PreRunApplicationHook,- PreRunApplicationHookAsync,- PostRunApplicationHook,- PostRunApplicationHookAsync,+ PreApplicationExecuteCallHook,+ PreApplicationExecuteCallHookAsync,+ PostApplicationExecuteCallHook,+ PostApplicationExecuteCallHookAsync,PostApplicationCreateHook,PreStartSpanHook,PreStartSpanHookAsync,diff --git a/docs/reference/lifecycle.rst b/docs/reference/lifecycle.rstindex 6d6c9dfe..74f4d5cc 100644--- a/docs/reference/lifecycle.rst+++ b/docs/reference/lifecycle.rst@@ -34,6 +34,20 @@ and add instances to the application builder to customize your state machines's.. autoclass:: burr.lifecycle.base.PostEndSpanHookAsync:members:+.. autoclass:: burr.lifecycle.base.ExecuteMethod+ :members:++.. autoclass:: burr.lifecycle.base.PreApplicationExecuteCallHook+ :members:++.. autoclass:: burr.lifecycle.base.PreApplicationExecuteCallHookAsync+ :members:++.. autoclass:: burr.lifecycle.base.PostApplicationExecuteCallHook+ :members:++.. autoclass:: burr.lifecycle.base.PostApplicationExecuteCallHookAsync+ :members:These hooks are available for you to use:diff --git a/tests/core/test_application.py b/tests/core/test_application.pyindex d6c4257a..a4a211b6 100644--- a/tests/core/test_application.py+++ b/tests/core/test_application.py@@ -47,7 +47,14 @@ from burr.lifecycle import (PreRunStepHookAsync,internal,)-from burr.lifecycle.base import PostApplicationCreateHook+from burr.lifecycle.base import (+ ExecuteMethod,+ PostApplicationCreateHook,+ PostApplicationExecuteCallHook,+ PostApplicationExecuteCallHookAsync,+ PreApplicationExecuteCallHook,+ PreApplicationExecuteCallHookAsync,+)from burr.lifecycle.internal import LifecycleAdapterSetfrom burr.tracking.base import SyncTrackingClient@@ -121,10 +128,14 @@ base_counter_action_with_inputs = PassedInAction()-class ActionTracker(PreRunStepHook, PostRunStepHook):+class ActionTracker(+ PreRunStepHook, PostRunStepHook, PreApplicationExecuteCallHook, PostApplicationExecuteCallHook+):def __init__(self):self.pre_called = []self.post_called = []+ self.pre_run_execute_calls = []+ self.post_run_execute_calls = []def pre_run_step(self,@@ -151,9 +162,62 @@ class ActionTracker(PreRunStepHook, PostRunStepHook):exception: Exception,**future_kwargs: Any,):- locals()self.post_called.append((action.name, locals()))+ def pre_run_execute_call(+ self,+ *,+ app_id: str,+ partition_key: str,+ state: "State",+ method: ExecuteMethod,+ **future_kwargs: Any,+ ):+ self.pre_run_execute_calls.append(("pre", locals()))++ def post_run_execute_call(+ self,+ *,+ app_id: str,+ partition_key: str,+ state: "State",+ method: ExecuteMethod,+ exception: Optional[Exception],+ **future_kwargs,+ ):+ self.post_run_execute_calls.append(("post", locals()))+++class ExecuteMethodTrackerAsync(+ PreApplicationExecuteCallHookAsync, PostApplicationExecuteCallHookAsync+):+ def __init__(self):+ self.pre_run_execute_calls = []+ self.post_run_execute_calls = []++ async def pre_run_execute_call(+ self,+ *,+ app_id: str,+ partition_key: str,+ state: "State",+ method: ExecuteMethod,+ **future_kwargs: Any,+ ):+ self.pre_run_execute_calls.append(("pre", locals()))++ async def post_run_execute_call(+ self,+ *,+ app_id: str,+ partition_key: str,+ state: "State",+ method: ExecuteMethod,+ exception: Optional[Exception],+ **future_kwargs,+ ):+ self.post_run_execute_calls.append(("post", locals()))+class ActionTrackerAsync(PreRunStepHookAsync, PostRunStepHookAsync):def __init__(self):@@ -1503,6 +1567,9 @@ def test_stream_result_halt_after_unique_ordered_sequence_id():0,1,] # ensure sequence ID is respected+ # One post call/one pre-call, as we call stream_result once+ assert len(action_tracker.post_run_execute_calls) == 1+ assert len(action_tracker.pre_run_execute_calls) == 1async def test_astream_result_halt_after_unique_ordered_sequence_id():@@ -1543,6 +1610,8 @@ async def test_astream_result_halt_after_unique_ordered_sequence_id():0,1,] # ensure sequence ID is respected+ assert len(action_tracker.post_run_execute_calls) == 1+ assert len(action_tracker.pre_run_execute_calls) == 1def test_stream_result_halt_after_run_through_streaming():@@ -1582,6 +1651,8 @@ def test_stream_result_halt_after_run_through_streaming():0,1,] # ensure sequence ID is respected+ assert len(action_tracker.post_run_execute_calls) == 1+ assert len(action_tracker.pre_run_execute_calls) == 1async def test_astream_result_halt_after_run_through_streaming():@@ -1623,6 +1694,8 @@ async def test_astream_result_halt_after_run_through_streaming():0,1,] # ensure sequence ID is respected+ assert len(action_tracker.post_run_execute_calls) == 1+ assert len(action_tracker.pre_run_execute_calls) == 1def test_stream_result_halt_after_run_through_non_streaming():@@ -1667,6 +1740,8 @@ def test_stream_result_halt_after_run_through_non_streaming():assert [item["sequence_id"] for _, item in action_tracker.post_called] == list(range(0, 11)) # ensure sequence ID is respected+ assert len(action_tracker.post_run_execute_calls) == 1+ assert len(action_tracker.pre_run_execute_calls) == 1async def test_astream_result_halt_after_run_through_non_streaming():@@ -1711,6 +1786,8 @@ async def test_astream_result_halt_after_run_through_non_streaming():assert [item["sequence_id"] for _, item in action_tracker.post_called] == list(range(0, 11)) # ensure sequence ID is respected+ assert len(action_tracker.post_run_execute_calls) == 1+ assert len(action_tracker.pre_run_execute_calls) == 1def test_stream_result_halt_after_run_through_final_non_streaming():@@ -1754,6 +1831,8 @@ def test_stream_result_halt_after_run_through_final_non_streaming():assert [item["sequence_id"] for _, item in action_tracker.post_called] == list(range(0, 11)) # ensure sequence ID is respected+ assert len(action_tracker.pre_run_execute_calls) == 1+ assert len(action_tracker.post_run_execute_calls) == 1async def test_astream_result_halt_after_run_through_final_streaming():@@ -1801,6 +1880,8 @@ async def test_astream_result_halt_after_run_through_final_streaming():assert [item["sequence_id"] for _, item in action_tracker.post_called] == list(range(0, 11)) # ensure sequence ID is respected+ assert len(action_tracker.post_run_execute_calls) == 1+ assert len(action_tracker.pre_run_execute_calls) == 1def test_stream_result_halt_before():@@ -1835,6 +1916,8 @@ def test_stream_result_halt_before():assert [item["sequence_id"] for _, item in action_tracker.post_called] == list(range(0, 10)) # ensure sequence ID is respected+ assert len(action_tracker.post_run_execute_calls) == 1+ assert len(action_tracker.pre_run_execute_calls) == 1async def test_astream_result_halt_before():@@ -1873,6 +1956,8 @@ async def test_astream_result_halt_before():assert [item["sequence_id"] for _, item in action_tracker.post_called] == list(range(0, 10)) # ensure sequence ID is respected+ assert len(action_tracker.post_run_execute_calls) == 1+ assert len(action_tracker.pre_run_execute_calls) == 1def test_app_set_state():@@ -1984,13 +2069,13 @@ def test_application_builder_unset():def test_application_run_step_hooks_sync():- tracker = ActionTracker()+ action_tracker = ActionTracker()counter_action = base_counter_action.with_name("counter")result_action = Result("count").with_name("result")app = Application(state=State({}),entrypoint="counter",- adapter_set=internal.LifecycleAdapterSet(tracker),+ adapter_set=internal.LifecycleAdapterSet(action_tracker),partition_key="test",uid="test-123",sequence_id=0,@@ -2003,11 +2088,11 @@ def test_application_run_step_hooks_sync():),)app.run(halt_after=["result"])- assert set(dict(tracker.pre_called).keys()) == {"counter", "result"}- assert set(dict(tracker.post_called).keys()) == {"counter", "result"}+ assert set(dict(action_tracker.pre_called).keys()) == {"counter", "result"}+ assert set(dict(action_tracker.post_called).keys()) == {"counter", "result"}# assert sequence id is incremented- assert tracker.pre_called[0][1]["sequence_id"] == 1- assert tracker.post_called[0][1]["sequence_id"] == 1+ assert action_tracker.pre_called[0][1]["sequence_id"] == 1+ assert action_tracker.post_called[0][1]["sequence_id"] == 1assert {"action","sequence_id",@@ -2015,7 +2100,7 @@ def test_application_run_step_hooks_sync():"inputs","app_id","partition_key",- }.issubset(set(tracker.pre_called[0][1].keys()))+ }.issubset(set(action_tracker.pre_called[0][1].keys()))assert {"sequence_id","result",@@ -2023,11 +2108,15 @@ def test_application_run_step_hooks_sync():"exception","app_id","partition_key",- }.issubset(set(tracker.post_called[0][1].keys()))- assert len(tracker.pre_called) == 11- assert len(tracker.post_called) == 11+ }.issubset(set(action_tracker.post_called[0][1].keys()))+ assert len(action_tracker.pre_called) == 11+ assert len(action_tracker.post_called) == 11# quick inclusion to ensure that the action is not called when we're done running+ assert len(action_tracker.post_run_execute_calls) == 1+ assert len(action_tracker.pre_run_execute_calls) == 1assert app.step() is None # should be None+ assert len(action_tracker.post_run_execute_calls) == 2+ assert len(action_tracker.pre_run_execute_calls) == 2async def test_application_run_step_hooks_async():@@ -2131,6 +2220,8 @@ async def test_application_run_step_runs_hooks():}.issubset(set(hooks[1].post_called[0][1].keys()))assert len(hooks[1].pre_called) == 1assert len(hooks[1].post_called) == 1+ assert len(hooks[0].post_run_execute_calls) == 1+ assert len(hooks[0].pre_run_execute_calls) == 1def test_application_post_application_create_hook():