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.

feat: improve default viz (#309)

Thierry Jeanf3fb3766b614
diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml
index f0830a50..3dec66a7 100644
--- a/.github/workflows/python-package.yml
+++ b/.github/workflows/python-package.yml
@@ -28,13 +28,21 @@ jobs:
steps:
- uses: actions/checkout@v3
+
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v3
with:
python-version: ${{ matrix.python-version }}
+
+ - name: Install Graphviz system dependency
+ run: |
+ sudo apt-get install -y --no-install-recommends graphviz
+ sudo apt-get clean
+
- name: Install dependencies
run: |
- python -m pip install -e ".[tests,tracking-client]"
+ python -m pip install -e ".[tests,tracking-client,graphviz]"
+
- name: Run tests
run: |
python -m pytest tests --ignore=tests/integrations/persisters
diff --git a/burr/core/application.py b/burr/core/application.py
index 92826625..5f0140fb 100644
--- a/burr/core/application.py
+++ b/burr/core/application.py
@@ -1474,6 +1474,7 @@ class Application:
include_state: bool = False,
view: bool = False,
engine: Literal["graphviz"] = "graphviz",
+ write_dot: bool = False,
**engine_kwargs: Any,
) -> Optional["graphviz.Digraph"]: # noqa: F821
"""Visualizes the application graph using graphviz. This will render the graph.
@@ -1484,6 +1485,7 @@ class Application:
:param include_state: Whether to indicate the action "signature" (reads/writes) on the nodes
:param view: Whether to bring up a view
:param engine: The engine to use -- only graphviz is supported for now
+ :param write_dot: If True, produce a graphviz dot file
:param engine_kwargs: Additional kwargs to pass to the engine
:return: The graphviz object
"""
@@ -1493,6 +1495,7 @@ class Application:
include_state=include_state,
view=view,
engine=engine,
+ write_dot=write_dot,
**engine_kwargs,
)
diff --git a/burr/core/graph.py b/burr/core/graph.py
index 7ad98bb6..ff70a4b1 100644
--- a/burr/core/graph.py
+++ b/burr/core/graph.py
@@ -2,6 +2,7 @@ import collections
import dataclasses
import inspect
import logging
+import pathlib
from typing import Any, Callable, List, Literal, Optional, Set, Tuple, Union
from burr import telemetry
@@ -53,6 +54,39 @@ def _validate_transitions(
return True
+def _render_graphviz(
+ graphviz_obj,
+ output_file_path: Union[str, pathlib.Path],
+ view: bool = False,
+ write_dot: bool = False,
+) -> None:
+ """Generate an image file for the graphviz object.
+
+ Use graphviz's `.render()` to produce a dot file or open the image
+ on the OS (i.e., `view` arg)
+ Use .pipe()` to not produce a not file; can't open the image
+ """
+ output_file_path = pathlib.Path(output_file_path)
+
+ if output_file_path.suffix != "":
+ # infer format from path; i.e., extract `svg` from the `.svg` suffix
+ format = output_file_path.suffix.partition(".")[-1]
+ else:
+ format = "png"
+
+ path_without_suffix = pathlib.Path(output_file_path.parent, output_file_path.stem)
+ if write_dot or view:
+ # `.render()` appends the `format` kwarg to the filename
+ # i.e., we need to pass `/my/filepath` to generate `/my/filepath.png`
+ # otherwise, passing `/my/filepath.png` will generate `/my/filepath.png.png`
+ graphviz_obj.render(path_without_suffix, format=format, view=view)
+ else:
+ # `.pipe()` doesn't append the format to the filename, so we do it explicitly
+ pathlib.Path(f"{path_without_suffix}.{format}").write_bytes(
+ graphviz_obj.pipe(format=format)
+ )
+
+
@dataclasses.dataclass
class Graph:
"""Graph class allows you to specify actions and transitions between them.
@@ -100,11 +134,12 @@ class Graph:
@telemetry.capture_function_usage
def visualize(
self,
- output_file_path: Optional[str] = None,
+ output_file_path: Optional[Union[str, pathlib.Path]] = None,
include_conditions: bool = False,
include_state: bool = False,
view: bool = False,
engine: Literal["graphviz"] = "graphviz",
+ write_dot: bool = False,
**engine_kwargs: Any,
) -> Optional["graphviz.Digraph"]: # noqa: F821
"""Visualizes the graph using graphviz. This will render the graph.
@@ -115,6 +150,7 @@ class Graph:
:param include_state: Whether to indicate the action "signature" (reads/writes) on the nodes
:param view: Whether to bring up a view
:param engine: The engine to use -- only graphviz is supported for now
+ :param write_dot: If True, produce a graphviz dot file
:param engine_kwargs: Additional kwargs to pass to the engine
:return: The graphviz object
"""
@@ -135,6 +171,11 @@ class Graph:
compound="false",
concentrate="false",
),
+ node_attr=dict(
+ fontname="Helvetica",
+ margin="0.15",
+ fillcolor="#b4d8e4",
+ ),
)
for g_key, g_value in engine_kwargs.items():
if isinstance(g_value, dict):
@@ -148,14 +189,14 @@ class Graph:
if not include_state
else f"{action.name}({', '.join(action.reads)}): {', '.join(action.writes)}"
)
- digraph.node(action.name, label=label, shape="box", style="rounded")
+ digraph.node(action.name, label=label, shape="box", style="rounded,filled")
required_inputs, optional_inputs = action.optional_and_required_inputs
for input_ in required_inputs | optional_inputs:
if input_.startswith("__"):
# These are internally injected by the framework
continue
input_name = f"input__{input_}"
- digraph.node(input_name, shape="oval", style="dashed", label=f"input: {input_}")
+ digraph.node(input_name, shape="rect", style="dashed", label=f"input: {input_}")
digraph.edge(input_name, action.name)
for transition in self.transitions:
condition = transition.condition
@@ -165,10 +206,27 @@ class Graph:
label=condition.name if include_conditions and condition is not default else None,
style="dashed" if transition.condition is not default else "solid",
)
+
if output_file_path:
- digraph.render(output_file_path, view=view)
+ _render_graphviz(
+ graphviz_obj=digraph,
+ output_file_path=output_file_path,
+ view=view,
+ write_dot=write_dot,
+ )
+
return digraph
+ def _repr_mimebundle_(self, include=None, exclude=None, **kwargs):
+ """Attribute read by notebook renderers
+ This returns the attribute of the `graphviz.Digraph` returned by `self.display_all_functions()`
+
+ The parameters `include`, `exclude`, and `**kwargs` are required, but not explicitly used
+ ref: https://ipython.readthedocs.io/en/stable/config/integrating.html
+ """
+ dot = self.visualize(include_conditions=True, include_state=False)
+ return dot._repr_mimebundle_(include=include, exclude=exclude, **kwargs)
+
class GraphBuilder:
"""GraphBuilder class. This allows you to construct a graph without considering application concerns.
diff --git a/tests/core/test_graphviz_display.py b/tests/core/test_graphviz_display.py
new file mode 100644
index 00000000..7fda9fdd
--- /dev/null
+++ b/tests/core/test_graphviz_display.py
@@ -0,0 +1,53 @@
+import pathlib
+
+import pytest
+
+from burr.core.graph import GraphBuilder
+
+from tests.core.test_graph import PassedInAction
+
+
+def base_counter_action():
+ yield PassedInAction(
+ reads=["count"],
+ writes=["count"],
+ fn=lambda state: {"count": state.get("count", 0) + 1},
+ update_fn=lambda result, state: state.update(**result),
+ inputs=[],
+ )
+
+
+def graph(base_counter_action):
+ yield (
+ GraphBuilder()
+ .with_actions(counter=base_counter_action)
+ .with_transitions(("counter", "counter"))
+ .build()
+ )
+
+
+ "filename, write_dot", [("app", False), ("app.png", False), ("app", True), ("app.png", True)]
+)
+def test_visualize_dot_output(graph, tmp_path: pathlib.Path, filename: str, write_dot: bool):
+ """Handle file generation with `graph.Digraph` `.render()` and `.pipe()`"""
+ output_file_path = f"{tmp_path}/{filename}"
+
+ graph.visualize(
+ output_file_path=output_file_path,
+ write_dot=write_dot,
+ )
+
+ # assert pathlib.Path(tmp_path, "app.png").exists()
+ assert pathlib.Path(tmp_path, "app").exists() == write_dot
+
+
+def test_visualize_no_dot_output(graph, tmp_path: pathlib.Path):
+ """Check that no dot file is generated when output_file_path=None"""
+ dot_file_path = tmp_path / "dag"
+
+ graph.visualize(output_file_path=None)
+
+ assert not dot_file_path.exists()