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
Enables passing inputs through to multiple actions
Stefan Krawczyk742b596a6f8e
diff --git a/burr/core/application.py b/burr/core/application.pyindex 9731a20c..1d107811 100644--- a/burr/core/application.py+++ b/burr/core/application.py@@ -335,13 +335,13 @@ class Application:return Noneif inputs is None:inputs = {}- inputs = self._process_inputs(inputs, next_action)+ action_inputs = self._process_inputs(inputs, next_action)if _run_hooks:self._adapter_set.call_all_lifecycle_hooks_sync("pre_run_step",action=next_action,state=self._state,- inputs=inputs,+ inputs=action_inputs,sequence_id=self.sequence_id,app_id=self._uid,partition_key=self._partition_key,@@ -351,9 +351,11 @@ class Application:new_state = self._statetry:if next_action.single_step:- result, new_state = _run_single_step_action(next_action, self._state, inputs)+ result, new_state = _run_single_step_action(next_action, self._state, action_inputs)else:- result = _run_function(next_action, self._state, inputs, name=next_action.name)+ result = _run_function(+ next_action, self._state, action_inputs, name=next_action.name+ )new_state = _run_reducer(next_action, self._state, result, next_action.name)new_state = self._update_internal_state_value(new_state, next_action)@@ -395,11 +397,12 @@ class Application:for key in list(inputs.keys()):if key in action.inputs:processed_inputs[key] = inputs.pop(key)- if len(inputs) > 0:- raise ValueError(+ if len(inputs) > 0 and logger.isEnabledFor(logging.DEBUG):+ logger.debug(f"Keys {inputs.keys()} were passed in as inputs to action "- f"{action.name}, but not declared by the action as an input! "- f"Action needs: {action.inputs}"+ f"{action.name}, but not declared by the action as an input. "+ f"Action only needs: {action.inputs} so we're just letting you know "+ f"some inputs are being skipped.")missing_inputs = set(action.inputs) - set(processed_inputs.keys())for required_input in list(missing_inputs):@@ -444,12 +447,12 @@ class Application:return Noneif inputs is None:inputs = {}- inputs = self._process_inputs(inputs, next_action)+ action_inputs = self._process_inputs(inputs, next_action)await self._adapter_set.call_all_lifecycle_hooks_sync_and_async("pre_run_step",action=next_action,state=self._state,- inputs=inputs,+ inputs=action_inputs,sequence_id=self.sequence_id,app_id=self._uid,partition_key=self._partition_key,@@ -465,15 +468,15 @@ class Application:# which this is supposed to be its OK).# this delegates hooks to the synchronous version, so we'll call all of them as wellreturn self._step(- inputs=inputs, _run_hooks=False+ inputs=action_inputs, _run_hooks=False) # Skip hooks as we already ran all of them/will run all of them in this function's finallyif next_action.single_step:result, new_state = await _arun_single_step_action(- next_action, self._state, inputs=inputs+ next_action, self._state, inputs=action_inputs)else:result = await _arun_function(- next_action, self._state, inputs=inputs, name=next_action.name+ next_action, self._state, inputs=action_inputs, name=next_action.name)new_state = _run_reducer(next_action, self._state, result, next_action.name)new_state = self._update_internal_state_value(new_state, next_action)@@ -600,7 +603,6 @@ class Application:while self.has_next_action():# self.step will only return None if there is no next action, so we can rely on tuple unpackingprior_action, result, state = self.step(inputs=inputs)- inputs = {} # only pass inputs in the first timeyield prior_action, result, stateif self._should_halt_iterate(halt_before, halt_after, prior_action):break@@ -631,7 +633,6 @@ class Application:while self.has_next_action():# self.step will only return None if there is no next action, so we can rely on tuple unpackingprior_action, result, state = await self.astep(inputs=inputs)- inputs = {} # only pass inputs in the first timeyield prior_action, result, stateif self._should_halt_iterate(halt_before, halt_after, prior_action):breakdiff --git a/docs/concepts/actions.rst b/docs/concepts/actions.rstindex 3f1e9a2d..51c2fd49 100644--- a/docs/concepts/actions.rst+++ b/docs/concepts/actions.rst@@ -18,21 +18,62 @@ The ``run`` method should return a dictionary of the result and the ``update`` mthe updated state. They declare their dependencies so the framework knows *which* state variables they read and write. This allows theframework to optimize the execution of the workflow. We call (1) a ``Function`` and (2) a ``Reducer`` (similar to `Redux <https://redux.js.org/>`_, if you're familiar with frontend UI technology).-.. _inputref:+There are two APIs for defining actions: class-based and function-based. They are largely equivalent, but differ in use.----------------Runtime Inputs---------------+- use the function-based API when you want to write something quick and terse that reads from a fixed set of state variables+- use the class-based API when you want to leverage inheritance or parameterize the action in more powerful ways-Actions can declare inputs that are not part of the state. This is for the case that you want to pause workflow execution for human input.+----------------------+Function-based actions+-----------------------For instance, say you have a chatbot. The first step will declare the ``input`` parameter ``prompt`` -- it will take that, process it, and put-it in the state. The subsequent steps will read the result of that from state.+You can also define actions by decorating a function with the :py:func:`@action <burr.core.action.action>` decorator:-There are two APIs for defining actions: class-based and function-based. They are largely equivalent, but differ in use.+.. code-block:: python++ from burr.core import action, State++ @action(reads=["var_from_state"], writes=["var_to_update"])+ def custom_action(state: State) -> Tuple[dict, State]:+ result = {"var_to_update": state["var_from_state"] + 1}+ return result, state.update(**result)++ app = ApplicationBuilder().with_actions(+ custom_action=custom_action+ )...++Function-based actions can take in parameters which are akin to passing in constructor parameters. This is done through the :py:meth:`bind <burr.core.action.bind>` method:++.. code-block:: python++ @action(reads=["var_from_state"], writes=["var_to_update"])+ def custom_action(state: State, increment_by: int) -> Tuple[dict, State]:+ result = {"var_to_update": state["var_from_state"] + increment_by}+ return result, state.update(**result)++ app = ApplicationBuilder().with_actions(+ custom_action=custom_action.bind(increment_by=2)+ )...++This is the same as ``functools.partial``, but it is more explicit and easier to read. If an action has parameters that are not+bound, they will be referred to as inputs. For example:+++.. code-block:: python++ @action(reads=["var_from_state"], writes=["var_to_update"])+ def custom_action(state: State, increment_by: int) -> Tuple[dict, State]:+ result = {"var_to_update": state["var_from_state"] + increment_by}+ return result, state.update(**result)++ app = ApplicationBuilder().with_actions(+ custom_action=custom_action+ )...++Will require the inputs to be passed in at runtime. See below for how to do that.++Note that these combine the ``update`` and ``run`` methods into a single function, and they're both executed at the same time.-- use the function-based API when you want to write something quick and terse that reads from a fixed set of state variables-- use the class-based API when you want to leverage inheritance or parameterize the action in more powerful ways-------------------Class-Based Actions@@ -96,87 +137,82 @@ Note that if the action has inputs, you have to define the optional ``inputs`` preturn ["increment_by"]------------------------Function-based actions-----------------------+See below for how to pass in inputs at runtime.-You can also define actions by decorating a function with the :py:func:`@action <burr.core.action.action>` decorator:+-----------------------+``Inputs`` only actions+------------------------.. code-block:: python-- from burr.core import action, State-- @action(reads=["var_from_state"], writes=["var_to_update"])- def custom_action(state: State) -> Tuple[dict, State]:- result = {"var_to_update": state["var_from_state"] + 1}- return result, state.update(**result)-- app = ApplicationBuilder().with_actions(- custom_action=custom_action- )...--Function-based actions can take in parameters which are akin to passing in constructor parameters. This is done through the :py:meth:`bind <burr.core.action.bind>` method:+If you simply want a node to take in inputs and pass them to the state, you can use the `Input` action:.. code-block:: python- @action(reads=["var_from_state"], writes=["var_to_update"])- def custom_action(state: State, increment_by: int) -> Tuple[dict, State]:- result = {"var_to_update": state["var_from_state"] + increment_by}- return result, state.update(**result)-app = ApplicationBuilder().with_actions(- custom_action=custom_action.bind(increment_by=2)+ get_input=Input("var_from_state"))...-This is the same as ``functools.partial``, but it is more explicit and easier to read. If an action has parameters that are not-bound, they will be referred to as inputs. For example:+This will look for the `var_from_state` in the inputs and pass it to the state. Note this is just syntactic sugar+for declaring inputs through one of the other APIs and adding it to state -- if you want to do anything more complex+with the input, you should use other APIs.+------------------------+``Results`` only actions+-------------------------.. code-block:: python+If you just want to fill a result from the state, you can use the `Result` action:- @action(reads=["var_from_state"], writes=["var_to_update"])- def custom_action(state: State, increment_by: int) -> Tuple[dict, State]:- result = {"var_to_update": state["var_from_state"] + increment_by}- return result, state.update(**result)+.. code-block:: pythonapp = ApplicationBuilder().with_actions(- custom_action=custom_action+ get_result=Result("var_from_state"))...-Will require the inputs to be passed in at runtime.-Note that these combine the ``update`` and ``run`` methods into a single function, and they're both executed at the same time.+This simply grabs the value from the state and returns it as the result. It is purely a placeholder+for an action that should just use the result, although you do not need it.-------------``Inputs``------------+Refer to :ref:`actions <actions>` for documentation.-If you simply want a node to take in inputs and pass them to the state, you can use the `Input` action:-.. code-block:: python+.. _inputref:- app = ApplicationBuilder().with_actions(- get_input=Input("var_from_state")- )...+--------------+Runtime Inputs+---------------This will look for the `var_from_state` in the inputs and pass it to the state. Note this is just syntactic sugar-for declaring inputs through one of the other APIs and adding it to state -- if you want to do anything more complex-with the input, you should use other APIs.+Actions can declare parameters that are not part of the state. Use this to:-------------``Results``------------+1. Provide variables that can be bound to an action. E.g. API clients, DB clients, etc.+2. Provide inputs that are required as part of the application to function, e.g. human input, configuration, etc.-If you just want to fill a result from the state, you can use the `Result` action:+For example using the function based API, consider the following action:+.. code-block:: python+ @action(reads=["..."], writes=["..."])+ def my_action(state: State, client: Client, prompt: str) -> Tuple[dict, State]:+ """`client` & `prompt` here are something we need to pass in."""+ context = client.get_data(state["..."])+ result = llm_call(prompt, context) # some LLM call...+ return result, state.update(**result)++We need to pass in `client` and `prompt` somehow. Here are the ways to do that:.. code-block:: python- app = ApplicationBuilder().with_actions(- get_result=Result("var_from_state")- )...+ # (1) bind values+ app = (+ ApplicationBuilder()+ # we can "bind" values to an action+ .with_actions(my_action=my_action.bind(client=client))+ ...+ .build()+ )-This simply grabs the value from the state and returns it as the result. It is purely a placeholder-for an action that should just use the result, although you do not need it.+ # (2) pass them in at runtime+ app.run( # or app.step, app.iterate, app.astep, etc.\n"+ halt_..., # your halt logic\n"+ inputs={"prompt": "this will be passed into `prompt`"} # <-- we pass in values here+ )-Refer to :ref:`actions <actions>` for documentation.+For instance, say you have a chatbot. The first step will likely declare the ``input`` parameter ``prompt`` --+it will take that, process it, and put the result in state. The subsequent steps will read the result of that from state.diff --git a/tests/core/test_application.py b/tests/core/test_application.pyindex 40f34ae6..c5d8d8e0 100644--- a/tests/core/test_application.py+++ b/tests/core/test_application.py@@ -1101,6 +1101,31 @@ def test_run_with_inputs():assert state["count"] == result["count"] == 11+def test_run_with_inputs_multiple_actions():+ """Tests that inputs aren't popped off and are passed through to multiple actions."""+ result_action = Result("count").with_name("result")+ counter_action1 = base_counter_action_with_inputs.with_name("counter1")+ counter_action2 = base_counter_action_with_inputs.with_name("counter2")+ app = Application(+ actions=[counter_action1, counter_action2, result_action],+ transitions=[+ Transition(counter_action1, counter_action1, Condition.expr("count < 10")),+ Transition(counter_action1, counter_action2, Condition.expr("count >= 10")),+ Transition(counter_action2, counter_action2, Condition.expr("count < 20")),+ Transition(counter_action2, result_action, default),+ ],+ state=State({}),+ initial_step="counter1",+ partition_key="test",+ uid="test-123",+ sequence_id=0,+ )+ action_, result, state = app.run(halt_after=["result"], inputs={"additional_increment": 8})+ assert action_.name == "result"+ assert state["count"] == result["count"] == 27+ assert state["__SEQUENCE_ID"] == 4++async def test_arun():result_action = Result("count").with_name("result")counter_action = base_counter_action_async.with_name("counter")@@ -1164,6 +1189,32 @@ async def test_arun_with_inputs():assert action_.name == "result"+async def test_arun_with_inputs_multiple_actions():+ result_action = Result("count").with_name("result")+ counter_action1 = base_counter_action_with_inputs_async.with_name("counter1")+ counter_action2 = base_counter_action_with_inputs_async.with_name("counter2")+ app = Application(+ actions=[counter_action1, counter_action2, result_action],+ transitions=[+ Transition(counter_action1, counter_action1, Condition.expr("count < 10")),+ Transition(counter_action1, counter_action2, Condition.expr("count >= 10")),+ Transition(counter_action2, counter_action2, Condition.expr("count < 20")),+ Transition(counter_action2, result_action, default),+ ],+ state=State({}),+ initial_step="counter1",+ partition_key="test",+ uid="test-123",+ sequence_id=0,+ )+ action_, result, state = await app.arun(+ halt_after=["result"], inputs={"additional_increment": 8}+ )+ assert state["count"] == result["count"] == 27+ assert action_.name == "result"+ assert state["__SEQUENCE_ID"] == 4++async def test_app_a_run_async_and_sync():result_action = Result("count").with_name("result")counter_action_sync = base_counter_action_async.with_name("counter_sync")