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 application graph + fixes bug in application
elijahbenizzybd1f5d6ef70a
diff --git a/burr/core/__init__.py b/burr/core/__init__.pyindex 8140573e..3445bdff 100644--- a/burr/core/__init__.py+++ b/burr/core/__init__.py@@ -1,5 +1,5 @@from burr.core.action import Action, Condition, Result, action, default, expr, when-from burr.core.application import Application, ApplicationBuilder+from burr.core.application import Application, ApplicationBuilder, ApplicationGraphfrom burr.core.state import State__all__ = [@@ -7,6 +7,7 @@ __all__ = ["Action","Application","ApplicationBuilder",+ "ApplicationGraph","Condition","default","expr",diff --git a/burr/core/application.py b/burr/core/application.pyindex 3571404c..1dceefa7 100644--- a/burr/core/application.py+++ b/burr/core/application.py@@ -6,6 +6,7 @@ from typing import (Any,AsyncGenerator,Callable,+ Dict,Generator,List,Literal,@@ -95,7 +96,7 @@ def _run_reducer(reducer: Reducer, state: State, result: dict, name: str) -> Staf"Action {name} attempted to write to keys {extra_keys} "f"that it did not declare. It declared: ({reducer.writes})!")- return state.merge(new_state.update(**{PRIOR_STEP: name}))+ return state.merge(new_state)def _create_dict_string(kwargs: dict) -> str:@@ -156,6 +157,20 @@ async def _arun_single_step_action(action: SingleStepAction, state: State) -> Tureturn result, state.merge(new_state.subset(*action.writes)) # we just want the writes action+class ApplicationGraph:+ """User-facing representation of the state machine. This has++ #. All the action objects+ #. All the transition objects+ #. The entrypoint action+ """++ actions: List[Action]+ transitions: List[Transition]+ entrypoint: Action++class Application:def __init__(self,@@ -172,6 +187,7 @@ class Application:self._initial_step = initial_stepself._state = stateself._adapter_set = adapter_set if adapter_set is not None else LifecycleAdapterSet()+ self._graph = self._create_graph()def step(self) -> Optional[Tuple[Action, dict, State]]:"""Performs a single step, advancing the state machine along.@@ -200,6 +216,7 @@ class Application:else:result = _run_function(next_action, self._state)new_state = _run_reducer(next_action, self._state, result, next_action.name)+ new_state = new_state.update(**{PRIOR_STEP: next_action.name})self._set_state(new_state)except Exception as e:exc = e@@ -238,6 +255,7 @@ class Application:else:result = await _arun_function(next_action, self._state)new_state = _run_reducer(next_action, self._state, result, next_action.name)+ new_state = new_state.update(**{PRIOR_STEP: next_action.name})except Exception as e:exc = elogger.exception(_format_error_message(next_action, self._state))@@ -280,10 +298,10 @@ class Application:)while not condition():- result = self.step()- if result is None:+ state_output = self.step()+ if state_output is None:break- action, result, state = result+ action, result, state = state_outputif action.name in until:seen_results.add(action.name)results[index_by_name[action.name]] = result@@ -462,9 +480,23 @@ class Application:"""return self._state+ def _create_graph(self) -> ApplicationGraph:+ """Internal-facing utility function for creating an ApplicationGraph"""+ all_actions = {action.name: action for action in self._actions}+ return ApplicationGraph(+ actions=self._actions,+ transitions=self._transitions,+ entrypoint=all_actions[self._initial_step],+ )+@property- def actions(self) -> List[Action]:- return self._actions+ def graph(self) -> ApplicationGraph:+ """Application graph object -- if you want to inspect, visualize, etc..+ this is what you want.++ :return: The application graph object+ """+ return self._graphdef _assert_set(value: Optional[Any], field: str, method: str):@@ -524,6 +556,14 @@ class ApplicationBuilder:self.lifecycle_adapters: List[LifecycleAdapter] = list()def with_state(self, **kwargs) -> "ApplicationBuilder":+ """Sets initial values in the state. If you want to load from a prior state,+ you can do so here and pass the values in.++ TODO -- enable passing in a `state` object instead of `**kwargs`++ :param kwargs: Key-value pairs to set in the state+ :return: The application builder for future chaining.+ """if self.state is not None:self.state = self.state.update(**kwargs)else:@@ -534,8 +574,8 @@ class ApplicationBuilder:"""Adds an entrypoint to the application. This is the action that will be run first.This can only be called once.- :param action:- :return:+ :param action: The name of the action to set as the entrypoint+ :return: The application builder for future chaining."""# TODO -- validate only called onceself.start = action@@ -599,7 +639,24 @@ class ApplicationBuilder:self.lifecycle_adapters.extend(adapters)return self+ def with_tracker(+ self, project: str, tracker: Literal["local"] = "local", params: Dict[str, Any] = None+ ):+ if params is None:+ params = {}+ if tracker == "local":+ from burr.tracking.client import LocalTrackingClient++ self.lifecycle_adapters.append(LocalTrackingClient(project=project, **params))+ else:+ raise ValueError(f"Tracker {tracker} not supported")+ return self+def build(self) -> Application:+ """Builds the application.++ :return: The application object+ """_validate_actions(self.actions)actions_by_name = {action.name: action for action in self.actions}all_actions = set(actions_by_name.keys())diff --git a/burr/integrations/streamlit.py b/burr/integrations/streamlit.pyindex f7f77565..2cba0b67 100644--- a/burr/integrations/streamlit.py+++ b/burr/integrations/streamlit.py@@ -173,7 +173,7 @@ def render_action(state: AppState):"""app: Application = state.appcurrent_node = state.current_action- actions = {action.name: action for action in app.actions}+ actions = {action.name: action for action in app.graph.actions}if current_node is None:st.markdown("No current action.")returndiff --git a/docs/concepts/state-machine.rst b/docs/concepts/state-machine.rstindex a34cc324..1bcc5000 100644--- a/docs/concepts/state-machine.rst+++ b/docs/concepts/state-machine.rst@@ -91,3 +91,14 @@ Run just calls out to ``iterate`` and returns the final state.Currently the ``until`` variable is a ``or`` gate (E.G. ``any_complete``), although we will be adding an ``and`` gate (E.G. ``all_complete``),and the ability to run until the state machine naturally executes (``until=None``).++----------+Inspection+----------++You can ask various questions of the state machine using publicly-supported APIs:++- ``application.graph`` will give you a static reprsentation of the state machine with enough information to visualize+- ``application.state`` will give you the current state of the state machine. Note that if you modify it the results will not show up -- state is immutable!++See the :ref:`application docs <applicationref>`diff --git a/docs/reference/application.rst b/docs/reference/application.rstindex 87455732..21aa7399 100644--- a/docs/reference/application.rst+++ b/docs/reference/application.rst@@ -9,7 +9,12 @@ and not the ``Application`` class directly... autoclass:: burr.core.application.ApplicationBuilder:members:+.. _applicationref:+.. autoclass:: burr.core.application.Application:members:.. automethod:: __init__++.. autoclass:: burr.core.application.ApplicationGraph+ :members:diff --git a/tests/core/test_application.py b/tests/core/test_application.pyindex 48db4bd9..8f87c6b3 100644--- a/tests/core/test_application.py+++ b/tests/core/test_application.py@@ -7,6 +7,7 @@ import pytestfrom burr.core import Statefrom burr.core.action import Action, Condition, Result, SingleStepAction, defaultfrom burr.core.application import (+ PRIOR_STEP,Application,ApplicationBuilder,Transition,@@ -202,6 +203,7 @@ def test_app_step():action, result, state = app.step()assert action.name == "counter"assert result == {"counter": 1}+ assert state[PRIOR_STEP] == "counter" # internal contract, not part of the public APIdef test_app_step_broken(caplog):@@ -241,6 +243,7 @@ async def test_app_astep():action, result, state = await app.astep()assert action.name == "counter_async"assert result == {"counter": 1}+ assert state[PRIOR_STEP] == "counter_async" # internal contract, not part of the public APIasync def test_app_astep_broken(caplog):@@ -606,3 +609,21 @@ async def test_application_runs_hooks_async():assert set(tracker.post_called) == {"counter", "result"}assert len(tracker.pre_called) == 11assert len(tracker.post_called) == 11+++async def test_application_gives_graph():+ counter_action = base_counter_action.with_name("counter")+ result_action = Result(fields=["counter"]).with_name("result")+ app = Application(+ actions=[counter_action, result_action],+ transitions=[+ Transition(counter_action, result_action, Condition.expr("counter >= 10")),+ Transition(counter_action, counter_action, default),+ ],+ state=State({}),+ initial_step="counter",+ )+ graph = app.graph+ assert len(graph.actions) == 2+ assert len(graph.transitions) == 2+ assert graph.entrypoint.name == "counter"