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 action tagging

elijahbenizzy5a7348717b6d
diff --git a/burr/core/action.py b/burr/core/action.py
index e3f17082..6da45afc 100644
--- a/burr/core/action.py
+++ b/burr/core/action.py
@@ -239,6 +239,15 @@ class Action(Function, Reducer, abc.ABC):
write_repr = ", ".join(self.writes) if self.writes else "{}"
return f"{self.name}: {read_repr} -> {write_repr}"
+ @property
+ def tags(self) -> list[str]:
+ """Returns the tags associated with this action.
+ Tags are effectively action aliases -- names that apply towards multiple actions.
+
+ :return: List of string tags
+ """
+ return []
+
class Condition(Function):
KEY = "PROCEED"
@@ -586,6 +595,7 @@ class FunctionBasedAction(SingleStepAction):
input_spec: Optional[tuple[list[str], list[str]]] = None,
originating_fn: Optional[Callable] = None,
schema: ActionSchema = DEFAULT_SCHEMA,
+ tags: Optional[List[str]] = None,
):
"""Instantiates a function-based action with the given function, reads, and writes.
The function must take in a state and return a tuple of (result, new_state).
@@ -611,6 +621,7 @@ class FunctionBasedAction(SingleStepAction):
)
)
self._schema = schema
+ self._tags = tags if tags is not None else []
@property
def fn(self) -> Callable:
@@ -632,6 +643,10 @@ class FunctionBasedAction(SingleStepAction):
def schema(self) -> ActionSchema:
return self._schema
+ @property
+ def tags(self) -> list[str]:
+ return self._tags
+
def with_params(self, **kwargs: Any) -> "FunctionBasedAction":
"""Binds parameters to the function.
Note that there is no reason to call this by the user. This *could*
@@ -649,6 +664,7 @@ class FunctionBasedAction(SingleStepAction):
input_spec=self._inputs,
originating_fn=self._originating_fn,
schema=self._schema,
+ tags=self._tags,
)
def run_and_update(self, state: State, **run_kwargs) -> tuple[dict, State]:
@@ -1063,6 +1079,7 @@ class FunctionBasedStreamingAction(SingleStepStreamingAction):
input_spec: Optional[tuple[list[str], list[str]]] = None,
originating_fn: Optional[Callable] = None,
schema: ActionSchema = DEFAULT_SCHEMA,
+ tags: Optional[List[str]] = None,
):
"""Instantiates a function-based streaming action with the given function, reads, and writes.
The function must take in a state (and inputs) and return a generator of (result, new_state).
@@ -1086,6 +1103,7 @@ class FunctionBasedStreamingAction(SingleStepStreamingAction):
)
self._originating_fn = originating_fn if originating_fn is not None else fn
self._schema = schema
+ self._tags = tags if tags is not None else []
async def _a_stream_run_and_update(
self, state: State, **run_kwargs
@@ -1115,6 +1133,10 @@ class FunctionBasedStreamingAction(SingleStepStreamingAction):
def streaming(self) -> bool:
return True
+ @property
+ def tags(self) -> list[str]:
+ return self._tags
+
def with_params(self, **kwargs: Any) -> "FunctionBasedStreamingAction":
"""Binds parameters to the function. This is not user-facing -- this is
meant to be used internally by the API.
@@ -1130,6 +1152,7 @@ class FunctionBasedStreamingAction(SingleStepStreamingAction):
input_spec=self._inputs,
originating_fn=self._originating_fn,
schema=self._schema,
+ tags=self._tags,
)
@property
@@ -1204,6 +1227,7 @@ class action:
writes: List[str],
state_input_type: Optional[Type["BaseModel"]] = None,
state_output_type: Optional[Type["BaseModel"]] = None,
+ tags: Optional[List[str]] = None,
) -> Callable:
"""Action that specifies inputs/outputs using pydantic models.
This should make it easier to develop with guardrails.
@@ -1216,6 +1240,7 @@ class action:
If this is None it will attempt to derive from the signature.
:param state_output_type: The pydantic model type that is used to represent the output state.
If this is None it will attempt to derive from the signature.
+ :param tags: Optional list of tags to associate with this action
:return:
"""
try:
@@ -1230,9 +1255,10 @@ class action:
writes=writes,
state_input_type=state_input_type,
state_output_type=state_output_type,
+ tags=tags,
)
- def __init__(self, reads: List[str], writes: List[str]):
+ def __init__(self, reads: List[str], writes: List[str], tags: Optional[List[str]] = None):
"""Decorator to create a function-based action. This is user-facing.
Note that, in the future, with typed state, we may not need this for
all cases.
@@ -1247,12 +1273,13 @@ class action:
"""
self.reads = reads
self.writes = writes
+ self.tags = tags
def __call__(self, fn) -> FunctionRepresentingAction:
setattr(
fn,
FunctionBasedAction.ACTION_FUNCTION,
- FunctionBasedAction(fn, self.reads, self.writes),
+ FunctionBasedAction(fn, self.reads, self.writes, tags=self.tags),
)
setattr(fn, "bind", types.MethodType(bind, fn))
return fn
@@ -1266,6 +1293,7 @@ class streaming_action:
state_input_type: Type["BaseModel"],
state_output_type: Type["BaseModel"],
stream_type: Union[Type["BaseModel"], Type[dict]],
+ tags: Optional[List[str]] = None,
) -> Callable:
"""Creates a streaming action that uses pydantic models.
@@ -1275,6 +1303,7 @@ class streaming_action:
Use a dict if you want this untyped.
:param state_input_type: The pydantic model type that is used to represent the input state.
:param state_output_type: The pydantic model type that is used to represent the output state.
+ :param tags: Optional list of tags to associate with this action
:return: The same function, decorated function.
"""
try:
@@ -1290,9 +1319,10 @@ class streaming_action:
state_input_type=state_input_type,
state_output_type=state_output_type,
stream_type=stream_type,
+ tags=tags,
)
- def __init__(self, reads: List[str], writes: List[str]):
+ def __init__(self, reads: List[str], writes: List[str], tags: Optional[List[str]] = None):
"""Decorator to create a streaming function-based action. This is user-facing.
If parameters are not bound, they will be interpreted as inputs and must be passed in at runtime.
@@ -1325,16 +1355,20 @@ class streaming_action:
# return the final result
return {'response': full_response}, state.update(response=full_response)
+ :param reads: The fields this consumes from the state.
+ :param writes: The fields this writes to the state.
+ :param tags: Optional list of tags to associate with this action
"""
self.reads = reads
self.writes = writes
+ self.tags = tags
def __call__(self, fn: Callable) -> FunctionRepresentingAction:
fn = copy_func(fn)
setattr(
fn,
FunctionBasedAction.ACTION_FUNCTION,
- FunctionBasedStreamingAction(fn, self.reads, self.writes),
+ FunctionBasedStreamingAction(fn, self.reads, self.writes, tags=self.tags),
)
setattr(fn, "bind", types.MethodType(bind, fn))
return fn
diff --git a/burr/core/application.py b/burr/core/application.py
index fe2fe792..66dc465c 100644
--- a/burr/core/application.py
+++ b/burr/core/application.py
@@ -1079,7 +1079,18 @@ class Application(Generic[ApplicationStateType]):
return next_action, result, new_state
- def _clean_iterate_params(
+ def _parse_action_list(self, action_list: list[str]) -> Tuple[List[str], List[str]]:
+ """Utility function to parse a list of actions/tags into a list of actions and a list of tags."""
+ actions = []
+ tags = []
+ for action in action_list:
+ if action.startswith("@tag"):
+ tags.append(action[len("@tag:") :])
+ else:
+ actions.append(action)
+ return actions, tags
+
+ def _process_control_flow_params(
self,
halt_before: list[str] = None,
halt_after: list[str] = None,
@@ -1092,13 +1103,18 @@ class Application(Generic[ApplicationStateType]):
logger.warning(
"No halt termination specified -- this has the possibility of running forever!"
)
- if halt_before is None:
- halt_before = []
- if halt_after is None:
- halt_after = []
- if inputs is None:
- inputs = {}
- return halt_before, halt_after, inputs
+ halt_before = halt_before or []
+ halt_after = halt_after or []
+ inputs = inputs or {}
+ halt_before_actions, halt_before_tags = self._parse_action_list(halt_before)
+ halt_after_actions, halt_after_tags = self._parse_action_list(halt_after)
+ halt_before_expanded = set(halt_before_actions)
+ for tag in halt_before_tags:
+ halt_before_expanded.update([item.name for item in self.graph.get_actions_by_tag(tag)])
+ halt_after_expanded = set(halt_after_actions)
+ for tag in halt_after_tags:
+ halt_after_expanded.update([item.name for item in self.graph.get_actions_by_tag(tag)])
+ return list(halt_before_expanded), list(halt_after_expanded), inputs
def _validate_halt_conditions(self, halt_before: list[str], halt_after: list[str]) -> None:
"""Utility function to validate halt conditions"""
@@ -1182,19 +1198,23 @@ class Application(Generic[ApplicationStateType]):
of the system as it updates. Note this returns a generator, and also the final result
(for convenience).
+ Note that tags must be specified by the form "@tag:<tag_name>" to differentiate them from actions.
+
Note the nuance with halt_before and halt_after. halt_before conditions will take precedence to halt_after. Furthermore,
a single iteration will always be executed prior to testing for any halting conditions.
- :param halt_before: The list of actions to halt before execution of. It will halt prior to the execution of the first one it sees.
- :param halt_after: The list of actions to halt after execution of. It will halt after the execution of the first one it sees.
+ :param halt_before: The list of actions/tags to halt before execution of. It will halt prior to the execution of the first one it sees.
+ :param halt_after: The list of actions/tags to halt after execution of. It will halt after the execution of the first one it sees.
:param inputs: Inputs to the action -- this is if this action requires an input that is passed in from the outside world.
Note that this is only used for the first iteration -- subsequent iterations will not use this.
:return: Each iteration returns the result of running `step`. This generator also returns a tuple of
[action, result, current state]
"""
self.validate_correct_async_use()
- halt_before, halt_after, inputs = self._clean_iterate_params(
- halt_before, halt_after, inputs
+ halt_before, halt_after, inputs = self._process_control_flow_params(
+ halt_before,
+ halt_after,
+ inputs,
)
self._validate_halt_conditions(halt_before, halt_after)
@@ -1220,14 +1240,16 @@ class Application(Generic[ApplicationStateType]):
"""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 halt_before: The list of actions to halt before execution of. It will halt on the first one.
- :param halt_after: The list of actions to halt after execution of. It will halt on the first one.
+ Note that tags must be specified by the form "@tag:<tag_name>" to differentiate them from actions.
+
+ :param halt_before: The list of actions/tags to halt before execution of. It will halt on the first one.
+ :param halt_after: The list of actions/tags to halt after execution of. It will halt on the first one.
:param inputs: Inputs to the action -- this is if this action requires an input that is passed in from the outside world.
Note that this is only used for the first iteration -- subsequent iterations will not use this.
:return: Each iteration returns the result of running `step`. This returns nothing -- it's an async generator which is not
allowed to have a return value.
"""
- halt_before, halt_after, inputs = self._clean_iterate_params(
+ halt_before, halt_after, inputs = self._process_control_flow_params(
halt_before, halt_after, inputs
)
self._validate_halt_conditions(halt_before, halt_after)
@@ -1250,8 +1272,10 @@ class Application(Generic[ApplicationStateType]):
"""Runs your application through until completion. Does
not give access to the state along the way -- if you want that, use iterate().
- :param halt_before: The list of actions to halt before execution of. It will halt on the first one.
- :param halt_after: The list of actions to halt after execution of. It will halt on the first one.
+ Note that tags must be specified by the form "@tag:<tag_name>" to differentiate them from actions.
+
+ :param halt_before: The list of actions/tags to halt before execution of. It will halt on the first one.
+ :param halt_after: The list of actions/tags to halt after execution of. It will halt on the first one.
:param inputs: Inputs to the action -- this is if this action requires an input that is passed in from the outside world.
Note that this is only used for the first iteration -- subsequent iterations will not use this.
:return: The final state, and the results of running the actions in the order that they were specified.
@@ -1277,15 +1301,17 @@ class Application(Generic[ApplicationStateType]):
"""Runs your application through until completion, using async. Does
not give access to the state along the way -- if you want that, use iterate().
- :param halt_before: The list of actions to halt before execution of. It will halt on the first one.
- :param halt_after: The list of actions to halt after execution of. It will halt on the first one.
+ Note that tags must be specified by the form "@tag:<tag_name>" to differentiate them from actions.
+
+ :param halt_before: The list of actions/tags to halt before execution of. It will halt on the first one.
+ :param halt_after: The list of actions/tags to halt after execution of. It will halt on the first one.
:param inputs: Inputs to the action -- this is if this action requires an input that is passed in from the outside world
:return: The final state, and the results of running the actions in the order that they were specified.
"""
prior_action = None
result = None
- halt_before, halt_after, inputs = self._clean_iterate_params(
+ halt_before, halt_after, inputs = self._process_control_flow_params(
halt_before, halt_after, inputs
)
self._validate_halt_conditions(halt_before, halt_after)
@@ -1304,8 +1330,8 @@ class Application(Generic[ApplicationStateType]):
) -> Tuple[Action, StreamingResultContainer[ApplicationStateType, Union[dict, Any]]]:
"""Streams a result out.
- :param halt_after: The list of actions to halt after execution of. It will halt on the first one.
- :param halt_before: The list of actions to halt before execution of. It will halt on the first one. Note that
+ :param halt_after: The list of actions/tags to halt after execution of. It will halt on the first one.
+ :param halt_before: The list of actions/tags to halt before execution of. It will halt on the first one. Note that
if this is met, the streaming result container will be empty (and return None) for the result, having an empty generator.
:param inputs: Inputs to the action -- this is if this action requires an input that is passed in from the outside world
:return: A streaming result container, which is a generator that will yield results as they come in, as well as cache/give you the final result,
@@ -1405,7 +1431,7 @@ class Application(Generic[ApplicationStateType]):
self.validate_correct_async_use()
call_execute_method_wrapper = _call_execute_method_pre_post(ExecuteMethod.stream_result)
call_execute_method_wrapper.call_pre(self)
- halt_before, halt_after, inputs = self._clean_iterate_params(
+ halt_before, halt_after, inputs = self._process_control_flow_params(
halt_before, halt_after, inputs
)
self._validate_halt_conditions(halt_before, halt_after)
@@ -1554,8 +1580,8 @@ class Application(Generic[ApplicationStateType]):
) -> Tuple[Action, AsyncStreamingResultContainer[ApplicationStateType, Union[dict, Any]]]:
"""Streams a result out in an asynchronous manner.
- :param halt_after: The list of actions to halt after execution of. It will halt on the first one.
- :param halt_before: The list of actions to halt before execution of. It will halt on the first one. Note that
+ :param halt_after: The list of actions/tags to halt after execution of. It will halt on the first one.
+ :param halt_before: The list of actions/tags to halt before execution of. It will halt on the first one. Note that
if this is met, the streaming result container will be empty (and return None) for the result, having an empty generator.
:param inputs: Inputs to the action -- this is if this action requires an input that is passed in from the outside world
:return: An asynchronous :py:class:`AsyncStreamingResultContainer <burr.core.action.AsyncStreamingResultContainer>`, which is a generator that will yield results as they come in, as well as cache/give you the final result,
@@ -1578,7 +1604,7 @@ class Application(Generic[ApplicationStateType]):
which will be empty. Thus ``halt_after`` takes precedence -- if it is met, the streaming result container will contain the result of the
halt_after condition.
- The :py:class:`AsyncStreamingResultContainer <burr.core.action.StreamingResultContainer>` is meant as a convenience -- specifically this allows for
+ The :py:class:`AsyncStreamingResultContainer <burr.core.action.AsyncStreamingResultContainer>` is meant as a convenience -- specifically this allows for
hooks, callbacks, etc... so you can take the control flow and still have state updated afterwards. Hooks/state update will be called after an exception
is thrown during streaming, or the stream is completed. Note that it is undefined behavior to attempt to execute another action while a stream is in progress.
@@ -1657,7 +1683,7 @@ class Application(Generic[ApplicationStateType]):
"""
call_execute_method_wrapper = _call_execute_method_pre_post(ExecuteMethod.stream_result)
await call_execute_method_wrapper.acall_pre(self)
- halt_before, halt_after, inputs = self._clean_iterate_params(
+ halt_before, halt_after, inputs = self._process_control_flow_params(
halt_before, halt_after, inputs
)
self._validate_halt_conditions(halt_before, halt_after)
diff --git a/burr/core/graph.py b/burr/core/graph.py
index 61bc4961..6b1ebba6 100644
--- a/burr/core/graph.py
+++ b/burr/core/graph.py
@@ -98,7 +98,8 @@ class Graph:
def __post_init__(self):
"""Sets up initial state for easy graph operations later"""
self._action_map = {action.name: action for action in self.actions}
- self._adjacency_map = Graph._create_adjacency_map(self.transitions)
+ self._adjacency_map = self._create_adjacency_map(self.transitions)
+ self._action_tag_map = self._create_action_tag_map(self.actions)
@staticmethod
def _create_adjacency_map(transitions: List[Transition]) -> dict:
@@ -109,6 +110,19 @@ class Graph:
adjacency_map[from_.name].append((to.name, transition.condition))
return adjacency_map
+ @staticmethod
+ def _create_action_tag_map(actions: List[Action]) -> dict[str, List[Action]]:
+ """Creates a mapping of action tags to lists of corresponding actions.
+
+ :param actions: List of Action objects
+ :return: Dictionary mapping action tags to lists of matching Action objects
+ """
+ tag_map = collections.defaultdict(list)
+ for action in actions:
+ for tag in action.tags:
+ tag_map[tag].append(action)
+ return dict(tag_map)
+
def get_next_node(
self, prior_step: Optional[str], state: State, entrypoint: str
) -> Optional[Action]:
@@ -130,6 +144,15 @@ class Graph:
)
return self._action_map.get(action_name)
+ def get_actions_by_tag(self, tag: str) -> List[Action]:
+ """Gets a list of actions given a tag. Note that, if no tags match the action a ValueError will be raised."""
+ if tag not in self._action_tag_map:
+ raise ValueError(
+ BASE_ERROR_MESSAGE + f"Tag: {tag} not found in graph. "
+ f"Tags are: {self._action_tag_map.keys()}."
+ )
+ return self._action_tag_map.get(tag)
+
@telemetry.capture_function_usage
def visualize(
self,
diff --git a/burr/integrations/pydantic.py b/burr/integrations/pydantic.py
index a42deeda..fb64078d 100644
--- a/burr/integrations/pydantic.py
+++ b/burr/integrations/pydantic.py
@@ -172,6 +172,7 @@ def pydantic_action(
writes: List[str],
state_input_type: Optional[Type[pydantic.BaseModel]] = None,
state_output_type: Optional[Type[pydantic.BaseModel]] = None,
+ tags: Optional[List[str]] = None,
) -> Callable[[PydanticActionFunction], PydanticActionFunction]:
"""See docstring for @action.pydantic"""
@@ -234,6 +235,7 @@ def pydantic_action(
output_type=SubsetOutputType,
intermediate_result_type=dict,
),
+ tags=tags,
),
)
setattr(fn, "bind", types.MethodType(bind, fn))
@@ -290,6 +292,7 @@ def pydantic_streaming_action(
state_input_type: Type[pydantic.BaseModel],
state_output_type: Type[pydantic.BaseModel],
stream_type: PartialType,
+ tags: Optional[List[str]] = None,
) -> Callable[[PydanticStreamingActionFunction], PydanticStreamingActionFunction]:
"""See docstring for @streaming_action.pydantic"""
@@ -353,6 +356,7 @@ def pydantic_streaming_action(
output_type=SubsetOutputType,
intermediate_result_type=stream_type_processed,
),
+ tags=tags,
),
)
setattr(fn, "bind", types.MethodType(bind, fn))
diff --git a/docs/concepts/actions.rst b/docs/concepts/actions.rst
index f8657e9e..541cea83 100644
--- a/docs/concepts/actions.rst
+++ b/docs/concepts/actions.rst
@@ -286,3 +286,28 @@ We need to pass in `client` and `prompt` somehow. Here are the ways to do that:
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.
+
+---------------
+Tagging Actions
+---------------
+
+You can tag actions with a list of strings -- this effectively functions as a "alias" for the action,
+so that a single alias can refer to multiple actions. This allows you to refer to a set of actions
+that have similar capabilities as one, using a variety of :ref:`application <applications>` APIs.
+
+.. code-block:: python
+
+ @action(reads=["..."], writes=["..."], tags=["response_to_display"])
+ def text_response(state: State, client: Client, prompt: str) -> 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 state.update(**result)
+
+This can be referred to either as the name of the action within the application, and/or as the tag
+``response_to_display`` -- referred to as ``@tag:response_to_display`` in the ``halt_after`` or ``halt_before`` parameters
+of :py:func:`Application.run <burr.core.application.Application.run>`, :py:func:`Application.iterate <burr.core.application.Application.iterate>`, etc.
+APIs.
+
+In all function-based APIs, you can pass in a list of tags with the ``tags`` parameter.
+In class-based APIs, you can set the ``tags`` property.
diff --git a/tests/core/test_action.py b/tests/core/test_action.py
index 675f5dd3..74f3664a 100644
--- a/tests/core/test_action.py
+++ b/tests/core/test_action.py
@@ -68,6 +68,10 @@ class BasicAction(Action):
def update(self, result: dict, state: State) -> State:
return state.update(**result)
+ @property
+ def tags(self) -> list[str]:
+ return ["tag1", "tag2"]
+
def test_with_name():
action = BasicAction()
@@ -76,6 +80,7 @@ def test_with_name():
assert with_name.name == "my_action" # Name set on copy
assert with_name.reads == action.reads
assert with_name.writes == action.writes
+ assert with_name.tags == action.tags
def test_condition():
@@ -230,7 +235,7 @@ def test_input():
def test_function_based_action():
- @action(reads=["input_variable"], writes=["output_variable"])
+ @action(reads=["input_variable"], writes=["output_variable"], tags=["tag1", "tag2"])
def my_action(state: State) -> Tuple[dict, State]:
return {"output_variable": state["input_variable"]}, state.update(
output_variable=state["input_variable"]
@@ -241,13 +246,14 @@ def test_function_based_action():
assert fn_based_action.name == "my_action"
assert fn_based_action.reads == ["input_variable"]
assert fn_based_action.writes == ["output_variable"]
+ assert fn_based_action.tags == ["tag1", "tag2"]
result, state = fn_based_action.run_and_update(State({"input_variable": "foo"}))
assert result == {"output_variable": "foo"}
assert state.get_all() == {"input_variable": "foo", "output_variable": "foo"}
def test_function_based_action_with_inputs():
- @action(reads=["input_variable"], writes=["output_variable"])
+ @action(reads=["input_variable"], writes=["output_variable"], tags=["tag1", "tag2"])
def my_action(state: State, bound_input: int, unbound_input: int) -> Tuple[dict, State]:
res = state["input_variable"] + bound_input + unbound_input
return {"output_variable": res}, state.update(output_variable=res)
@@ -256,6 +262,7 @@ def test_function_based_action_with_inputs():
SingleStepAction, create_action(my_action.bind(bound_input=10), name="my_action")
)
assert fn_based_action.inputs == (["unbound_input"], [])
+ assert fn_based_action.tags == ["tag1", "tag2"]
result, state = fn_based_action.run_and_update(State({"input_variable": 1}), unbound_input=100)
assert state.get_all() == {"input_variable": 1, "output_variable": 111}
assert result == {"output_variable": 111}
@@ -328,7 +335,7 @@ def test_function_based_action_with_defaults_unbound():
async def test_function_based_action_async():
- @action(reads=["input_variable"], writes=["output_variable"])
+ @action(reads=["input_variable"], writes=["output_variable"], tags=["tag1", "tag2"])
async def my_action(state: State) -> Tuple[dict, State]:
await asyncio.sleep(0.01)
return {"output_variable": state["input_variable"]}, state.update(
@@ -341,6 +348,7 @@ async def test_function_based_action_async():
assert fn_based_action.name == "my_action"
assert fn_based_action.reads == ["input_variable"]
assert fn_based_action.writes == ["output_variable"]
+ assert fn_based_action.tags == ["tag1", "tag2"]
result, state = await fn_based_action.run_and_update(State({"input_variable": "foo"}))
assert result == {"output_variable": "foo"}
assert state.get_all() == {"input_variable": "foo", "output_variable": "foo"}
@@ -391,10 +399,11 @@ def test_create_action_class_api():
assert created_action.name == "my_action"
assert created_action.reads == raw_action.reads
assert created_action.writes == raw_action.writes
+ assert created_action.tags == raw_action.tags
def test_create_action_fn_api():
- @action(reads=["input_variable"], writes=["output_variable"])
+ @action(reads=["input_variable"], writes=["output_variable"], tags=["tag1", "tag2"])
def test_action(state: State) -> Tuple[dict, State]:
result = {"output_variable": state["input_variable"]}
return result, state.update(output_variable=result["output_variable"])
@@ -404,6 +413,7 @@ def test_create_action_fn_api():
assert created_action.reads == ["input_variable"]
assert created_action.writes == ["output_variable"]
assert created_action.single_step
+ assert created_action.tags == ["tag1", "tag2"]
result, state = created_action.run_and_update(State({"input_variable": "foo"}))
assert result == {"output_variable": "foo"}
assert state.get_all() == {"input_variable": "foo", "output_variable": "foo"}
@@ -435,7 +445,7 @@ def test_create_action_fn_api_with_bind():
def test_create_action_streaming_fn_api_with_bind():
- @streaming_action(reads=["input_variable"], writes=["output_variable"])
+ @streaming_action(reads=["input_variable"], writes=["output_variable"], tags=["tag1", "tag2"])
def test_action(
state: State, prefix: str
) -> Generator[Tuple[dict, Optional[State]], None, None]:
@@ -452,6 +462,7 @@ def test_create_action_streaming_fn_api_with_bind():
assert created_action.name == "my_action"
assert created_action.reads == ["input_variable"]
assert created_action.writes == ["output_variable"]
+ assert created_action.tags == ["tag1", "tag2"]
assert created_action.single_step
gen = created_action.stream_run_and_update(State({"input_variable": "foo"}))
out = [item for item in gen]
@@ -463,7 +474,7 @@ def test_create_action_streaming_fn_api_with_bind():
async def test_create_action_streaming_fn_api_with_bind_async():
- @streaming_action(reads=["input_variable"], writes=["output_variable"])
+ @streaming_action(reads=["input_variable"], writes=["output_variable"], tags=["tag1", "tag2"])
async def test_action(
state: State, prefix: str
) -> AsyncGenerator[Tuple[dict, Optional[State]], None]:
@@ -483,6 +494,7 @@ async def test_create_action_streaming_fn_api_with_bind_async():
assert created_action.reads == ["input_variable"]
assert created_action.writes == ["output_variable"]
assert created_action.single_step
+ assert created_action.tags == ["tag1", "tag2"]
gen = created_action.stream_run_and_update(State({"input_variable": "foo"}))
out = [item async for item in gen]
final_result, state = out[-1]
diff --git a/tests/core/test_application.py b/tests/core/test_application.py
index bbc9df46..70676646 100644
--- a/tests/core/test_application.py
+++ b/tests/core/test_application.py
@@ -3531,3 +3531,29 @@ async def test_async_application_builder_initialize_raises_on_broken_persistor()
)
.abuild()
)
+
+
+def test_application__process_control_flow_params():
+ @action(reads=[], writes=[], tags=["tag1", "tag2"])
+ def test_action(state: State) -> State:
+ return state
+
+ @action(reads=[], writes=[], tags=["tag1", "tag3"])
+ def test_action_2(state: State) -> State:
+ return state
+
+ app = (
+ ApplicationBuilder()
+ .with_state(count=0)
+ .with_actions(test_action, test_action_2)
+ .with_transitions(("test_action", "test_action_2"))
+ .with_entrypoint("test_action")
+ .build()
+ )
+ halt_before, halt_after, inputs = app._process_control_flow_params(
+ halt_after=["@tag:tag1"], halt_before=["@tag:tag2"]
+ )
+
+ assert sorted(halt_after) == ["test_action", "test_action_2"]
+ assert halt_before == ["test_action"]
+ assert inputs == {}
diff --git a/tests/core/test_graph.py b/tests/core/test_graph.py
index 7fe6df56..c2013ee6 100644
--- a/tests/core/test_graph.py
+++ b/tests/core/test_graph.py
@@ -15,6 +15,7 @@ class PassedInAction(Action):
fn: Callable[..., dict],
update_fn: Callable[[dict, State], State],
inputs: list[str],
+ tags: list[str] = None,
):
super(PassedInAction, self).__init__()
self._reads = reads
@@ -22,6 +23,7 @@ class PassedInAction(Action):
self._fn = fn
self._update_fn = update_fn
self._inputs = inputs
+ self._tags = tags
def run(self, state: State, **run_kwargs) -> dict:
return self._fn(state, **run_kwargs)
@@ -41,6 +43,10 @@ class PassedInAction(Action):
def writes(self) -> list[str]:
return self._writes
+ @property
+ def tags(self) -> list[str]:
+ return self._tags or []
+
def test__validate_transitions_correct():
_validate_transitions(
@@ -87,6 +93,7 @@ base_counter_action = PassedInAction(
fn=lambda state: {"count": state.get("count", 0) + 1},
update_fn=lambda result, state: state.update(**result),
inputs=[],
+ tags=["tag1", "tag2"],
)
@@ -115,3 +122,36 @@ def test_graph_builder_get_next_node():
assert len(graph.actions) == 2
assert len(graph.transitions) == 2
assert graph.get_next_node(None, State({"count": 0}), entrypoint="counter").name == "counter"
+
+
+def test_get_actions_by_tag():
+ action_with_tags = PassedInAction(
+ reads=["count"],
+ writes=["count"],
+ fn=lambda state: {"count": state.get("count", 0) + 1},
+ update_fn=lambda result, state: state.update(**result),
+ inputs=[],
+ tags=["tag1", "tag2"],
+ )
+
+ action_with_tags_2 = PassedInAction(
+ reads=["count"],
+ writes=["count"],
+ fn=lambda state: {"count": state.get("count", 0) + 1},
+ update_fn=lambda result, state: state.update(**result),
+ inputs=[],
+ tags=["tag1", "tag3"],
+ )
+ graph = (
+ GraphBuilder()
+ .with_actions(counter1=action_with_tags, counter2=action_with_tags_2)
+ .with_transitions(("counter1", "counter2"))
+ .with_transitions(("counter2", "counter1"))
+ .build()
+ )
+ # tag1 is in both actions, tag2 is in one, tag3 is in one
+ assert len(graph.get_actions_by_tag("tag1")) == 2
+ assert len(graph.get_actions_by_tag("tag2")) == 1
+ assert len(graph.get_actions_by_tag("tag3")) == 1
+ with pytest.raises(ValueError, match="not found"):
+ graph.get_actions_by_tag("tag4")