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.

Adds initial implementation of Burr library

elijahbenizzy8f4de9728c53
diff --git a/burr/__init__.py b/burr/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/burr/core/__init__.py b/burr/core/__init__.py
new file mode 100644
index 00000000..52747b3c
--- /dev/null
+++ b/burr/core/__init__.py
@@ -0,0 +1,15 @@
+from burr.core.action import Action, Condition, Result, default, expr, when
+from burr.core.application import Application, ApplicationBuilder
+from burr.core.state import State
+
+__all__ = [
+ "Action",
+ "ApplicationBuilder",
+ "Condition",
+ "Result",
+ "default",
+ "when",
+ "expr",
+ "Application",
+ "State",
+]
diff --git a/burr/core/action.py b/burr/core/action.py
new file mode 100644
index 00000000..fe1b8fc5
--- /dev/null
+++ b/burr/core/action.py
@@ -0,0 +1,165 @@
+import abc
+import ast
+import copy
+import inspect
+from typing import Callable, List
+
+from burr.core.state import State
+
+
+class Function(abc.ABC):
+ @property
+ @abc.abstractmethod
+ def reads(self) -> list[str]:
+ pass
+
+ @abc.abstractmethod
+ def run(self, state: State) -> dict:
+ pass
+
+ def is_async(self):
+ return inspect.iscoroutinefunction(self.run)
+
+
+class Reducer(abc.ABC):
+ @property
+ @abc.abstractmethod
+ def writes(self) -> list[str]:
+ pass
+
+ @abc.abstractmethod
+ def update(self, result: dict, state: State) -> State:
+ pass
+
+
+class Action(Function, Reducer, abc.ABC):
+ def __init__(self):
+ """Represents an action in a state machine. This is the base class from which:
+
+ 1. Custom actions
+ 2. Conditions
+ 3. Results
+
+ All extend this class. Note that name is optional so that APIs can set the
+ name on these actions as part of instantiation.
+ When they're used, they must have a name set.
+ """
+ self._name = None
+
+ def with_name(self, name: str) -> "Action":
+ """Returns a copy of the given action with the given name. Why do we need this?
+ We instantiate actions without names, and then set them later. This is a way to
+ make the API cleaner/consolidate it, and the ApplicationBuilder will end up handling it
+ for you, in the with_actions(...) method, which is the only way to use actions.
+
+ Note they can also take in names in the constructor for testing, but otherwise this is
+ not something users will ever have to think about.
+
+ :param name: Name to set
+ :return: A new action with the given name
+ """
+ if self._name is not None:
+ raise ValueError(
+ f"Name of {self} already set to {self._name} -- cannot set name to {name}"
+ )
+ # TODO -- ensure that we're not mutating anything later on
+ # If we are, we may want to copy more intelligently
+ new_action = copy.copy(self)
+ new_action._name = name
+ return new_action
+
+ @property
+ def name(self) -> str:
+ """Gives the name of this action. This should be unique
+ across your agent."""
+ return self._name
+
+ def __repr__(self):
+ read_repr = ", ".join(self.reads) if self.reads else "{}"
+ write_repr = ", ".join(self.writes) if self.writes else "{}"
+ return f"{self.name}: {read_repr} -> {write_repr}"
+
+
+class Condition(Function):
+ KEY = "PROCEED"
+
+ def __init__(self, keys: List[str], resolver: Callable[[State], bool], name: str = None):
+ self._resolver = resolver
+ self._keys = keys
+ self._name = name
+
+ @staticmethod
+ def expr(expr: str) -> "Condition":
+ """Returns a condition that evaluates the given expression"""
+ tree = ast.parse(expr, mode="eval")
+
+ # Visitor class to collect variable names
+ class NameVisitor(ast.NodeVisitor):
+ def __init__(self):
+ self.names = set()
+
+ def visit_Name(self, node):
+ self.names.add(node.id)
+
+ # Visit the nodes and collect variable names
+ visitor = NameVisitor()
+ visitor.visit(tree)
+ keys = list(visitor.names)
+
+ # Compile the expression into a callable function
+ def condition_func(state: State) -> bool:
+ __globals = state.get_all() # we can get all becuase externally we will subset
+ return eval(compile(tree, "<string>", "eval"), {}, __globals)
+
+ return Condition(keys, condition_func, name=expr)
+
+ def run(self, state: State) -> dict:
+ return {Condition.KEY: self._resolver(state)}
+
+ @property
+ def reads(self) -> list[str]:
+ return self._keys
+
+ @classmethod
+ def when(cls, **kwargs):
+ """Returns a condition that checks if the given keys are in the
+ state and equal to the given values."""
+ keys = list(kwargs.keys())
+
+ def condition_func(state: State) -> bool:
+ for key, value in kwargs.items():
+ if state.get(key) != value:
+ return False
+ return True
+
+ name = f"{', '.join(f'{key}={value}' for key, value in sorted(kwargs.items()))}"
+ return Condition(keys, condition_func, name=name)
+
+ @property
+ def name(self) -> str:
+ return self._name
+
+
+default = Condition([], lambda _: True, name="default")
+when = Condition.when
+expr = Condition.expr
+
+
+class Result(Action):
+ def __init__(self, fields: list[str]):
+ super(Result, self).__init__()
+ self._fields = fields
+
+ def run(self, state: State) -> dict:
+ return {key: value for key, value in state.get_all().items() if key in self._fields}
+
+ def update(self, result: dict, state: State) -> State:
+ return state # does not modify state in any way
+
+ @property
+ def reads(self) -> list[str]:
+ return self._fields
+
+ @property
+ def writes(self) -> list[str]:
+ return []
diff --git a/burr/core/application.py b/burr/core/application.py
new file mode 100644
index 00000000..686882ef
--- /dev/null
+++ b/burr/core/application.py
@@ -0,0 +1,520 @@
+import collections
+import dataclasses
+import logging
+from typing import Any, AsyncGenerator, Generator, List, Literal, Optional, Set, Tuple, Union
+
+from burr.core.action import Action, Condition, Function, Reducer, default
+from burr.core.state import State
+from burr.lifecycle.base import LifecycleAdapter
+from burr.lifecycle.internal import LifecycleAdapterSet
+
+logger = logging.getLogger(__name__)
+
+
+class Transition:
+ """Internal, utility class"""
+
+ from_: Action
+ to: Action
+ condition: Condition
+
+
+TerminationCondition = Literal["any_complete", "all_complete"]
+
+PRIOR_STEP = "__PRIOR_STEP"
+
+
+def _run_function(function: Function, state: State) -> dict:
+ """Runs a function, returning the result of running the function.
+ Note this restricts the keys in the state to only those that the
+ function reads.
+
+ :param function:
+ :param state:
+ :return:
+ """
+ if function.is_async():
+ raise ValueError(
+ f"Cannot run async: {function} "
+ "in non-async context. Use astep()/aiterate()/arun() "
+ "instead...)"
+ )
+ state_to_use = state.subset(*function.reads)
+ return function.run(state_to_use)
+
+
+async def _arun_function(function: Function, state: State) -> dict:
+ """Runs a function, returning the result of running the function.
+ Async version of the above.
+
+ :param function:
+ :param state:
+ :return:
+ """
+ state_to_use = state.subset(*function.reads)
+ return await function.run(state_to_use)
+
+
+def _run_reducer(reducer: Reducer, state: State, result: dict, name: str) -> State:
+ """Runs the reducer, returning the new state. Note this restricts the
+ keys in the state to only those that the function writes.
+
+ :param reducer:
+ :param state:
+ :param result:
+ :return:
+ """
+ state_to_use = state.subset(*reducer.writes)
+ new_state = reducer.update(result, state_to_use)
+ keys_in_new_state = set(new_state.keys())
+ extra_keys = keys_in_new_state - set(reducer.writes)
+ if extra_keys:
+ raise ValueError(
+ f"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}))
+
+
+class Application:
+ def __init__(
+ self,
+ actions: List[Action],
+ transitions: List[Transition],
+ state: State,
+ initial_step: str,
+ adapter_set: Optional[LifecycleAdapterSet] = None,
+ ):
+ self._action_map = {action.name: action for action in actions}
+ self._adjacency_map = Application._create_adjacency_map(transitions)
+ self._transitions = transitions
+ self._actions = actions
+ self._initial_step = initial_step
+ self._state = state
+ self._adapter_set = adapter_set if adapter_set is not None else LifecycleAdapterSet()
+
+ def step(self) -> 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
+ the action, and the new state.
+
+ Use this if you just want to do something with the state and not rely on generators.
+ E.G. press forward/backwards, hnuman in the loop, etc... Odds are this is not
+ the method you want -- you'll want iterate() (if you want to see the state/
+ results along the way), or run() (if you just want the final state/results).
+
+ :return: Tuple[Function, dict, State] -- the function that was just ran, the result of running it, and the new state
+ """
+ next_action = self.get_next_action()
+ self._adapter_set.call_all_lifecycle_hooks_sync(
+ "pre_run_step", action=next_action, state=self._state
+ )
+ if next_action is None:
+ return None
+ exc = None
+ result = None
+ new_state = self._state
+ try:
+ result = _run_function(next_action, self._state)
+ new_state = _run_reducer(next_action, self._state, result, next_action.name)
+ self._set_state(new_state)
+ except Exception as e:
+ exc = e
+ raise e
+ finally:
+ self._adapter_set.call_all_lifecycle_hooks_sync(
+ "post_run_step", action=next_action, state=new_state, result=result, exception=exc
+ )
+ return next_action, result, new_state
+
+ async def astep(self) -> Optional[Tuple[Action, dict, State]]:
+ """Asynchronous version of step.
+
+ :return:
+ """
+ next_action = self.get_next_action()
+ if next_action is None:
+ return None
+ await self._adapter_set.call_all_lifecycle_hooks_async(
+ "pre_run_step", action=next_action, state=self._state
+ )
+ 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 delegatees hooks to the synchronous version, so we'll call all of them as well
+ return self.step()
+ result = await _arun_function(next_action, self._state)
+ new_state = _run_reducer(next_action, self._state, result, next_action.name)
+ except Exception as e:
+ exc = e
+ raise e
+ finally:
+ await self._adapter_set.call_all_lifecycle_hooks_sync_and_async(
+ "post_run_step", action=next_action, state=new_state, result=result, exception=exc
+ )
+ self._set_state(new_state)
+ return next_action, result, new_state
+
+ def iterate(
+ self, *, until: list[str], gate: TerminationCondition = "any_complete"
+ ) -> Generator[Tuple[Action, dict, State], None, Tuple[State, List[dict]]]:
+ """Returns a generator that calls step() in a row, enabling you to see the state
+ of the system as it updates. Note this returns a generator, and also the final result
+ (for convenience).
+
+ :param until: The list of actions to run until -- these must be strings
+ that match the names of the actions.
+ :param gate: The gate to run until. This can be "any_complete" or "all_complete"
+ :return: Each iteration returns the result of running `step`
+ The final result is the current state + results in the order that they were specified.
+ """
+
+ if gate != "any_complete":
+ raise NotImplementedError(
+ "Only any_complete is supported for now -- "
+ "please reach out to the developers to unblock other gate types!"
+ )
+
+ results: List[Optional[dict]] = [None for _ in until]
+ index_by_name = {name: index for index, name in enumerate(until)}
+ seen_results = set()
+
+ condition = (
+ lambda: any(item in seen_results for item in until)
+ if gate == "any_complete"
+ else lambda: len(seen_results) == len(until)
+ )
+
+ while not condition():
+ result = self.step()
+ if result is None:
+ break
+ action, result, state = result
+ if action.name in until:
+ seen_results.add(action.name)
+ results[index_by_name[action.name]] = result
+ yield action, result, state
+ return self._state, results
+
+ async def aiterate(
+ self, *, until: list[str], gate: TerminationCondition = "any_complete"
+ ) -> AsyncGenerator[Tuple[Action, dict, State], Tuple[State, List[dict]]]:
+ """Returns a generator that calls step() in a row, enabling you to see the state
+ of the system as it updates. This is the asynchronous version so it has no capability of t
+
+ :param until: The list of actions to run until -- these must be strings
+ that match the names of the action.
+ :param gate: The gate to run until. This can be "any_complete" or "all_complete"
+ :return: Each iteration returns the result of running `step`
+ The final result is the current state + results in the order that they were specified.
+ """
+
+ seen_results = set()
+ condition = (
+ lambda: any(item in seen_results for item in until)
+ if gate == "any_complete"
+ else lambda: len(seen_results) == len(until)
+ )
+
+ while not condition():
+ result = await self.astep()
+ if result is None:
+ break
+ action, result, state = result
+ if action.name in until:
+ seen_results.add(action.name)
+ yield action, result, state
+
+ def run(
+ self,
+ *,
+ until: list[str],
+ gate: TerminationCondition = "any_complete",
+ ) -> Tuple[State, List[dict]]:
+ """
+
+ :param gate:
+ :param until:
+ :return:
+ """
+ gen = self.iterate(until=until, gate=gate)
+ while True:
+ try:
+ next(gen)
+ except StopIteration as e:
+ return e.value
+
+ async def arun(
+ self,
+ *,
+ until: list[str],
+ gate: TerminationCondition = "any_complete",
+ ):
+ """Asynchronous version of run.
+
+ :param gate:
+ :param until:
+ :return:
+ """
+ state = self._state
+ results: List[Optional[dict]] = [None for _ in until]
+ index_by_name = {name: index for index, name in enumerate(until)}
+ async for action, result, state in self.aiterate(until=until, gate=gate):
+ if action.name in until:
+ results[index_by_name[action.name]] = result
+ return state, results
+
+ def visualize(
+ self,
+ output_file_path: str,
+ include_conditions: bool = False,
+ include_state: bool = False,
+ view: bool = False,
+ **graphviz_kwargs: Any,
+ ):
+ try:
+ import graphviz # noqa: F401
+ except ModuleNotFoundError:
+ logger.exception(
+ " graphviz is required for visualizing the application graph. Install it with:"
+ '\n\n pip install "burr[visualization]" or pip install graphviz \n\n'
+ )
+ return
+ digraph_attr = dict(
+ graph_attr=dict(
+ rankdir="TB",
+ ranksep="0.4",
+ compound="false",
+ concentrate="false",
+ ),
+ )
+ for g_key, g_value in graphviz_kwargs.items():
+ if isinstance(g_value, dict):
+ digraph_attr[g_key].update(**g_value)
+ else:
+ digraph_attr[g_key] = g_value
+ digraph = graphviz.Digraph(**digraph_attr)
+ for action in self._actions:
+ label = (
+ action.name
+ if not include_state
+ else f"{action.name}({', '.join(action.reads)}): {', '.join(action.writes)}"
+ )
+ digraph.node(action.name, label=label, shape="box", style="rounded")
+ for transition in self._transitions:
+ condition = transition.condition
+ digraph.edge(
+ transition.from_.name,
+ transition.to.name,
+ label=condition.name if include_conditions and condition is not default else None,
+ style="dashed" if transition.condition is not default else "solid",
+ )
+ digraph.render(output_file_path, view=view)
+ return digraph
+
+ @staticmethod
+ def _create_adjacency_map(transitions: List[Transition]) -> dict:
+ adjacency_map = collections.defaultdict(list)
+ for transition in transitions:
+ from_ = transition.from_
+ to = transition.to
+ adjacency_map[from_.name].append((to.name, transition.condition))
+ return adjacency_map
+
+ def _set_state(self, new_state: State):
+ self._state = new_state
+
+ def get_next_action(self) -> Optional[Action]:
+ if PRIOR_STEP not in self._state:
+ return self._action_map[self._initial_step]
+ possibilities = self._adjacency_map[self._state[PRIOR_STEP]]
+ for next_action, condition in possibilities:
+ if condition.run(self._state)[Condition.KEY]:
+ return self._action_map[next_action]
+ return None
+
+ def update_state(self, new_state: State):
+ """Updates state -- this is meant to be called if you need to do
+ anything with the state. For example:
+ 1. Reset it (after going through a loop)
+ 2. Store to some external source/log out
+
+ :param new_state:
+ :return:
+ """
+ self._state = new_state
+
+ @property
+ def state(self) -> State:
+ """Gives the state. Recall that state is purely immutable
+ -- anything you do with this state will not be persisted unless you
+ subsequently call update_state.
+
+ :return: The current state object.
+ """
+ return self._state
+
+ @property
+ def actions(self) -> List[Action]:
+ return self._actions
+
+
+def _assert_set(value: Optional[Any], field: str, method: str):
+ if value is None:
+ raise ValueError(
+ f"Must set {field} before building application! Do so with ApplicationBuilder.{method}"
+ )
+
+
+def _validate_transitions(
+ transitions: Optional[List[Tuple[str, str, Condition]]], actions: Set[str]
+):
+ _assert_set(transitions, "_transitions", "with_transitions")
+ exhausted = {} # items for which we have seen a default transition
+ for from_, to, condition in transitions:
+ if from_ not in actions:
+ raise ValueError(
+ f"Transition source: {from_} not found in actions! "
+ f"Please add to actions using with_actions({from_}=...)"
+ )
+ if to not in actions:
+ raise ValueError(
+ f"Transition target: {to} not found in actions! "
+ f"Please add to actions using with_actions({to}=...)"
+ )
+ if condition.name == "default": # we have seen a default transition
+ if from_ in exhausted:
+ raise ValueError(
+ f"Transition {from_} -> {to} is redundant -- "
+ f"a default transition has already been set for {from_}"
+ )
+ exhausted[from_] = True
+ return True
+
+
+def _validate_start(start: Optional[str], actions: Set[str]):
+ _assert_set(start, "_start", "with_entrypoint")
+ if start not in actions:
+ raise ValueError(
+ f"Entrypoint: {start} not found in actions. Please add "
+ f"using with_actions({start}=...)"
+ )
+
+
+def _validate_actions(actions: Optional[List[Action]]):
+ _assert_set(actions, "_actions", "with_actions")
+ if len(actions) == 0:
+ raise ValueError("Must have at least one action in the application!")
+
+
+class ApplicationBuilder:
+ state: State = dataclasses.field(default_factory=State)
+ transitions: List[Tuple[str, str, Condition]] = None
+ actions: List[Action] = None
+ start: str = None
+ lifecycle_adapters: List[LifecycleAdapter] = dataclasses.field(default_factory=list)
+
+ def with_state(self, **kwargs) -> "ApplicationBuilder":
+ if self.state is not None:
+ self.state = self.state.update(**kwargs)
+ else:
+ self.state = State(kwargs)
+ return self
+
+ def with_entrypoint(self, action: str) -> "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:
+ """
+ # TODO -- validate only called once
+ self.start = action
+ return self
+
+ def with_actions(self, **actions: Action) -> "ApplicationBuilder":
+ """Adds an action to the application. The actions are granted names (using the with_name)
+ method post-adding, using the kw argument. Thus, this is the only supported way to add actions.
+
+ :param actions: Actions to add, keyed by name
+ :return: The application builder for future chaining.
+ """
+ if self.actions is None:
+ self.actions = []
+ for key, value in actions.items():
+ self.actions.append(value.with_name(key))
+ return self
+
+ def with_transitions(
+ self,
+ *transitions: Union[
+ Tuple[Union[str, list[str]], str], Tuple[Union[str, list[str]], str, Condition]
+ ],
+ ) -> "ApplicationBuilder":
+ """Adds transitions to the application. Transitions are specified as tuples of either:
+ 1. (from, to, condition)
+ 2. (from, to) -- condition is set to DEFAULT (which is a fallback)
+
+ Transitions will be evaluated in order of specification -- if one is met, the others will not be evaluated.
+ Note that one transition can be terminal -- the system doesn't have
+
+
+ :param transitions: Transitions to add
+ :return: The application builder for future chaining.
+ """
+ if self.transitions is None:
+ self.transitions = []
+ for transition in transitions:
+ from_, to_, *conditions = transition
+ if len(conditions) > 0:
+ condition = conditions[0]
+ else:
+ condition = default
+ if not isinstance(from_, list):
+ from_ = [from_]
+ for action in from_:
+ if not isinstance(action, str):
+ raise ValueError(f"Transition source must be a string, not {action}")
+ if not isinstance(to_, str):
+ raise ValueError(f"Transition target must be a string, not {to_}")
+ self.transitions.append((action, to_, condition))
+ return self
+
+ def with_hooks(self, *adapters: LifecycleAdapter) -> "ApplicationBuilder":
+ """Adds a lifecycle adapter to the application. This is a way to add hooks to the application so that
+ they are run at the appropriate times. You can use this to synchronize state out, log results, etc...
+
+ :param adapter: Adapter to add
+ :return: The application builder for future chaining.
+ """
+ self.lifecycle_adapters.extend(adapters)
+ return self
+
+ def build(self) -> Application:
+ _validate_actions(self.actions)
+ actions_by_name = {action.name: action for action in self.actions}
+ all_actions = set(actions_by_name.keys())
+ _validate_transitions(self.transitions, all_actions)
+ _validate_start(self.start, all_actions)
+ return Application(
+ actions=self.actions,
+ transitions=[
+ Transition(
+ from_=actions_by_name[from_],
+ to=actions_by_name[to],
+ condition=condition,
+ )
+ for from_, to, condition in self.transitions
+ ],
+ state=self.state,
+ initial_step=self.start,
+ adapter_set=LifecycleAdapterSet(*self.lifecycle_adapters),
+ )
diff --git a/burr/core/implementations.py b/burr/core/implementations.py
new file mode 100644
index 00000000..62c49993
--- /dev/null
+++ b/burr/core/implementations.py
@@ -0,0 +1,34 @@
+from burr.core import State
+from burr.core.action import Action
+
+
+class Placeholder(Action):
+ """This is a placeholder action -- you would expect it to break if you tried to run it. It is specifically
+ for the following workflow:
+ 1. Create your state machine out of placeholders to model it
+ 2. Visualize the state machine
+ 2. Replace the placeholders with real actions as you see fit
+ """
+
+ def __init__(self, reads: list[str], writes: list[str]):
+ super().__init__()
+ self._reads = reads
+ self._writes = writes
+
+ def run(self, state: State) -> dict:
+ raise NotImplementedError(
+ f"This is a placeholder action and thus you are unable to run. Please implement: {self}!"
+ )
+
+ def update(self, result: dict, state: State) -> State:
+ raise NotImplementedError(
+ f"This is a placeholder action and thus cannot update state. Please implement: {self}!"
+ )
+
+ @property
+ def reads(self) -> list[str]:
+ return self._reads
+
+ @property
+ def writes(self) -> list[str]:
+ return self._writes
diff --git a/burr/core/state.py b/burr/core/state.py
new file mode 100644
index 00000000..a311887b
--- /dev/null
+++ b/burr/core/state.py
@@ -0,0 +1,198 @@
+import abc
+import copy
+import dataclasses
+import logging
+from typing import Any, Dict, Iterator, Mapping
+
+logger = logging.getLogger(__name__)
+
+
+class StateDelta(abc.ABC):
+ """Represents a delta operation for state. This represents a transaction.
+ Note it has the ability to mutate state in-place, but will be layered behind an immutable
+ state object."""
+
+ @classmethod
+ @abc.abstractmethod
+ def name(cls) -> str:
+ """Unique name of this operation for ser/deser"""
+ pass
+
+ def serialize(self) -> dict:
+ """Converts the state delta to a JSON object"""
+ if not dataclasses.is_dataclass(self):
+ raise TypeError("serialize method is only supported for dataclass instances")
+ return dataclasses.asdict(self)
+
+ def base_serialize(self) -> dict:
+ """Converts the state delta to a JSON object"""
+ return {"name": self.name(), "operation": self.serialize()}
+
+ @classmethod
+ def deserialize(cls, json_dict: dict) -> "StateDelta":
+ """Converts a JSON object to a state delta"""
+ if not dataclasses.is_dataclass(cls):
+ raise TypeError("deserialize method is only supported for dataclass types")
+ return cls(**json_dict) # Assumes all fields in the dataclass match keys in json_dict
+
+ def base_deserialize(self, json_dict: dict) -> "StateDelta":
+ """Converts a JSON object to a state delta"""
+ return self.deserialize(json_dict)
+
+ @abc.abstractmethod
+ def reads(self) -> list[str]:
+ """Returns the keys that this state delta reads"""
+ pass
+
+ @abc.abstractmethod
+ def writes(self) -> list[str]:
+ """Returns the keys that this state delta writes"""
+ pass
+
+ @abc.abstractmethod
+ def apply_mutate(self, inputs: dict):
+ """Applies the state delta to the inputs"""
+ pass
+
+
+class SetFields(StateDelta):
+ """State delta that sets fields in the state"""
+
+ values: Mapping[str, Any]
+
+ @classmethod
+ def name(cls) -> str:
+ return "set"
+
+ def reads(self) -> list[str]:
+ return list(self.values.keys())
+
+ def writes(self) -> list[str]:
+ return list(self.values.keys())
+
+ def apply_mutate(self, inputs: dict):
+ inputs.update(self.values)
+
+
+class AppendFields(StateDelta):
+ """State delta that appends to fields in the state"""
+
+ values: Mapping[str, Any]
+
+ @classmethod
+ def name(cls) -> str:
+ return "append"
+
+ def reads(self) -> list[str]:
+ return list(self.values.keys())
+
+ def writes(self) -> list[str]:
+ return list(self.values.keys())
+
+ def apply_mutate(self, inputs: dict):
+ for key, value in self.values.items():
+ if key not in inputs:
+ inputs[key] = []
+ if not isinstance(inputs[key], list):
+ raise ValueError(f"Cannot append to non-list value {key}={inputs[self.key]}")
+ inputs[key].append(value)
+
+
+class DeleteField(StateDelta):
+ """State delta that deletes fields from the state"""
+
+ keys: list[str]
+
+ @classmethod
+ def name(cls) -> str:
+ return "delete"
+
+ def reads(self) -> list[str]:
+ return list(self.keys)
+
+ def writes(self) -> list[str]:
+ return []
+
+ def apply_mutate(self, inputs: dict):
+ for key in self.keys:
+ inputs.pop(key, None)
+
+
+class State(Mapping):
+ """An immutable state object. Things to consider:
+ 1. Adding hooks on change
+ 2. Pulling/pushing to external places
+ 3. Simultaneous writes/reads in the case of parallelism
+ 4. Schema enforcement -- how to specify/manage? Should this be a
+ dataclass when implemented?
+ """
+
+ def __init__(self, initial_values: Dict[str, Any] = None):
+ if initial_values is None:
+ initial_values = dict()
+ self._state = initial_values
+
+ def apply_operation(self, operation: StateDelta) -> "State":
+ """Applies a given operation to the state, returning a new state"""
+ new_state = copy.deepcopy(self._state) # TODO -- restrict to just the read keys
+ operation.apply_mutate(
+ new_state
+ ) # todo -- validate that the write keys are the only different ones
+ return State(new_state)
+
+ def get_all(self) -> Dict[str, Any]:
+ """Returns the entire state, realize as a dictionary. This is a copy."""
+ return dict(self)
+
+ def update(self, **updates: Any) -> "State":
+ """Updates the state with a set of key-value pairs"""
+ return self.apply_operation(SetFields(updates))
+
+ def append(self, **updates: Any) -> "State":
+ """For each pair specified, appends to a list in state."""
+
+ return self.apply_operation(AppendFields(updates))
+
+ def wipe(self, delete: list[str] = None, keep: list[str] = None):
+ """Wipes the state, either by deleting the keys in delete and keeping everything else
+ or keeping the keys in keep. and deleting everything else. If you pass nothing in
+ it will delete the whole thing.
+
+ :param delete:
+ :param keep:
+ :return:
+ """
+ if delete is not None and keep is not None:
+ raise ValueError(
+ f"You cannot specify both delete and keep -- not both! "
+ f"You have specified: delete={delete}, keep={keep}"
+ )
+ if delete is not None:
+ fields_to_delete = delete
+ else:
+ fields_to_delete = [key for key in self._state if key not in keep]
+ return self.apply_operation(DeleteField(fields_to_delete))
+
+ def merge(self, other: "State") -> "State":
+ """Merges two states together, overwriting the values in self
+ with those in other."""
+ return State({**self.get_all(), **other.get_all()})
+
+ def subset(self, *keys: str, ignore_missing: bool = True) -> "State":
+ """Returns a subset of the state, with only the given keys"""
+ return State({key: self[key] for key in keys if key in self or not ignore_missing})
+
+ def __getitem__(self, __k: str) -> Any:
+ return self._state[__k]
+
+ def __len__(self) -> int:
+ return len(self._state)
+
+ def __iter__(self) -> Iterator[Any]:
+ return iter(self._state)
+
+ def __repr__(self):
+ return self.get_all().__repr__() # quick hack
diff --git a/burr/integrations/__init__.py b/burr/integrations/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/burr/integrations/base.py b/burr/integrations/base.py
new file mode 100644
index 00000000..c79f18e1
--- /dev/null
+++ b/burr/integrations/base.py
@@ -0,0 +1,6 @@
+def require_plugin(import_error: ImportError, libraries: list[str], plugin_name: str):
+ raise ImportError(
+ f"Missing plugin {plugin_name}! To use the {plugin_name} plugin, you must install the following libraries: {libraries}."
+ f"You can install this with burr[{plugin_name}] or pip install {' '.join(libraries)} (replace with your "
+ f"package manager of choice)."
+ ) from import_error
diff --git a/burr/integrations/hamilton.py b/burr/integrations/hamilton.py
new file mode 100644
index 00000000..78c9527b
--- /dev/null
+++ b/burr/integrations/hamilton.py
@@ -0,0 +1,221 @@
+import dataclasses
+from typing import Any, Dict, Literal, Tuple, Union
+
+from burr.core import Action, State
+from hamilton.driver import Driver
+
+
+class StateSource:
+ state_key: str
+ missing: Literal["drop", "error"] = "error"
+ # default: Any = None
+
+
+MissingAction = Literal["drop", "error"]
+
+
+class LiteralSource:
+ value: Any
+
+
+Input = Union[StateSource, LiteralSource]
+
+
+def from_state(
+ key: str,
+ missing: MissingAction = "error",
+) -> StateSource:
+ """Indicates that an input should come from state.
+ Specify "missing" to allow for missing keys to be dropped or raise an error.
+
+ :param key: Key in state to use
+ :param missing: What to do if the key is missing
+ :return: A StateSource object -- use by Hamilton(inputs=...)
+ """
+ return StateSource(key, missing)
+
+
+def from_value(value: Any) -> LiteralSource:
+ """Indicates that an input should come from a literal (variable/constant) value.
+ Use this if you just want to fix a parameter into the Hamilton DAG.
+
+ :param value: Value to use
+ :return: A LiteralSource object -- use by Hamilton(inputs=...)
+ """
+ return LiteralSource(value)
+
+
+class Output:
+ key: str
+ mode: Literal["update", "append"] = "update"
+
+
+def update_state(key: str) -> Output:
+ """At the update step of a Hamilton Action, call state.update to the key field of state.
+ Used with outputs= parameter of Hamilton(...)
+
+ :param key: Field in state to udpate
+ :return: An Output object
+ """
+ return Output(key, "update")
+
+
+def append_state(key: str):
+ """At the update state of a Hamilton Action, call state.append to the key field of state.
+ Used with outputs= parameter of Hamilton(...)
+
+ :param key: Field in state to append to
+ :return: An Output object
+ """
+ return Output(key, "append")
+
+
+DEFAULT_DRIVER = None
+
+
+class Hamilton(Action):
+ @staticmethod
+ def set_driver(driver: Driver):
+ """Default method if all the hamilton nodes are using the same driver.
+ Will set globally, so be careful.
+
+ Note that the driver must have the default adapter (so that it returns a dict).
+
+ :param driver: Driver to use
+ """
+ global DEFAULT_DRIVER
+ DEFAULT_DRIVER = driver
+
+ def __init__(
+ self,
+ inputs: Dict[str, Input],
+ outputs: Dict[str, Output],
+ driver: Driver = None,
+ ):
+ """Creates a Hamilton action. Allows youy to specify:
+ 1. How to wire state fields into hamilton inputs
+ 2 How to wire hamilton outputs into state fields
+
+ Note that we o not distinguish between overrides and inputs -- we intelligently decide
+ which are which based on the driver's available variables.
+
+ :param inputs:
+ :param outputs:
+ :param driver:
+ :param name:
+ """
+ super(Hamilton, self).__init__()
+ if driver is None and DEFAULT_DRIVER is None:
+ raise ValueError(
+ "Driver must be set before creating a Hamilton function. "
+ "You can do so with Hamilton.set_driver(...) to set it globally, "
+ "or pass in driver to the Hamilton(...) constructor."
+ )
+ self._driver = driver if driver is not None else DEFAULT_DRIVER
+ self._inputs = inputs
+ self._outputs = outputs
+
+ @property
+ def driver(self):
+ return self._driver
+
+ def _extract_inputs_overrides(self, state: State) -> Tuple[dict, dict]:
+ """Extracts the inputs and overrides from the state."""
+
+ def resolve_value(source: Input) -> Any:
+ if isinstance(source, StateSource):
+ if source.state_key in state:
+ return state[source.state_key]
+ else:
+ if source.missing == "error":
+ raise ValueError(f"Missing state key {source.state_key}")
+ else:
+ return None
+ else:
+ return source.value
+
+ inputs = {}
+ overrides = {}
+ dr_vars = {node.name: node for node in self._driver.list_available_variables()}
+ for key, source in self._inputs.items():
+ if key not in dr_vars:
+ raise ValueError(
+ f"Input {key} not available in driver -- "
+ f"available variables are: {list(self._driver.list_available_variables())}"
+ )
+ node = dr_vars[key]
+ if node.is_external_input:
+ inputs[node.name] = resolve_value(source)
+ else:
+ overrides[node.name] = resolve_value(source)
+ return inputs, overrides
+
+ def run(self, state: State) -> dict:
+ """Runs a hamilton action, using the driver to execute the hamilton DAG.
+
+ :param state: The state to use
+ :return: The results of the hamilton DAG
+ """
+ inputs, overrides = self._extract_inputs_overrides(state)
+ result = self._driver.raw_execute(
+ list(self._outputs.keys()),
+ overrides=overrides,
+ inputs=inputs,
+ )
+ return result
+
+ def update(self, result: dict, state: State) -> State:
+ """Updates the state with the results of the hamilton action, as specified in the outputs.
+
+ :param result: The results of the hamilton DAG
+ :param state: The state to update
+ """
+ update_values = {
+ self._outputs[key].key: value
+ for key, value in result.items()
+ if self._outputs[key].mode == "update"
+ }
+ append_values = {
+ self._outputs[key].key: value
+ for key, value in result.items()
+ if self._outputs[key].mode == "append"
+ }
+ return state.update(**update_values).append(**append_values)
+
+ @property
+ def reads(self) -> list[str]:
+ """The set of state items this action reads.
+ TODO:
+ 1. Parse the inputs and overrides to determine which state items are read
+ 2. Return them
+ """
+ return [
+ source.state_key for source in self._inputs.values() if isinstance(source, StateSource)
+ ]
+
+ @property
+ def writes(self) -> list[str]:
+ """The set of state items this action writes.
+ TODO:
+ 0. Determine how we want to represent writing final vars to the state
+ 1. Parse the final_vars to determine which state items are written to
+ 3. Return them
+ :return: The set of state items this action writes.
+ """
+ return [source.key for source in self._outputs.values()]
+
+ def visualize_step(self, **kwargs):
+ dr = self._driver
+ inputs = {key: ... for key in self._inputs}
+ overrides = inputs
+ final_vars = list(self._outputs.keys())
+ return dr.visualize_execution(
+ final_vars=final_vars,
+ inputs=inputs,
+ overrides=overrides,
+ bypass_validation=True,
+ **kwargs,
+ )
diff --git a/burr/integrations/streamlit.py b/burr/integrations/streamlit.py
new file mode 100644
index 00000000..e6aa4f54
--- /dev/null
+++ b/burr/integrations/streamlit.py
@@ -0,0 +1,281 @@
+import dataclasses
+import inspect
+import json
+from typing import List, Optional
+
+from burr.core import Application
+from burr.integrations.base import require_plugin
+from burr.integrations.hamilton import Hamilton, StateSource
+
+try:
+ import colorsys
+
+ import graphviz
+ import matplotlib.colors as mc
+ import streamlit as st
+except ImportError as e:
+ require_plugin(
+ e,
+ ["streamlit", "graphviz", "colorsys", "matplotlib"],
+ "streamlit",
+ )
+
+
+class Record:
+ state: dict
+ action: str
+ result: dict
+
+
+class AppState:
+ display_index: Optional[int] # index in the state/results dict
+ history: list[Record]
+ app: Application # we have to have this for registering the state machine --
+ num_prior_nodes: int = 5 # view last 5
+
+ @property
+ def current_action(self) -> Optional[str]:
+ if self.display_index is None or len(self.history) == 0:
+ return None
+ return self.history[self.display_index].action
+
+ @property
+ def prior_actions(self) -> List[str]:
+ if self.display_index is None or len(self.history) == 0:
+ return []
+ out = [
+ record.action
+ for record in self.history[
+ max(self.display_index - self.num_prior_nodes, 0) : self.display_index
+ ]
+ ]
+ return out
+
+ @property
+ def next_action(self) -> str:
+ if self.display_index < len(self.history) - 1:
+ return self.history[self.display_index + 1].action
+ return self.app.get_next_action().name # return the future one
+
+ @property
+ def max_index(self) -> int:
+ return len(self.history) - 1
+
+ @classmethod
+ def from_empty(cls, app: Application) -> "AppState":
+ return AppState(display_index=0, history=[], app=app)
+
+
+def load_state_from_log_file(jsonl_log_file: str, app: Application) -> AppState:
+ """Initializes the state from a log file. This must have been logged using StateAndResultFullLogger.
+ Note that, currently, you must pass in an Application object (although that will be optoinal in the future).
+
+ :param jsonl_log_file: Log file to load
+ :param app: Application object
+ :return: AppState
+ """
+ out = []
+ for i, line in enumerate(open(jsonl_log_file)):
+ json_line = json.loads(line)
+ record = Record(
+ state=json_line["state"],
+ action=json_line["action"],
+ result=json_line["result"]
+ # TODO -- add start time, end time
+ )
+ out.append(record)
+ return AppState(display_index=len(out) - 1, history=out, app=app)
+
+
+def update_state(new_state: AppState):
+ st.session_state.burr_state = new_state
+
+
+def get_state():
+ if "burr_state" not in st.session_state:
+ raise ValueError(
+ "No state found in streamlit session state. To initialize the state, call "
+ "initialize_state() as the first line from streamlit -- it will do nothing if the state is already initialized."
+ )
+ return st.session_state.get("burr_state")
+
+
+def _modify_state_machine_digraph(
+ digraph: graphviz.Digraph,
+ current_node: str = None,
+ prior_nodes: list = [],
+ next_node: str = None,
+):
+ def lighten_color(color, amount=0.5):
+ if amount > 1:
+ amount = 1
+ if amount < 0:
+ amount = 0
+ try:
+ c = mc.cnames[color]
+ except KeyError:
+ c = color
+ c = colorsys.rgb_to_hls(*mc.to_rgb(c))
+ lightened_color = colorsys.hls_to_rgb(c[0], 1 - amount * (1 - c[1]), c[2])
+ return mc.to_hex(lightened_color)
+
+ digraph.node(current_node, fillcolor="darkgreen", style="rounded,filled", fontcolor="white")
+ digraph.node(next_node, fillcolor="blue", style="rounded,filled", fontcolor="white")
+ seen = {current_node, next_node}
+ base_color = "lightblue"
+ for i, node in enumerate(prior_nodes):
+ if node not in seen:
+ seen.add(node)
+ lighter_color = lighten_color(base_color, amount=1 - ((i + 1) * 0.1))
+ digraph.node(node, fillcolor=lighter_color, style="rounded,filled", fontcolor="black")
+ else:
+ continue
+
+ digraph.attr(bgcolor="transparent")
+
+
+def render_state_machine(state: AppState):
+ """Visualization of the current state machine. Highlights:
+ 1. Current node in blue (with white backgorund)
+ 2. Prior nodes in progressively lighter shades of blue
+
+ Use this individually, or within the "render_explorer" view
+
+ :param state:
+ :return:
+ """
+ prior_nodes = state.prior_actions # grab the prior nodes
+ current_node = state.current_action
+ next_node = state.next_action
+ app = state.app
+ visualized = app.visualize(None, include_conditions=False, include_state=False)
+ if current_node is not None:
+ _modify_state_machine_digraph(
+ visualized, current_node=current_node, prior_nodes=prior_nodes, next_node=next_node
+ )
+ st.graphviz_chart(visualized, use_container_width=True)
+
+
+def render_action(state: AppState):
+ """Renders the current action, including the reads, writes, and the code for the action.
+ With Hamilton actions, it will also show the visualization of the action.
+
+ This can be used individually (with a state object) or within the "render_explorer" view.
+
+ :param state:
+ :return:
+ """
+ app: Application = state.app
+ current_node = state.current_action
+ actions = {action.name: action for action in app.actions}
+ if current_node is None:
+ st.markdown("No current action.")
+ return
+ st.header(f"`{current_node}`")
+ action_object = actions[current_node]
+ is_hamilton = isinstance(action_object, Hamilton)
+
+ def format_read(var):
+ out = f"- `{var}`"
+ if is_hamilton:
+ inputs = action_object._inputs # TODO -- don't use private variables
+ corresponding_input = {
+ k: v for k, v in inputs.items() if isinstance(v, StateSource) and v.state_key == var
+ }
+ if corresponding_input:
+ return f"- `state['{var}']` → `{list(corresponding_input.keys())[0]}`"
+ return out
+
+ def format_write(var):
+ out = f"- `{var}`"
+ if is_hamilton:
+ outputs = action_object._outputs
+ corresponding_output = {k: v for k, v in outputs.items() if v.key == var}
+ k, v = list(corresponding_output.items())[0]
+ if corresponding_output:
+ out = f"- `state['{var}']`"
+ if v.mode == "update":
+ out += f"← `{k}`"
+ if v.mode == "append":
+ out += f" ← `state['{var}'].append({k})`"
+ # out += " (`.append()`)"
+ return out
+
+ reads = "\n".join([format_read(var) for var in action_object.reads])
+ writes = "\n".join([format_write(var) for var in action_object.writes])
+ st.markdown(f"#### Reads: \n {reads}")
+ st.markdown(f"#### Writes: \n {writes}")
+ if is_hamilton:
+ digraph = action_object.visualize_step(show_legend=False)
+ st.graphviz_chart(digraph, use_container_width=False)
+ else:
+ code = inspect.getsource(action_object.__class__)
+ st.code(code, language="python")
+
+
+def render_state_results(state: AppState):
+ """Render the state and results for the current state. This includes the state and the result of the action.
+ This can be used individually (with a state object) or within the "render_explorer" view.
+
+ :param state: State object
+ :return: None
+ """
+ if len(state.history) == 0: # empty, have not yet started
+ return
+ current_node = state.current_action
+ st.header(f"`{current_node}`")
+ state_to_render = state.history[state.display_index].state
+ result_to_render = state.history[state.display_index].result
+ # if "chat_history" in state_to_render:
+ # del state_to_render["chat_history"]
+ st.header("State")
+ st.json(state_to_render, expanded=True)
+ st.header("Result")
+ st.json(result_to_render, expanded=True)
+
+
+def set_slider_to_current():
+ st.session_state.index_slider = get_state().max_index
+
+
+def render_explorer(app_state: AppState):
+ """Renders the entire explorer, including the state machine, the action, and the state/results.
+
+ :param app_state: State of the app
+ :return: None
+ """
+ total_state_length = len(app_state.history)
+ placeholder = st.empty()
+ placeholder.markdown("` `")
+ if total_state_length > 1:
+ slider_values = list(range(total_state_length))
+ slider_strings = [record.action for record in app_state.history]
+
+ def stringify(i):
+ return slider_strings[i]
+
+ slider = st.select_slider(
+ "index",
+ options=slider_values,
+ label_visibility="hidden",
+ format_func=stringify,
+ key="index_slider",
+ )
+ current_node_index = slider
+ # TODO -- consider a callback here instead
+ app_state.display_index = current_node_index
+
+ with placeholder.container(height=800):
+ state_machine_view, step_view, data_view = st.tabs(
+ ["Application", "Action", "State/Results"]
+ )
+ with st.container():
+ with state_machine_view:
+ render_state_machine(app_state)
+ with step_view:
+ render_action(app_state)
+ with data_view:
+ render_state_results(app_state)
+ update_state(app_state)
diff --git a/burr/lifecycle/__init__.py b/burr/lifecycle/__init__.py
new file mode 100644
index 00000000..25e31ead
--- /dev/null
+++ b/burr/lifecycle/__init__.py
@@ -0,0 +1,25 @@
+from burr.lifecycle.base import (
+ LifecycleAdapter,
+ PostRunApplicationHook,
+ PostRunApplicationHookAsync,
+ PostRunStepHook,
+ PostRunStepHookAsync,
+ PreRunApplicationHook,
+ PreRunApplicationHookAsync,
+ PreRunStepHook,
+ PreRunStepHookAsync,
+)
+from burr.lifecycle.default import StateAndResultsFullLogger
+
+__all__ = [
+ "PreRunStepHook",
+ "PreRunStepHookAsync",
+ "PostRunStepHook",
+ "PostRunStepHookAsync",
+ "PreRunApplicationHook",
+ "PreRunApplicationHookAsync",
+ "PostRunApplicationHook",
+ "PostRunApplicationHookAsync",
+ "LifecycleAdapter",
+ "StateAndResultsFullLogger",
+]
diff --git a/burr/lifecycle/base.py b/burr/lifecycle/base.py
new file mode 100644
index 00000000..a392b5c6
--- /dev/null
+++ b/burr/lifecycle/base.py
@@ -0,0 +1,100 @@
+import abc
+from typing import TYPE_CHECKING, Any, Optional, Union
+
+if TYPE_CHECKING:
+ # type-checking-only for a circular import
+ from burr.core import State, Action
+
+from burr.lifecycle.internal import lifecycle
+
+
[email protected]_hook("pre_run_step")
+class PreRunStepHook(abc.ABC):
+ @abc.abstractmethod
+ def pre_run_step(self, *, state: "State", action: "Action", **future_kwargs: Any):
+ pass
+
+
[email protected]_hook("pre_run_step")
+class PreRunStepHookAsync(abc.ABC):
+ @abc.abstractmethod
+ async def pre_run_step(self, *, state: "State", action: "Action", **future_kwargs: Any):
+ pass
+
+
[email protected]_hook("post_run_step")
+class PostRunStepHook(abc.ABC):
+ @abc.abstractmethod
+ def post_run_step(
+ self,
+ *,
+ state: "State",
+ action: "Action",
+ result: Optional[dict],
+ exception: Exception,
+ **future_kwargs: Any,
+ ):
+ pass
+
+
[email protected]_hook("post_run_step")
+class PostRunStepHookAsync(abc.ABC):
+ @abc.abstractmethod
+ async def post_run_step(
+ self,
+ *,
+ state: "State",
+ action: "Action",
+ result: Optional[dict],
+ exception: Exception,
+ **future_kwargs: Any,
+ ):
+ pass
+
+
+# THESE ARE NOT IN USE
+# TODO -- implement/decide how to use them
[email protected]_hook("pre_run_application")
+class PreRunApplicationHook(abc.ABC):
+ @abc.abstractmethod
+ def pre_run_application(self, *, state: "State", **future_kwargs: Any):
+ pass
+
+
[email protected]_hook("pre_run_application")
+class PreRunApplicationHookAsync(abc.ABC):
+ @abc.abstractmethod
+ async def pre_run_application(self, *, state: "State", **future_kwargs):
+ pass
+
+
[email protected]_hook("post_run_application")
+class PostRunApplicationHook(abc.ABC):
+ @abc.abstractmethod
+ def post_run_application(
+ self, *, state: "State", until: list[str], results: list[dict], **future_kwargs
+ ):
+ pass
+
+
[email protected]_hook("post_run_application")
+class PostRunApplicationHookAsync(abc.ABC):
+ @abc.abstractmethod
+ async def post_run_application(
+ self, *, state: "State", until: list[str], results: list[dict], **future_kwargs
+ ):
+ pass
+
+
+# strictly for typing -- this conflicts a bit with the lifecycle decorator above, but its fine for now
+# This makes IDE completion/type-hinting easier
+LifecycleAdapter = Union[
+ PreRunStepHook,
+ PreRunStepHookAsync,
+ PostRunStepHook,
+ PostRunStepHookAsync,
+ PreRunApplicationHook,
+ PreRunApplicationHookAsync,
+ PostRunApplicationHook,
+ PostRunApplicationHookAsync,
+]
diff --git a/burr/lifecycle/default.py b/burr/lifecycle/default.py
new file mode 100644
index 00000000..e748bd72
--- /dev/null
+++ b/burr/lifecycle/default.py
@@ -0,0 +1,77 @@
+import datetime
+import json
+import time
+from typing import TYPE_CHECKING, Any, Callable, Literal, Optional
+
+if TYPE_CHECKING:
+ from burr.core import State, Action
+
+from burr.lifecycle.base import PostRunStepHook, PreRunStepHook
+
+
+def safe_json(obj: Any) -> str:
+ return json.dumps(obj, default=str)
+
+
+class StateAndResultsFullLogger(PostRunStepHook, PreRunStepHook):
+ DONT_INCLUDE = object() # sentinel value
+
+ def __init__(
+ self,
+ jsonl_path: str,
+ mode: Literal["append", "w"] = "append",
+ json_dump: Callable[[dict], str] = safe_json,
+ ):
+ if not jsonl_path.endswith(".jsonl"):
+ raise ValueError(f"jsonl_path must end with .jsonl. Got: {jsonl_path}")
+ self.jsonl_path = jsonl_path
+ open_mode = "a" if mode == "append" else "w"
+ self.f = open(jsonl_path, mode=open_mode) # open in append mode
+ self.tracker = [] # tracker to keep track of timing/whatnot
+
+ def pre_run_step(self, **future_kwargs: Any):
+ self.tracker.append({"time": datetime.datetime.now()})
+
+ def post_run_step(
+ self,
+ *,
+ state: "State",
+ action: "Action",
+ result: Optional[dict],
+ exception: Exception,
+ **future_kwargs: Any,
+ ):
+ state_and_result = {
+ "state": state.get_all(),
+ "action": action.name,
+ "result": result,
+ "exception": str(exception),
+ "start_time": self.tracker[-1]["time"].isoformat(),
+ "end_time": datetime.datetime.now().isoformat(),
+ }
+ self.f.writelines([safe_json(state_and_result) + "\n"])
+
+ def __del__(self):
+ if hasattr(self, "f"):
+ # possible something fails beforehand
+ self.f.close()
+
+
+class SlowDownHook(PostRunStepHook, PreRunStepHook):
+ def __init__(self, pre_sleep_time: float = 0.5, post_sleep_time: float = 0.5):
+ self.post_sleep_time = post_sleep_time
+ self.pre_sleep_time = pre_sleep_time
+
+ def post_run_step(
+ self,
+ *,
+ state: "State",
+ action: "Action",
+ result: Optional[dict],
+ exception: Exception,
+ **future_kwargs: Any,
+ ):
+ time.sleep(self.post_sleep_time)
+
+ def pre_run_step(self, *, state: "State", action: "Action", **future_kwargs: Any):
+ time.sleep(self.pre_sleep_time)
diff --git a/burr/lifecycle/internal.py b/burr/lifecycle/internal.py
new file mode 100644
index 00000000..f70bc5b9
--- /dev/null
+++ b/burr/lifecycle/internal.py
@@ -0,0 +1,187 @@
+"""Base tooling, internal-facing, for lifecycle hooks. This is stolen from the
+hamilton implementation, but significantly simplified."""
+import asyncio
+import collections
+import inspect
+from typing import TYPE_CHECKING, Callable, Dict, List, Set, Tuple
+
+if TYPE_CHECKING:
+ # type-checking-only for a circular import
+ from burr.lifecycle.base import LifecycleAdapter
+
+SYNC_HOOK = "hooks"
+ASYNC_HOOK = "async_hooks"
+
+REGISTERED_SYNC_HOOKS: Set[str] = set()
+REGISTERED_ASYNC_HOOKS: Set[str] = set()
+
+
+class InvalidLifecycleHook(Exception):
+ """Container exception to indicate that a lifecycle adapter is invalid."""
+
+ pass
+
+
+def validate_hook_fn(fn: Callable):
+ """Validates that a function forms a valid hook. This means:
+ 1. Function returns nothing
+ 2. Function must consist of only kwarg-only arguments
+
+ :param fn: The function to validate
+ :raises InvalidLifecycleAdapter: If the function is not a valid hook
+ """
+ sig = inspect.signature(fn)
+ if (
+ "future_kwargs" not in sig.parameters
+ or sig.parameters["future_kwargs"].kind != inspect.Parameter.VAR_KEYWORD
+ ):
+ raise InvalidLifecycleHook(
+ f"Lifecycle hooks must have a `**future_kwargs` argument. Method/hook {fn} does not."
+ )
+ for param in sig.parameters.values():
+ if param.name != "future_kwargs":
+ if param.kind != inspect.Parameter.KEYWORD_ONLY and param.name != "self":
+ raise InvalidLifecycleHook(
+ f"Lifecycle hooks can only have keyword-only arguments. "
+ f"Method/hook {fn} has argument {param} that is not keyword-only."
+ )
+
+
+class lifecycle:
+ """Container class for decorators to register hooks.
+ This is just a container so it looks clean (`@lifecycle.base_hook(...)`), but we could easily move it out.
+ What do these decorators do?
+ 1. We decorate a class with a method/hook/validator call
+ 2. This implies that there exists a function by that name
+ 3. We validate that that function has an appropriate signature
+ 4. We store this in the appropriate registry (see the constants above)
+ Then, when we want to perform a hook/method/validator, we can ask the AdapterLifecycleSet to do so.
+ It crawls up the MRO, looking to see which classes are in the registry, then elects which functions to run.
+ See LifecycleAdapterSet for more information.
+ """
+
+ @classmethod
+ def base_hook(cls, fn_name: str):
+ """Hooks get called at distinct stages of Hamilton's execution.
+ These can be layered together, and potentially coupled to other hooks.
+
+ :param fn_name: Name of the function that will reside in the class we're decorating
+ """
+
+ def decorator(clazz):
+ fn = getattr(clazz, fn_name, None)
+ if fn is None:
+ raise ValueError(
+ f"Class {clazz} does not have a method {fn_name}, but is "
+ f'decorated with @lifecycle.base_hook("{fn_name}"). The parameter '
+ f"to @lifecycle.base_hook must be the name "
+ f"of a method on the class."
+ )
+ validate_hook_fn(fn)
+ if inspect.iscoroutinefunction(fn):
+ setattr(clazz, ASYNC_HOOK, fn_name)
+ REGISTERED_ASYNC_HOOKS.add(fn_name)
+ else:
+ setattr(clazz, SYNC_HOOK, fn_name)
+ REGISTERED_SYNC_HOOKS.add(fn_name)
+ return clazz
+
+ return decorator
+
+
+class LifecycleAdapterSet:
+ """An internal class that groups together all the lifecycle adapters.
+ This allows us to call methods through a delegation pattern, enabling us to add
+ whatever callbacks, logging, error-handling, etc... we need globally. While this
+ does increase the stack trace in an error, it should be pretty easy to figure out what's going on.
+ """
+
+ def __init__(self, *adapters: "LifecycleAdapter"):
+ """Initializes the adapter set.
+
+ :param adapters: Adapters to group together
+ """
+ self._adapters = list(adapters)
+ self.sync_hooks, self.async_hooks = self._get_lifecycle_hooks()
+
+ def _get_lifecycle_hooks(
+ self,
+ ) -> Tuple[Dict[str, List["LifecycleAdapter"]], Dict[str, List["LifecycleAdapter"]]]:
+ sync_hooks = collections.defaultdict(list)
+ async_hooks = collections.defaultdict(list)
+ for adapter in self.adapters:
+ for cls in inspect.getmro(adapter.__class__):
+ sync_hook = getattr(cls, SYNC_HOOK, None)
+ if sync_hook is not None:
+ if adapter not in sync_hooks[sync_hook]:
+ sync_hooks[sync_hook].append(adapter)
+ async_hook = getattr(cls, ASYNC_HOOK, None)
+ if async_hook is not None:
+ if adapter not in async_hooks[async_hook]:
+ async_hooks[async_hook].append(adapter)
+ return (
+ {hook: adapters for hook, adapters in sync_hooks.items()},
+ {hook: adapters for hook, adapters in async_hooks.items()},
+ )
+
+ def _does_hook(self, hook_name: str, is_async: bool) -> bool:
+ """Whether or not a hook is implemented by any of the adapters in this group.
+ If this hook is not registered, this will raise a ValueError.
+
+ :param hook_name: Name of the hook
+ :param is_async: Whether you want the async version or not
+ :return: True if this adapter set does this hook, False otherwise
+ """
+ if is_async and hook_name not in REGISTERED_ASYNC_HOOKS:
+ raise ValueError(
+ f"Hook {hook_name} is not registered as an asynchronous lifecycle hook. "
+ f"Registered hooks are {REGISTERED_ASYNC_HOOKS}"
+ )
+ if not is_async and hook_name not in REGISTERED_SYNC_HOOKS:
+ raise ValueError(
+ f"Hook {hook_name} is not registered as a synchronous lifecycle hook. "
+ f"Registered hooks are {REGISTERED_SYNC_HOOKS}"
+ )
+ if not is_async:
+ return hook_name in self.sync_hooks
+ return hook_name in self.async_hooks
+
+ def call_all_lifecycle_hooks_sync(self, hook_name: str, **kwargs):
+ """Calls all the lifecycle hooks in this group, by hook name (stage)
+
+ :param hook_name: Name of the hooks to call
+ :param kwargs: Keyword arguments to pass into the hook
+ """
+ if not self._does_hook(hook_name, False):
+ return
+ for adapter in self.sync_hooks[hook_name]:
+ getattr(adapter, hook_name)(**kwargs)
+
+ async def call_all_lifecycle_hooks_async(self, hook_name: str, **kwargs):
+ """Calls all the lifecycle hooks in this group, by hook name (stage).
+
+ :param hook_name: Name of the hook
+ :param kwargs: Keyword arguments to pass into the hook
+ """
+ if not self._does_hook(hook_name, True):
+ return
+ futures = []
+ for adapter in self.async_hooks[hook_name]:
+ futures.append(getattr(adapter, hook_name)(**kwargs))
+ await asyncio.gather(*futures)
+
+ async def call_all_lifecycle_hooks_sync_and_async(self, hook_name: str, **kwargs):
+ """Calls all the lifecycle hooks in this group, by hook name (stage).
+
+ :param hook_name: Name of the hook
+ """
+ self.call_all_lifecycle_hooks_sync(hook_name, **kwargs)
+ await self.call_all_lifecycle_hooks_async(hook_name, **kwargs)
+
+ @property
+ def adapters(self) -> List["LifecycleAdapter"]:
+ """Gives the adapters in this group
+
+ :return: A list of adapters
+ """
+ return self._adapters
diff --git a/burr/version.py b/burr/version.py
new file mode 100644
index 00000000..21209874
--- /dev/null
+++ b/burr/version.py
@@ -0,0 +1,3 @@
+import importlib.metadata
+
+__version__ = importlib.metadata.version("burr")