Lesson 28 of 39 · Workflows
Workflow State, Types and Visualization
Share data between Agent Framework executors with workflow state, design message types the graph checks, save custom state and draw workflows with WorkflowViz.
- 12 min read
- Intermediate
- Reviewed
- Share data between executors with set_state and get_state
- Explain how long workflow state lives, and when to build a fresh workflow
- Design message types that the graph check understands
- Register custom classes so saved session state can be restored
- Draw a workflow as a Mermaid or Graphviz diagram with WorkflowViz
Three places for data
Executors often need information that isn't in the message they just received: an order's audit trail, a customer's language, a running total. In a workflow, data can live in three places:
| Where | How | Lives for | Good for |
|---|---|---|---|
| In the message | Fields of the object you send | One hop | Everything the next step needs |
| Shared workflow state | ctx.set_state and ctx.get_state | The whole Workflow object | Data many steps read, such as an audit trail |
| Executor attributes | self.something in a class executor | The executor object | Caches and connections, not per-run data |
Prefer messages: they make each step's inputs obvious and easy to test. Use shared state for data that many executors need and that would clutter every message.
Shared workflow state
Every executor's context can read and write a shared store of key-value pairs:
import asyncio
from dataclasses import dataclass
from typing import Never
from agent_framework import WorkflowBuilder, WorkflowContext, executor
@dataclass
class Order:
id: str
total: float
@executor(id="check_stock")
async def check_stock(order: Order, ctx: WorkflowContext[Order]) -> None:
log = ctx.get_state("audit", []) # a COPY of the list (or [] the first time)
log.append(f"{order.id}: stock ok")
ctx.set_state("audit", log) # write the changed list back
await ctx.send_message(order)
@executor(id="charge")
async def charge(order: Order, ctx: WorkflowContext[Never, str]) -> None:
log = ctx.get_state("audit", [])
log.append(f"{order.id}: charged {order.total:.2f}")
ctx.set_state("audit", log)
await ctx.yield_output(f"{order.id} done, audit has {len(log)} lines")
async def main():
workflow = WorkflowBuilder(start_executor=check_stock).add_edge(check_stock, charge).build()
print((await workflow.run(Order("A-1", 120.0))).get_outputs())
print((await workflow.run(Order("A-2", 35.5))).get_outputs()) # same workflow object
asyncio.run(main())['A-1 done, audit has 2 lines'] ['A-2 done, audit has 4 lines']
ctx.set_state(key, value)stores a value, andctx.get_state(key, default)reads it, returningdefaultif the key doesn't exist. Neither needsawait.get_statereturns a deep copy. Changing the list you got back doesn't change the state, so afterlog.append(...)you must callset_stateagain, as both executors do.- Writes go into a pending buffer that every executor can read straight away. At the end of each superstep the buffer is committed, and that committed state is what a checkpoint saves. If two executors in the same superstep write the same key, the last write wins, so parallel branches should use different keys.
- Keys that start with
_are reserved for the framework.
How long state lives
Look at the second line of output: 4 audit lines, not 2. Shared state belongs to the Workflow object and survives from one run() to the next. That's deliberate: when a workflow acts as an agent (the Agents in Workflows and Workflows as Agents lesson), each new user message is another run(), and the conversation's state must survive. Attributes of class executors behave the same way.
When runs must be independent, for example one workflow per customer or per job, build a fresh workflow for each one:
import asyncio
from dataclasses import dataclass
from typing import Never
from agent_framework import Executor, Workflow, WorkflowBuilder, WorkflowContext, handler
@dataclass
class Order:
id: str
total: float
class Charge(Executor):
def __init__(self) -> None:
super().__init__(id="charge")
self.charged = 0.0 # an attribute: lives as long as the object
@handler
async def charge(self, order: Order, ctx: WorkflowContext[Never, str]) -> None:
self.charged += order.total
await ctx.yield_output(f"{order.id}: total charged by this executor {self.charged:.2f}")
def build_workflow() -> Workflow: # new executors, new state, every call
return WorkflowBuilder(start_executor=Charge()).build()
async def main():
shared = build_workflow()
for order in [Order("A-1", 120.0), Order("A-2", 35.5)]:
print("shared:", (await shared.run(order)).get_outputs())
for order in [Order("A-1", 120.0), Order("A-2", 35.5)]:
print("fresh: ", (await build_workflow().run(order)).get_outputs())
asyncio.run(main())shared: ['A-1: total charged by this executor 120.00'] shared: ['A-2: total charged by this executor 155.50'] fresh: ['A-1: total charged by this executor 120.00'] fresh: ['A-2: total charged by this executor 35.50']
The same idea in plain Python. An object keeps its data until you make a new one:
# Why a reused object "remembers": state lives as long as the object that holds it.
class Charge:
def __init__(self):
self.charged = 0.0
def run(self, amount):
self.charged += amount
return self.charged
shared = Charge() # one object for every customer
print("shared:", [shared.run(a) for a in (120.0, 35.5)])
fresh = [Charge().run(a) for a in (120.0, 35.5)] # a new object per customer
print("fresh: ", fresh)Message types the graph can check
A message can be any Python object, but dataclasses and Pydantic models work best: their fields document what travels between steps, and the type hints let build() check every edge.
import asyncio
from dataclasses import dataclass
from typing import Never
from agent_framework import TypeCompatibilityError, WorkflowBuilder, WorkflowContext, executor
@dataclass
class Event: # a base message type
customer: str
@dataclass
class Payment(Event): # a more specific kind of Event
amount: float
@executor(id="receive")
async def receive(raw: str, ctx: WorkflowContext[Event]) -> None:
customer, amount = raw.split(":")
await ctx.send_message(Payment(customer, float(amount)))
@executor(id="log_event")
async def log_event(event: Event, ctx: WorkflowContext[Never, str]) -> None: # accepts any Event
await ctx.yield_output(f"{type(event).__name__} from {event.customer}")
@executor(id="refund")
async def refund(amount: float, ctx: WorkflowContext[Never, str]) -> None:
await ctx.yield_output(f"refunded {amount}")
async def main():
workflow = WorkflowBuilder(start_executor=receive).add_edge(receive, log_event).build()
print(workflow.input_types, workflow.output_types)
print((await workflow.run("ana:49.90")).get_outputs()) # a Payment reaches the Event handler
try:
WorkflowBuilder(start_executor=receive).add_edge(receive, refund).build()
except TypeCompatibilityError as error:
print(error)
try:
await workflow.run(49.90) # receive only accepts str
except RuntimeError as error:
print(error)
asyncio.run(main())[<class 'str'>] [<class 'str'>] ['Payment from ana'] [TYPE_COMPATIBILITY] Type incompatibility between executors 'receive' -> 'refund'. Source executor outputs types ["<class '__main__.Event'>"] but target executor can only handle types ["<class 'float'>"]. Start executor 'receive' cannot handle input of type 'float'. Expected input types: [<class 'str'>].
What this shows:
workflow.input_typesandworkflow.output_typesare worked out from the start executor's handler and from the second type of everyWorkflowContext.- A handler for a base class also receives its subclasses:
log_eventacceptsEvent, so aPaymentreaches it. Use this to give one executor a whole family of messages. A handler typedAnyaccepts everything. TypeCompatibilityErrorcomes frombuild(), when an edge connects a sender to a target that can't accept any of the sender's declared types.- Passing the wrong type to
run()raises aRuntimeErrornaming the expected types.
State that must survive a restart
Everything above lives in memory. Two kinds of state can be saved and loaded again later:
| State | Saved by | Custom classes need |
|---|---|---|
| Workflow state, executor state and messages in transit | Checkpoints (the Human-in-the-Loop and Checkpoints lesson) | register_checkpoint_type(MyClass) |
An agent session's state, for example the state of an agent's context providers, or of a workflow running as an agent | session.to_dict() and session stores | register_state_type(MyClass, ...) |
Plain values (text, numbers, lists and dicts of them) work everywhere. For your own classes, the framework needs to know how to turn them into data and back. This is how register_state_type does that for session state:
import json
from dataclasses import asdict, dataclass
from pydantic import BaseModel
from agent_framework import AgentSession, register_state_type
@dataclass
class Basket:
items: list[str]
total: float
class Preferences(BaseModel):
language: str = "en"
newsletter: bool = False
# Register once, right after defining each class.
register_state_type(
Basket,
type_id="bikeshop.basket", # stored in the saved data; keep it stable
encoder=asdict, # Basket -> dict
decoder=lambda data: Basket(items=data["items"], total=data["total"]), # dict -> Basket
)
register_state_type(Preferences, type_id="bikeshop.preferences") # Pydantic: no codec needed
session = AgentSession(session_id="customer-42")
session.state["basket"] = Basket(["helmet", "lights"], 74.5)
session.state["prefs"] = Preferences(language="hi")
saved = json.dumps(session.to_dict()) # store this in a file or database
print(saved)
restored = AgentSession.from_dict(json.loads(saved)) # later, maybe in another process
print(restored.state["basket"])
print(restored.state["prefs"]){"type": "session", "session_id": "customer-42", "service_session_id": null, "state": {"basket": {"items": ["helmet", "lights"], "total": 74.5, "type": "bikeshop.basket"}, "prefs": {"language": "hi", "newsletter": false, "type": "bikeshop.preferences"}}}
Basket(items=['helmet', 'lights'], total=74.5)
language='hi' newsletter=False- The saved data includes a
"type"field with yourtype_id. Keep it stable forever, or old saved sessions can't be loaded. Make it unique, for example by starting it with your app's name. - Pydantic models and classes with
to_dict()andfrom_dict()get a codec automatically. Other classes, such as dataclasses, need anencoderand adecoder. - The decoder receives the saved mapping including the
"type"key, so pick the fields you need instead of writingBasket(**data). That fails withgot an unexpected keyword argument 'type'. - Without registration,
to_dict()warns that durable session stores will reject the value, andjson.dumpsfails withObject of type Basket is not JSON serializable. - Registering the same class twice with different ids raises
ValueError: State type 'Basket' is already registered as 'bikeshop.basket', not 'bikeshop.other'.
Drawing a workflow
As workflows grow, a picture helps. WorkflowViz turns a workflow into a diagram:
from typing import Never
from agent_framework import WorkflowBuilder, WorkflowContext, WorkflowViz, executor
@executor(id="start")
async def start(review: str, ctx: WorkflowContext[str]) -> None:
await ctx.send_message(review)
@executor(id="sentiment")
async def sentiment(review: str, ctx: WorkflowContext[str]) -> None:
await ctx.send_message("negative" if "late" in review else "positive")
@executor(id="topics")
async def topics(review: str, ctx: WorkflowContext[str]) -> None:
await ctx.send_message("delivery" if "late" in review else "product")
@executor(id="report")
async def report(results: list[str], ctx: WorkflowContext[str]) -> None:
await ctx.send_message(", ".join(sorted(results)))
@executor(id="escalate")
async def escalate(summary: str, ctx: WorkflowContext[Never, str]) -> None:
await ctx.yield_output(f"Escalated: {summary}")
def is_negative(summary: str) -> bool:
return "negative" in summary
workflow = (
WorkflowBuilder(start_executor=start)
.add_fan_out_edges(start, [sentiment, topics])
.add_fan_in_edges([sentiment, topics], report)
.add_edge(report, escalate, condition=is_negative)
.build()
)
viz = WorkflowViz(workflow)
print(viz.to_mermaid()) # paste into any Mermaid viewer
dot_text = viz.to_digraph() # Graphviz DOT text
viz.save_svg("review_workflow.svg") # needs: pip install graphviz, plus the Graphviz program
print("saved review_workflow.svg")flowchart TD start["start (Start)"]; sentiment["sentiment"]; topics["topics"]; report["report"]; escalate["escalate"]; fan_in__report__948a3476((fan-in)) sentiment --> fan_in__report__948a3476; topics --> fan_in__report__948a3476; fan_in__report__948a3476 --> report; start --> sentiment; start --> topics; report -. conditional .-> escalate; saved review_workflow.svg
| Method | Gives you |
|---|---|
to_mermaid() | Mermaid text: paste it into a Markdown file on GitHub, or any Mermaid editor |
to_digraph() | Graphviz DOT text |
export(format="svg"), save_svg(), save_png(), save_pdf() | An image file |
The start executor is marked, a fan-in appears as a small circle, and conditional edges are dashed. Image export needs the graphviz Python package (pip install graphviz) and the free Graphviz program (for example sudo apt-get install graphviz or brew install graphviz); without them you get an ImportError that explains what to install. Pass include_internal_executors=True to also see the helper executors the framework adds.
Common mistakes
Build a small copy of how workflow state works: writes go to a pending buffer as deep copies, reads return deep copies, and commit moves pending writes into committed state.
import copy
class State:
def __init__(self):
self.committed = {}
self.pending = {}
def set(self, key, value):
# Store a deep copy of value in self.pending
pass
def get(self, key, default=None):
# Look in pending first, then committed. Return a deep copy, or default if missing.
pass
def commit(self):
# Move everything from pending into committed, then empty pending
pass
state = State()
state.set("seen", ["ticket-1"])
seen = state.get("seen")
seen.append("ticket-2") # changes only the copy
print(state.get("seen"))
state.set("seen", seen) # write it back
print(state.committed, state.pending)
state.commit() # the end of a superstep
print(state.committed, state.pending)
print(state.get("missing", "none"))
An executor runs items = ctx.get_state('items') and then items.append('x'), but never calls set_state. What does the next executor see in 'items'?
Summary
- Data can travel in messages, in shared workflow state or in executor attributes. Prefer messages.
set_stateandget_stateshare data between executors. Reads return copies, writes are committed at the end of each superstep, and the last write wins.- Shared state and executor attributes live as long as the
Workflowobject: build a fresh workflow per conversation or job. - Typed messages (dataclasses, Pydantic models, subclasses) let
build()raiseTypeCompatibilityError. Undeclared types are dropped silently. register_state_typemakes custom classes in session state restorable (checkpoints useregister_checkpoint_type), andWorkflowVizdraws workflows as Mermaid, DOT or images.
Next: Functional Workflows.
Finished reading? Tick it off to track your progress.