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
Wires through application context to nodes that request it
elijahbenizzy373149f340d6
diff --git a/burr/core/application.py b/burr/core/application.pyindex ffc6ca63..6c863e80 100644--- a/burr/core/application.py+++ b/burr/core/application.py@@ -6,6 +6,7 @@ import loggingimport pprintimport uuidfrom typing import (+ TYPE_CHECKING,Any,AsyncGenerator,Callable,@@ -42,6 +43,9 @@ from burr.core.state import Statefrom burr.lifecycle.base import LifecycleAdapterfrom burr.lifecycle.internal import LifecycleAdapterSet+if TYPE_CHECKING:+ from burr.tracking.base import TrackingClient+logger = logging.getLogger(__name__)@@ -361,6 +365,14 @@ class ApplicationGraph:entrypoint: Action+class ApplicationContext:+ app_id: str+ partition_key: Optional[str]+ sequence_id: Optional[int]+ tracker: Optional["TrackingClient"]++class Application:def __init__(self,@@ -374,6 +386,7 @@ class Application:adapter_set: Optional[LifecycleAdapterSet] = None,builder: Optional["ApplicationBuilder"] = None,parent_pointer: Optional[burr_types.ParentPointer] = None,+ tracker: Optional["TrackingClient"] = None,):"""Instantiates an Application. This is an internal API -- use the builder!@@ -407,15 +420,18 @@ class Application:parent_pointer=parent_pointer,)# TODO -- consider adding global inputs + global input factories to the builder- self.dependency_factory = {- "__tracer": functools.partial(- visibility.tracing.TracerFactory, lifecycle_adapters=self._adapter_set- )- }+ self._tracker = tracker+if sequence_id is not None:self._set_sequence_id(sequence_id)self._builder = builderself._parent_pointer = parent_pointer+ self.dependency_factory = {+ "__tracer": functools.partial(+ visibility.tracing.TracerFactory, lifecycle_adapters=self._adapter_set+ ),+ "__context": self._context_factory,+ }# @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@@ -438,6 +454,14 @@ class Application:out = self._step(inputs=inputs, _run_hooks=True)return out+ def _context_factory(self, action: Action, sequence_id: int) -> ApplicationContext:+ return ApplicationContext(+ app_id=self._uid,+ tracker=self._tracker,+ partition_key=self._partition_key,+ sequence_id=sequence_id,+ )+def _step(self, inputs: Optional[Dict[str, Any]], _run_hooks: bool = True) -> Optional[Tuple[Action, dict, State]]:@@ -519,13 +543,15 @@ class Application:f"so we're just letting you know some inputs are being skipped.")missing_inputs = required_inputs - set(processed_inputs.keys())- for required_input in list(missing_inputs):+ additional_inputs = optional_inputs - set(processed_inputs.keys())+ for input_ in missing_inputs | additional_inputs:# if we can find it in the dependency factory, we'll use that- if required_input in self.dependency_factory:- processed_inputs[required_input] = self.dependency_factory[required_input](- action, self.sequence_id- )- missing_inputs.remove(required_input)+ # TODO -- figure out what happens if people attempt to override default factory+ # inputs+ if input_ in self.dependency_factory:+ processed_inputs[input_] = self.dependency_factory[input_](action, self.sequence_id)+ if input_ in missing_inputs:+ missing_inputs.remove(input_)if len(missing_inputs) > 0:missing_inputs_dict = {key: "FILL ME IN" for key in missing_inputs}missing_inputs_dict.update({key: "..." for key in inputs.keys()})@@ -1420,6 +1446,15 @@ class Application:"""return self._state.get(SEQUENCE_ID)+ @property+ def context(self) -> ApplicationContext:+ """Gives the application context.+ This has information you need for the tracker, sequence ID, application, etc...++ :return: Application context+ """+ return self._context_factory(self.get_next_action(), self.sequence_id)+def _increment_sequence_id(self):if SEQUENCE_ID not in self._state:self._state = self._state.update(**{SEQUENCE_ID: 0})@@ -1536,6 +1571,7 @@ class ApplicationBuilder:self.fork_from_partition_key: Optional[str] = Noneself.fork_from_sequence_id: Optional[int] = Noneself.loaded_from_fork: bool = False+ self.tracker = Nonedef with_identifiers(self, app_id: str = None, partition_key: str = None, sequence_id: int = None@@ -1672,8 +1708,8 @@ class ApplicationBuilder:def with_tracker(self,tracker: Union[- Literal["local"], LifecycleAdapter- ] = "local", # TODO -- tighten type-check for tracker. For now it has the lifecycle adapter+ Literal["local"], "TrackingClient" # TODO -- support async tracking+ ] = "local",project: str = "default",params: Dict[str, Any] = None,):@@ -1710,6 +1746,7 @@ class ApplicationBuilder:raise ValueError("Params are not supported for object-specified trackers, these are already initialized!")+ self.tracker = trackerreturn selfdef initialize_from(@@ -1897,4 +1934,5 @@ class ApplicationBuilder:)if self.loaded_from_forkelse None,+ tracker=self.tracker,)diff --git a/burr/tracking/base.py b/burr/tracking/base.pynew file mode 100644index 00000000..25aa473f--- /dev/null+++ b/burr/tracking/base.py@@ -0,0 +1,26 @@+import abc++from burr.lifecycle import (+ PostApplicationCreateHook,+ PostEndSpanHook,+ PostRunStepHook,+ PreRunStepHook,+ PreStartSpanHook,+)+++class SyncTrackingClient(+ PostApplicationCreateHook,+ PreRunStepHook,+ PostRunStepHook,+ PreStartSpanHook,+ PostEndSpanHook,+ abc.ABC,+):+ """Base class for synchronous tracking clients. All tracking clients must implement from this+ TODO -- create an async tracking client"""++ pass+++TrackingClient = SyncTrackingClientdiff --git a/burr/tracking/client.py b/burr/tracking/client.pyindex cf9d361a..c3e270cb 100644--- a/burr/tracking/client.py+++ b/burr/tracking/client.py@@ -1,11 +1,18 @@+import abcimport datetimeimport jsonimport loggingimport osimport reimport traceback+from abc import ABCfrom typing import Any, Dict, Optional+try:+ from typing import Self+except ImportError:+ Self = "Self"+from burr import systemfrom burr.common import types as burr_typesfrom burr.core import Action, ApplicationGraph, State, serde@@ -64,12 +71,29 @@ def _allowed_project_name(project_name: str, on_windows: bool) -> bool:return bool(re.match(pattern, project_name))-class LocalTrackingClient(+class SyncTrackingClient(PostApplicationCreateHook,PreRunStepHook,PostRunStepHook,PreStartSpanHook,PostEndSpanHook,+ ABC,+):+ @abc.abstractmethod+ def spawn(self) -> Self:+ """Spawns a tracking client with the correct parent pointer.+ Also potentially logs the spawn event to the tracking system.++ This enables you to launch a Burr application inside another Burr application,+ and have the parent application track the child application.++ :return:+ """+ pass+++class LocalTrackingClient(+ SyncTrackingClient,BaseStateLoader,):"""Tracker to track locally -- goes along with the Burr UI. Writes@@ -330,6 +354,9 @@ class LocalTrackingClient(# TODO:return []+ def spawn(self) -> Self:+ raise ValueError("TODO")+def load(self, partition_key: str, app_id: Optional[str], sequence_id: Optional[int] = None, **kwargs) -> Optional[PersistedStateData]:diff --git a/tests/core/test_application.py b/tests/core/test_application.pyindex 8924347f..c51ac4b2 100644--- a/tests/core/test_application.py+++ b/tests/core/test_application.py@@ -25,6 +25,7 @@ from burr.core.application import (PRIOR_STEP,Application,ApplicationBuilder,+ ApplicationContext,Transition,_arun_function,_arun_multi_step_streaming_action,@@ -50,6 +51,7 @@ from burr.lifecycle import ()from burr.lifecycle.base import PostApplicationCreateHookfrom burr.lifecycle.internal import LifecycleAdapterSet+from burr.tracking.base import SyncTrackingClientclass PassedInAction(Action):@@ -2302,7 +2304,7 @@ def test_application_builder_initialize_fork_errors_on_same_app_id():)-def tests_application_builder_initialize_fork_app_id_happy_pth():+def test_application_builder_initialize_fork_app_id_happy_pth():"""Tests that forking properly works"""counter_action = base_counter_action.with_name("counter")result_action = Result("count").with_name("result")@@ -2325,3 +2327,107 @@ def tests_application_builder_initialize_fork_app_id_happy_pth():assert app.uid != old_app_idassert app.state == State({"count": 5, "__PRIOR_STEP": "counter", "__SEQUENCE_ID": 5})assert app.parent_pointer.app_id == old_app_id+++class NoOpTracker(SyncTrackingClient):+ def __init__(self, unique_id: str):+ self.unique_id = unique_id++ def post_application_create(self, **future_kwargs: Any):+ pass++ def pre_run_step(self, **future_kwargs: Any):+ pass++ def post_run_step(self, **future_kwargs: Any):+ pass++ def pre_start_span(self, **future_kwargs: Any):+ pass++ def post_end_span(self, **future_kwargs: Any):+ pass+++def test_application_exposes_app_context():+ """Tests that we can get the context from the application correctly"""+ counter_action = base_counter_action.with_name("counter")+ result_action = Result("count").with_name("result")+ app = (+ ApplicationBuilder()+ .with_actions(counter_action, result_action)+ .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()+ )+ context = app.context+ assert context.app_id == "test123"+ assert context.partition_key == "user123"+ assert context.sequence_id == 5+ assert context.tracker.unique_id == "unique_tracker_name"+++def test_application_passes_context_when_declared():+ """Tests that the context is passed to the function correctly"""+ context_list = []++ @action(reads=["count"], writes=["count"])+ def context_counter(+ state: State, __context: ApplicationContext+ ) -> Tuple[Dict[str, Any], State]:+ context_list.append(__context)+ return {}, state.update(count=state["count"] + 1)++ result_action = Result("count")+ app = (+ ApplicationBuilder()+ .with_actions(counter=context_counter, result=result_action)+ .with_transitions(("counter", "counter", expr("count < 10")), ("counter", "result"))+ .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"])+ sequence_ids = [context.sequence_id for context in context_list]+ assert sequence_ids == list(range(6, 16))+ app_ids = set(context.app_id for context in context_list)+ assert app_ids == {"test123"}+ trackers = set(context.tracker.unique_id for context in context_list)+ assert trackers == {"unique_tracker_name"}+++def test_optional_context_in_dependency_factories():+ """Tests that the context is passed to the function correctly when nulled out.+ TODO -- gret this to tests without instantiating an application."""+ context_list = []++ @action(reads=["count"], writes=["count"])+ def context_counter(+ state: State, __context: ApplicationContext = None+ ) -> Tuple[Dict[str, Any], State]:+ context_list.append(__context)+ return {}, state.update(count=state["count"] + 1)++ result_action = Result("count")+ app = (+ ApplicationBuilder()+ .with_actions(counter=context_counter, result=result_action)+ .with_transitions(("counter", "counter", expr("count < 10")), ("counter", "result"))+ .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()+ )+ inputs = app._process_inputs({}, app.get_next_action())+ assert "__context" in inputs # it should be there+ assert inputs["__context"] is not None # it should not be None+ assert inputs["__context"].app_id == "test123" # it should be the correct context+ assert (+ inputs["__context"].tracker.unique_id == "unique_tracker_name"+ ) # it should be the correct context