Lesson 29 of 39 · Workflows
Functional Workflows
Write Agent Framework workflows as plain async Python with @workflow and @step: parallel steps, RunContext, human input, replay, checkpoints and agent use.
- 11 min read
- Intermediate
- Reviewed
- Write a workflow as an ordinary async function with @workflow
- Track, cache and observe calls with @step
- Run steps in parallel with asyncio.gather
- Use RunContext for state, events and human input, and explain replay
- Turn a functional workflow into an agent, and choose between functional and graph workflows
The same ideas, written as a function
Graph workflows make every step and edge explicit. That's great for complex routing, but for a simple pipeline it's a lot of ceremony: classes, handlers, edges and type annotations on the context. Agent Framework offers a second style:
You still get the workflow features: events, outputs, human-in-the-loop pauses, checkpoints and running as an agent.
Your first functional workflow
import asyncio
from agent_framework import step, workflow
@step
async def fetch_order(order_id: str) -> dict:
return {"id": order_id, "items": ["helmet", "lights"], "total": 74.5}
@step
async def check_stock(item: str) -> str:
await asyncio.sleep(1) # pretend to ask the warehouse
return f"{item}: in stock"
@step
async def write_receipt(order: dict, stock: list[str]) -> str:
return f"Receipt {order['id']}: {'; '.join(stock)}. Total {order['total']:.2f} EUR"
@workflow
async def order_pipeline(order_id: str) -> str: # ordinary Python control flow
order = await fetch_order(order_id)
stock = await asyncio.gather(*(check_stock(item) for item in order["items"])) # in parallel
return await write_receipt(order, list(stock)) # the return value is the output
async def main():
pipeline = order_pipeline.build() # a runnable FunctionalWorkflow
result = await pipeline.run("A-1042") # the same kind of result as a graph workflow
print(result.get_outputs())
for event in result:
print(f"{event.type:<20} {event.executor_id}")
asyncio.run(main())['Receipt A-1042: helmet: in stock; lights: in stock. Total 74.50 EUR'] executor_invoked fetch_order executor_completed fetch_order executor_invoked check_stock executor_invoked check_stock executor_completed check_stock executor_completed check_stock executor_invoked write_receipt executor_completed write_receipt output order_pipeline
What's happening:
@workflowturns the function into aFunctionalWorkflowDefinition: a recipe. Its first parameter receives the input.@workflow(name="...", description="...")sets a name and description; otherwise the function name is used..build()creates aFunctionalWorkflow, the runnable instance. Itsrun()takes the same arguments as a graph workflow's (stream=True,responses=...,checkpoint_id=...) and returns the sameWorkflowRunResult.@stepmarks a function as a tracked step (the decorator returns aStepWrapper). Each call producesexecutor_invokedandexecutor_completedevents named after the step. There are no supersteps here: your code decides the order.asyncio.gatherruns the twocheck_stockcalls at the same time, so the two one-second checks take about one second.- The function's return value becomes the workflow's output, in an
outputevent named after the workflow.
What @step adds
@step is optional: plain async functions work inside a @workflow too. Add @step when a call should be:
- Observable: it appears as events, and in traces.
- Replayable: when a paused workflow resumes, finished steps return their saved result instead of running again (next sections).
- Checkpointed: its result is saved with the workflow's checkpoint.
Outside a workflow, a step is just the original function: await fetch_order("A-1") works in a unit test with no workflow running. @step(name="...") changes the name used in events. @step only accepts async functions; decorating a normal def raises TypeError: @step can only decorate async functions, but 'not_async' is not a coroutine function.
RunContext: the workflow's toolbox
Add a parameter annotated RunContext (or simply named ctx) to the workflow function or to a step, and the framework passes in the run's context:
RunContext method | What it does |
|---|---|
await ctx.request_info(data, response_type=...) | Pauses the workflow until a person or system answers, then returns the answer |
ctx.get_state(key, default) and ctx.set_state(key, value) | Key-value state for this run, saved in checkpoints |
await ctx.add_event(event) | Adds your own event to the run, for example progress updates |
ctx.is_streaming() | True when the run was started with stream=True |
Helper code that isn't a step can still reach the context with get_run_context(), which returns the active RunContext inside a workflow and None outside one.
Unlike a graph workflow's shared state, this state belongs to one run: a second run() with a new input starts empty. It survives pauses and checkpoints, not separate runs.
Human input, replay and restarts
Here, a person must approve each reply before it's sent:
import asyncio
import tempfile
from agent_framework import FileCheckpointStorage, RunContext, step, workflow
@step
async def draft_reply(question: str) -> str:
print(" (drafting, an expensive model call)")
return f"Thanks for asking about {question}. We are open 9:00-18:00."
@step
async def send_reply(text: str) -> str:
return f"SENT: {text}"
@workflow
async def support(question: str, ctx: RunContext) -> str:
draft = await draft_reply(question)
decision = await ctx.request_info({"draft": draft}, response_type=str) # pause for a person
if decision == "approve":
return await send_reply(draft)
return f"Not sent: {decision}"
async def main():
storage = FileCheckpointStorage(tempfile.mkdtemp()) # saved to disk
first = support.build(checkpoint_storage=storage)
result = await first.run("opening hours")
print(result.get_final_state().value)
request = result.get_request_info_events()[0]
print("waiting for", request.request_id, "with", request.data)
# Later, even after a restart: a NEW instance resumes from the latest checkpoint.
latest = await storage.get_latest(workflow_name=first.name)
second = support.build(checkpoint_storage=storage)
result = await second.run(responses={request.request_id: "approve"}, checkpoint_id=latest.checkpoint_id)
print(result.get_outputs())
print([(event.type, event.executor_id) for event in result if event.type.startswith("executor")])
asyncio.run(main()) (drafting, an expensive model call)
IDLE_WITH_PENDING_REQUESTS
waiting for auto::0 with {'draft': 'Thanks for asking about opening hours. We are open 9:00-18:00.'}
['SENT: Thanks for asking about opening hours. We are open 9:00-18:00.']
[('executor_bypassed', 'draft_reply'), ('executor_invoked', 'send_reply'), ('executor_completed', 'send_reply')]ctx.request_info(...)pauses the run. The result's state isIDLE_WITH_PENDING_REQUESTS, andget_request_info_events()lists the open questions, each with arequest_id(generated asauto::0unless you passrequest_id=...) and itsdata.run(responses={request_id: answer})resumes. Here a new instance resumes from the latest checkpoint in aFileCheckpointStorage, exactly what would happen after a server restart. The Human-in-the-Loop and Checkpoints lesson covers checkpoint storage in detail.- On resume, the workflow function runs again from the top. Finished steps are replayed from the saved results: the
executor_bypassedevent shows thatdraft_reply, the expensive model call, did not run a second time. This timerequest_inforeturns the answer, and the function continues tosend_reply.
Here's the replay mechanism in plain Python:
# How resuming works, in plain Python: the workflow function runs again from the top,
# but steps that already finished return their saved result instead of running again.
saved = {} # stands in for the checkpoint
answers = {} # what the person has answered so far
class Paused(Exception):
pass
def step(name, func, *args):
if name in saved:
print(f" replayed {name}")
return saved[name]
print(f" ran {name}")
saved[name] = func(*args)
return saved[name]
def request_info(question):
if question in answers:
return answers[question]
raise Paused(question)
def support(question):
draft = step("draft_reply", lambda q: f"About {q}: open 9-18", question)
decision = request_info("approve?")
return step("send_reply", lambda d: "SENT " + d, draft) if decision == "yes" else "not sent"
for attempt in (1, 2):
print("run", attempt)
try:
print(" output:", support("opening hours"))
except Paused as pause:
print(" paused, waiting for:", pause)
answers["approve?"] = "yes" # a person answers before run 2A step is recognised on replay by its name and arguments. If two calls could look identical but mean different things (for example the same arguments run twice in parallel with different results), give the step a replay_key: @step(replay_key=lambda connection, record_id: record_id) returns a stable, unique string for each call.
A functional workflow as an agent
.as_agent() wraps a workflow so anything that expects an agent can use it: a chat interface, another agent's tools, an orchestration.
import asyncio
from agent_framework import Message, step, workflow
@step
async def lookup_hours(day: str) -> str:
return {"saturday": "10:00-16:00", "sunday": "closed"}.get(day, "9:00-18:00")
@workflow(name="hours_bot", description="Answers questions about opening hours")
async def hours_bot(question: str | list[Message]) -> str:
text = question if isinstance(question, str) else question[-1].text # input arrives as given
day = next((d for d in ("saturday", "sunday") if d in text.lower()), "a weekday")
return f"On {day} we are open: {await lookup_hours(day)}."
async def main():
agent = hours_bot.build().as_agent() # a FunctionalWorkflowAgent
print(type(agent).__name__, "-", agent.name, "-", agent.description)
response = await agent.run("Are you open on Sunday?")
print(response.text)
response = await agent.run([Message("user", ["Is Saturday possible?"])])
print(response.text)
asyncio.run(main())FunctionalWorkflowAgent - hours_bot - Answers questions about opening hours On sunday we are open: closed. On saturday we are open: 10:00-16:00.
- The result is a
FunctionalWorkflowAgent. Itsrun()returns anAgentResponse, whose text is the workflow's return value, andrun(..., stream=True)streams it. - The input reaches the workflow as it was given: a string stays a string, and a list of
Messageobjects stays a list. Handle both if callers may send either. - If the workflow calls
request_info, the agent's response contains afunction_approval_requestinstead of an answer. Itsidis the request ID: answer withawait agent.run(responses={request_id: answer}). - One instance keeps its pending requests and checkpoints, so build one per caller, just like graph workflows.
Functional or graph?
Functional (@workflow) | Graph (WorkflowBuilder) | |
|---|---|---|
| Written as | One async function | Executors connected by edges |
| Control flow | if, for, await, asyncio.gather | Conditions, switch-case, fan-out, fan-in |
| Picture of the flow | Read the code | WorkflowViz draws it |
| Parallel work | asyncio.gather | Fan-out edges and supersteps |
| Status in 1.26 | Experimental | Stable |
| Best for | Pipelines and scripts, quick prototypes | Complex routing, team-designed processes, long-running systems |
Common mistakes
Write the replay logic behind @step: the first time a step runs, save its result; when the workflow runs again, return the saved result instead of running the step.
cache = {}
def run_step(name, func, value):
# If name is already in cache: print "replayed <name>" and return the saved result.
# Otherwise: print "ran <name>", call func(value), save the result in cache, return it.
pass
def pipeline(order_id):
order = run_step("fetch", lambda i: {"id": i, "total": 50}, order_id)
receipt = run_step("receipt", lambda o: f"{o['id']}: {o['total']} EUR", order)
return receipt
print(pipeline("A-1"))
print(pipeline("A-1")) # like a resumed run: every step is replayed
A functional workflow paused at request_info and is now resumed with run(responses=...). What happens to its code?
Summary
@workflowturns an async function into a workflow definition;.build()gives a runnableFunctionalWorkflowwith the samerun()as graph workflows.@stepmakes calls observable, replayable and checkpointed. Outside a workflow it's a normal function. Run steps in parallel withasyncio.gather.RunContext(orget_run_context()) givesrequest_info, per-run state and custom events.- On resume the function reruns from the top and finished steps replay, so keep side effects inside steps.
.as_agent()returns aFunctionalWorkflowAgent. Functional workflows are experimental; graph workflows are the stable choice for complex systems.
Next: Agents in Workflows and Workflows as Agents.
Finished reading? Tick it off to track your progress.