Velamuvi AIAcademy

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
In this lesson you will learn
  • 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())
Output
['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:

  1. @workflow turns the function into a FunctionalWorkflowDefinition: a recipe. Its first parameter receives the input. @workflow(name="...", description="...") sets a name and description; otherwise the function name is used.
  2. .build() creates a FunctionalWorkflow, the runnable instance. Its run() takes the same arguments as a graph workflow's (stream=True, responses=..., checkpoint_id=...) and returns the same WorkflowRunResult.
  3. @step marks a function as a tracked step (the decorator returns a StepWrapper). Each call produces executor_invoked and executor_completed events named after the step. There are no supersteps here: your code decides the order.
  4. asyncio.gather runs the two check_stock calls at the same time, so the two one-second checks take about one second.
  5. The function's return value becomes the workflow's output, in an output event 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 methodWhat 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())
Output
  (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')]
  1. ctx.request_info(...) pauses the run. The result's state is IDLE_WITH_PENDING_REQUESTS, and get_request_info_events() lists the open questions, each with a request_id (generated as auto::0 unless you pass request_id=...) and its data.
  2. run(responses={request_id: answer}) resumes. Here a new instance resumes from the latest checkpoint in a FileCheckpointStorage, exactly what would happen after a server restart. The Human-in-the-Loop and Checkpoints lesson covers checkpoint storage in detail.
  3. On resume, the workflow function runs again from the top. Finished steps are replayed from the saved results: the executor_bypassed event shows that draft_reply, the expensive model call, did not run a second time. This time request_info returns the answer, and the function continues to send_reply.

Here's the replay mechanism in plain Python:

Try it yourselfPython
# 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 2

A 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())
Output
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. Its run() returns an AgentResponse, whose text is the workflow's return value, and run(..., stream=True) streams it.
  • The input reaches the workflow as it was given: a string stays a string, and a list of Message objects stays a list. Handle both if callers may send either.
  • If the workflow calls request_info, the agent's response contains a function_approval_request instead of an answer. Its id is the request ID: answer with await 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 asOne async functionExecutors connected by edges
Control flowif, for, await, asyncio.gatherConditions, switch-case, fan-out, fan-in
Picture of the flowRead the codeWorkflowViz draws it
Parallel workasyncio.gatherFan-out edges and supersteps
Status in 1.26ExperimentalStable
Best forPipelines and scripts, quick prototypesComplex routing, team-designed processes, long-running systems

Common mistakes

Practice exercise

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.

Your solutionPython
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
Knowledge check

A functional workflow paused at request_info and is now resumed with run(responses=...). What happens to its code?

Summary

  • @workflow turns an async function into a workflow definition; .build() gives a runnable FunctionalWorkflow with the same run() as graph workflows.
  • @step makes calls observable, replayable and checkpointed. Outside a workflow it's a normal function. Run steps in parallel with asyncio.gather.
  • RunContext (or get_run_context()) gives request_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 a FunctionalWorkflowAgent. 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.