Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions burr/core/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -606,6 +606,15 @@ class ApplicationGraph(Graph):

entrypoint: Action

def to_dict(self) -> dict[str, Any]:
"""Return JSON-serializable application graph metadata.

:return: Graph metadata including the application's entrypoint.
"""
graph_data = super().to_dict()
graph_data.update(type="application_graph", entrypoint=self.entrypoint.name)
return graph_data


@dataclasses.dataclass
class ApplicationIdentifiers:
Expand Down
31 changes: 31 additions & 0 deletions burr/core/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,37 @@ def get_actions_by_tag(self, tag: str) -> List[Action]:
)
return self._action_tag_map.get(tag)

def to_dict(self) -> dict[str, Any]:
"""Return a dependency-free, JSON-serializable representation of the graph.

Actions and transitions retain their declaration order. Unordered action
metadata is sorted so repeated exports are deterministic.

:return: Graph metadata suitable for external tools and user interfaces.
"""
actions = []
for action in self.actions:
required_inputs, optional_inputs = action.optional_and_required_inputs
actions.append(
{
"name": action.name,
"reads": sorted(action.reads),
"writes": sorted(action.writes),
"inputs": sorted(required_inputs),
"optional_inputs": sorted(optional_inputs),
"tags": sorted(action.tags),
}
)
transitions = [
{
"from": transition.from_.name,
"to": transition.to.name,
"condition": transition.condition.name,
}
for transition in self.transitions
]
return {"type": "graph", "actions": actions, "transitions": transitions}

def visualize(
self,
output_file_path: Optional[Union[str, pathlib.Path]] = None,
Expand Down
18 changes: 18 additions & 0 deletions docs/reference/application.rst
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,24 @@ of situations.

The ``GraphBuilder`` class is used to build a graph, and the ``Graph`` class can be passed to the application builder.

Graphs can also be exported without Graphviz or tracking dependencies. ``to_dict()``
returns JSON-serializable action and transition metadata for external tools, API
responses, and custom user interfaces:

.. code-block:: python

import json

graph_data = application.graph.to_dict()
payload = json.dumps(graph_data)

``ApplicationGraph.to_dict()`` additionally includes the application entrypoint and
uses ``application_graph`` as its type. This compact metadata format intentionally
omits action source code and is distinct from the tracking subsystem's persisted
``ApplicationModel`` format. Action and transition declaration order is preserved,
while set-like metadata such as reads, writes, inputs, and tags is sorted for
deterministic output.

.. autoclass:: burr.core.graph.GraphBuilder
:members:

Expand Down
80 changes: 78 additions & 2 deletions tests/core/test_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@
# specific language governing permissions and limitations
# under the License.

from typing import Callable
import json
from typing import Callable, Union

import pytest

from burr.core import Action, Condition, Result, State, default
from burr.core.application import ApplicationGraph
from burr.core.graph import GraphBuilder, _validate_actions, _validate_transitions


Expand All @@ -31,7 +33,7 @@ def __init__(
writes: list[str],
fn: Callable[..., dict],
update_fn: Callable[[dict, State], State],
inputs: list[str],
inputs: Union[list[str], tuple[list[str], list[str]]],
tags: list[str] = None,
):
super(PassedInAction, self).__init__()
Expand Down Expand Up @@ -204,3 +206,77 @@ def test_get_actions_by_tag():
assert len(graph.get_actions_by_tag("tag3")) == 1
with pytest.raises(ValueError, match="not found"):
graph.get_actions_by_tag("tag4")


def test_graph_to_dict_returns_dependency_free_structure():
export_action = PassedInAction(
reads=["z_read", "a_read"],
writes=["z_write", "a_write"],
fn=lambda state, **inputs: inputs,
update_fn=lambda result, state: state,
inputs=(["z_required", "a_required"], ["z_optional", "a_optional"]),
tags=["z_tag", "a_tag"],
)
graph = (
GraphBuilder()
.with_actions(zeta=export_action, alpha=Result("a_read"))
.with_transitions(
("zeta", "alpha", Condition.expr("a_read < z_read")),
("alpha", "zeta"),
)
.build()
)

exported = graph.to_dict()

assert exported == {
"type": "graph",
"actions": [
{
"name": "zeta",
"reads": ["a_read", "z_read"],
"writes": ["a_write", "z_write"],
"inputs": ["a_required", "z_required"],
"optional_inputs": ["a_optional", "z_optional"],
"tags": ["a_tag", "z_tag"],
},
{
"name": "alpha",
"reads": ["a_read"],
"writes": [],
"inputs": [],
"optional_inputs": [],
"tags": [],
},
],
"transitions": [
{"from": "zeta", "to": "alpha", "condition": "a_read < z_read"},
{"from": "alpha", "to": "zeta", "condition": "default"},
],
}
assert json.loads(json.dumps(exported)) == exported


def test_application_graph_to_dict_includes_entrypoint():
counter = base_counter_action.with_name("counter")
graph = ApplicationGraph(
actions=[counter],
transitions=[],
entrypoint=counter,
)

assert graph.to_dict() == {
"type": "application_graph",
"entrypoint": "counter",
"actions": [
{
"name": "counter",
"reads": ["count"],
"writes": ["count"],
"inputs": [],
"optional_inputs": [],
"tags": ["tag1", "tag2"],
}
],
"transitions": [],
}
Loading