Lesson 31 of 39 · Workflows
Human-in-the-Loop and Checkpoints
Pause Agent Framework workflows for human answers with request_info and response_handler, approve tool calls, and save and resume runs with checkpoints.
- 16 min read
- Intermediate
- Reviewed
- Pause a workflow with request_info and handle the answer in a @response_handler
- Send answers with run(responses=...), in normal and streaming runs
- Approve an agent's tool calls inside a workflow
- Save checkpoints with InMemoryCheckpointStorage and FileCheckpointStorage, and resume from them
- Make your own classes and executor attributes survive a checkpoint
Workflows that wait for people
Some steps shouldn't be decided by code or by a model alone. A refund over 50 EUR needs a manager's yes. A draft email needs a person to check it. In these places the workflow has to stop, ask, and wait, sometimes for minutes, sometimes until the next day.
Waiting until tomorrow means the program might restart in the meantime. So workflows can also save their progress:
This lesson builds Velo's refund desk: small refunds go through automatically, and bigger ones wait for the manager.
Asking a question: request_info
import asyncio
from dataclasses import dataclass
from typing import Never
from agent_framework import Executor, WorkflowBuilder, WorkflowContext, handler, response_handler
@dataclass
class RefundRequest: # what the manager is asked
order_id: str
amount: float
reason: str
class RefundDesk(Executor):
@handler
async def start(self, request: RefundRequest, ctx: WorkflowContext[Never, str]) -> None:
if request.amount <= 50:
await ctx.yield_output(f"{request.order_id}: refunded {request.amount:.2f} EUR automatically")
else: # pause and ask a person
await ctx.request_info(request, response_type=bool, request_id=f"refund-{request.order_id}")
@response_handler
async def on_decision(self, request: RefundRequest, approved: bool, ctx: WorkflowContext[Never, str]) -> None:
verdict = "refunded" if approved else "refused"
await ctx.yield_output(f"{request.order_id}: {verdict} {request.amount:.2f} EUR (manager)")
async def main():
workflow = WorkflowBuilder(start_executor=RefundDesk(id="refund_desk")).build()
result = await workflow.run(RefundRequest("A-1001", 19.99, "broken bell"))
print(result.get_outputs())
result = await workflow.run(RefundRequest("A-1042", 89.00, "wrong size"))
print(result.get_final_state().value)
request = result.get_request_info_events()[0]
print(request.request_id, "|", request.source_executor_id, "|", request.response_type.__name__)
print(request.data)
result = await workflow.run(responses={request.request_id: True}) # the manager says yes
print(result.get_outputs())
asyncio.run(main())['A-1001: refunded 19.99 EUR automatically'] IDLE_WITH_PENDING_REQUESTS refund-A-1042 | refund_desk | bool RefundRequest(order_id='A-1042', amount=89.0, reason='wrong size') ['A-1042: refunded 89.00 EUR (manager)']
Step by step:
ctx.request_info(data, response_type=..., request_id=...)asks the outside world a question.datacan be any object (here aRefundRequest), andresponse_typesays what kind of answer is expected (herebool). Therequest_idis optional: without it the framework creates a random one. A readable ID likerefund-A-1042is easier to store and find, but it must be unique among the open questions.- The run stops when there's no more work, with the state
IDLE_WITH_PENDING_REQUESTS.result.get_request_info_events()lists the questions. Each event has arequest_id, itsdata, theresponse_type, and thesource_executor_idof the executor that asked. workflow.run(responses={request_id: answer})delivers the answer and continues the same workflow.run()takes a message or responses, never both: passing both raisesValueError: Cannot provide both 'message' and 'responses'. Use one or the other.- The answer goes to the method marked
@response_handlerin the executor that asked. It receives the original request (request), the answer (approved) and a context, so it knows exactly what was approved.
The framework picks the response handler from its type annotations: the first parameter's type must match the request's data, and the second the answer. One executor can have several response handlers for different request types. If you prefer not to rely on annotations, give the types to the decorator: @response_handler(request=RefundRequest, response=bool, workflow_output=str).
Matching answers to questions
Here is the bookkeeping the framework does for you, in plain Python. Run it, then try answering both questions in one call:
# How request_info and response_handler pair up, in plain Python.
pending = {} # request_id -> (question, handler)
def request_info(request_id, question, handler):
pending[request_id] = (question, handler) # the workflow pauses here
def on_decision(question, approved): # plays the part of a @response_handler
print(question["order"], "refunded" if approved else "refused")
def run(responses): # like workflow.run(responses=...)
for request_id, answer in responses.items():
question, handler = pending.pop(request_id)
handler(question, answer)
print("still waiting:", list(pending))
request_info("refund-A-1042", {"order": "A-1042", "amount": 89.0}, on_decision)
request_info("refund-A-1077", {"order": "A-1077", "amount": 640.0}, on_decision)
print("waiting:", list(pending))
run({"refund-A-1042": True}) # answer one now...
run({"refund-A-1077": False}) # ...and the other laterThe real workflow works the same way:
- You can answer several questions in one call or one at a time. While any question is open, the state stays
IDLE_WITH_PENDING_REQUESTS. get_request_info_events()only lists questions asked during that run. After a partial answer it can be empty although a question is still open, so keep your own list of open request IDs (or read them from a checkpoint, shown later).- An answer of the wrong type fails with
ValueError: Response type mismatch for request ID refund-A-1042: expected <class 'bool'>, got <class 'str'>, and an unknown ID withValueError: Response provided for unknown request ID: .... workflow.cancel_pending_requests([request_id])withdraws a question nobody will answer. The response handler doesn't run, and the workflow continues with its other work.
An approval loop in the console
A real desk handles a batch of refunds and shows results as they arrive. With stream=True, questions arrive as request_info events, and you answer them with a new streaming run:
import asyncio
from dataclasses import dataclass
from typing import Never
from agent_framework import Executor, WorkflowBuilder, WorkflowContext, handler, response_handler
@dataclass
class RefundRequest:
order_id: str
amount: float
reason: str
class BatchDesk(Executor):
@handler
async def start(self, batch: list[RefundRequest], ctx: WorkflowContext[Never, str]) -> None:
for request in batch:
if request.amount <= 50:
await ctx.yield_output(f"{request.order_id}: refunded automatically")
else:
await ctx.request_info(request, response_type=bool, request_id=f"refund-{request.order_id}")
@response_handler
async def on_decision(self, request: RefundRequest, approved: bool, ctx: WorkflowContext[Never, str]) -> None:
await ctx.yield_output(f"{request.order_id}: {'refunded' if approved else 'refused'} by the manager")
async def main():
workflow = WorkflowBuilder(start_executor=BatchDesk(id="batch_desk")).build()
batch = [RefundRequest("A-1001", 19.99, "broken bell"),
RefundRequest("A-1042", 89.00, "wrong size"),
RefundRequest("A-1077", 640.00, "changed my mind")]
stream = workflow.run(batch, stream=True)
while True:
pending = {}
async for event in stream:
if event.type == "output":
print(event.data)
elif event.type == "request_info":
pending[event.request_id] = event.data
if not pending: # nothing left to ask: done
break
answers = {}
for request_id, request in pending.items():
reply = input(f"Refund {request.amount:.2f} EUR for {request.order_id} ({request.reason})? [y/n] ")
answers[request_id] = reply.strip().lower() == "y"
stream = workflow.run(responses=answers, stream=True) # continue with the answers
asyncio.run(main())What the manager sees in the terminal, typing y and then n:
A-1001: refunded automatically Refund 89.00 EUR for A-1042 (wrong size)? [y/n] y Refund 640.00 EUR for A-1077 (changed my mind)? [y/n] n A-1042: refunded by the manager A-1077: refused by the manager
The while True loop is the standard pattern: run until the stream ends, collect the questions, ask a person, continue with the answers, and stop when a run ends without new questions. In a web app the same steps happen across requests: save the open request IDs, show the questions on a page, and call run(responses=...) when the manager clicks a button.
Approving an agent's tool calls
When an agent inside a workflow calls a tool marked approval_mode="always_require", its AgentExecutor pauses the workflow in the same way. The question is a function_approval_request (see the Tool Approval and User Input lesson):
import asyncio
from agent_framework import Agent, WorkflowBuilder, tool
from agent_framework.openai import OpenAIChatClient
@tool(approval_mode="always_require") # a person must approve every call
def issue_refund(order_id: str, amount: float) -> str:
"""Refund an order to the customer's card."""
return f"refunded {amount:.2f} EUR for {order_id}"
async def main():
agent = Agent(client=OpenAIChatClient(model="MODEL_NAME"), name="refunds",
instructions="You handle refunds for Velo, a bike shop. Use issue_refund when asked.",
tools=[issue_refund])
workflow = WorkflowBuilder(start_executor=agent).build()
result = await workflow.run("Please refund order A-1042, 89 EUR, wrong size.")
request = result.get_request_info_events()[0]
approval = request.data # a function_approval_request
print(request.source_executor_id, "|", approval.type, "|", approval.function_call.name,
approval.function_call.parse_arguments())
answer = approval.to_function_approval_response(approved=True)
result = await workflow.run(responses={request.request_id: answer})
print(result.get_outputs()[0].text)
asyncio.run(main())refunds | function_approval_request | issue_refund {'order_id': 'A-1042', 'amount': 89.0}
Done: refunded 89.00 EUR for A-1042request.datais the approval request.approval.function_callshows the tool name and arguments the model chose, so the person sees exactly what will happen.approval.to_function_approval_response(approved=True)creates the answer. Withapproved=Falsethe tool doesn't run, and the model receives the tool resultError: Tool call invocation was rejected by user.so it can tell the customer.- A run without streaming may log a warning such as
Response resp_1 contains 1 user input requests but total message contents are 2.It comes from version 1.26 itself: the agent's reply holds both the tool call and the approval request, and only the request is passed on. You can ignore it.
Checkpoints: saving a run as it goes
Give WorkflowBuilder a checkpoint storage, and the workflow saves a checkpoint at the start of a run and after every superstep. Here the payment service fails on the first try:
import asyncio
from typing import Never
from agent_framework import InMemoryCheckpointStorage, WorkflowBuilder, WorkflowContext, executor
payment_service_up = False # the first attempt will fail
@executor(id="reserve_stock")
async def reserve_stock(order_id: str, ctx: WorkflowContext[str]) -> None:
print(" reserved stock for", order_id)
await ctx.send_message(order_id)
@executor(id="charge_card")
async def charge_card(order_id: str, ctx: WorkflowContext[str]) -> None:
if not payment_service_up:
raise ConnectionError("payment service unavailable")
print(" charged card for", order_id)
await ctx.send_message(order_id)
@executor(id="send_receipt")
async def send_receipt(order_id: str, ctx: WorkflowContext[Never, str]) -> None:
await ctx.yield_output(f"receipt sent for {order_id}")
async def main():
global payment_service_up
storage = InMemoryCheckpointStorage()
workflow = (
WorkflowBuilder(name="order_pipeline", start_executor=reserve_stock, checkpoint_storage=storage)
.add_chain([reserve_stock, charge_card, send_receipt])
.build()
)
try:
await workflow.run("A-1042")
except ConnectionError as error:
print("run failed:", error)
for checkpoint in await storage.list_checkpoints(workflow_name="order_pipeline"):
print(f"superstep {checkpoint.iteration_count}: messages in transit from {list(checkpoint.messages)}")
payment_service_up = True # later: the service is back
latest = await storage.get_latest(workflow_name="order_pipeline")
result = await workflow.run(checkpoint_id=latest.checkpoint_id)
print(result.get_outputs())
asyncio.run(main())reserved stock for A-1042 run failed: payment service unavailable superstep 0: messages in transit from ['internal:reserve_stock'] superstep 1: messages in transit from ['reserve_stock'] charged card for A-1042 ['receipt sent for A-1042']
InMemoryCheckpointStoragekeeps checkpoints in a dictionary. It's quick and needs no setup, and it's gone when the program stops: good for tests, retries and learning.list_checkpoints(workflow_name=...)returnsWorkflowCheckpointobjects. The one after superstep 1 holds the message thatreserve_stocksent andcharge_cardnever processed. (internal:reserve_stockin the first one is your input, waiting for the start executor.)get_latest(workflow_name=...)returns the newest checkpoint, andrun(checkpoint_id=...)restores it and continues. Stock is not reserved a second time: the run picks up exactly where it failed.- The name comes from
WorkflowBuilder(name="order_pipeline", ...). Without a name, each build gets a random one such asWorkflowBuilder-3f2b..., and a restarted program can't find its own checkpoints.
Pause today, answer tomorrow
FileCheckpointStorage(folder) writes each checkpoint to a JSON file, so it survives restarts. Monday's program asks the question and ends; Tuesday's program, a completely new process, gives the answer:
import asyncio
import tempfile
from dataclasses import dataclass
from pathlib import Path
from typing import Never
from agent_framework import (CheckpointStorage, Executor, FileCheckpointStorage, WorkflowBuilder, WorkflowContext,
handler, register_checkpoint_type, response_handler)
@dataclass
class RefundRequest:
order_id: str
amount: float
reason: str
register_checkpoint_type(RefundRequest) # let checkpoints save and load this class
class RefundDesk(Executor):
@handler
async def start(self, request: RefundRequest, ctx: WorkflowContext[Never, str]) -> None:
await ctx.request_info(request, response_type=bool, request_id=f"refund-{request.order_id}")
@response_handler
async def on_decision(self, request: RefundRequest, approved: bool, ctx: WorkflowContext[Never, str]) -> None:
await ctx.yield_output(f"{request.order_id}: {'refunded' if approved else 'refused'} by the manager")
def build_desk(storage: CheckpointStorage): # the same name and graph every time
return WorkflowBuilder(name="refund_desk", start_executor=RefundDesk(id="refund_desk"),
checkpoint_storage=storage).build()
async def monday(storage: CheckpointStorage):
result = await build_desk(storage).run(RefundRequest("A-1042", 89.00, "wrong size"))
print("Monday:", result.get_final_state().value)
async def tuesday(storage: CheckpointStorage): # a new process: nothing left in memory
latest = await storage.get_latest(workflow_name="refund_desk")
for request_id, event in latest.pending_request_info_events.items():
print("Tuesday, still waiting:", request_id, event.data)
result = await build_desk(storage).run(checkpoint_id=latest.checkpoint_id, responses={"refund-A-1042": True})
print("Tuesday:", result.get_outputs())
for checkpoint_id in await storage.list_checkpoint_ids(workflow_name="refund_desk"):
await storage.delete(checkpoint_id) # the case is closed: tidy up
async def main():
folder = Path(tempfile.mkdtemp()) # in a real app: a fixed folder
await monday(FileCheckpointStorage(folder))
print("Files on disk:", len(list(folder.glob("*.json"))))
await tuesday(FileCheckpointStorage(folder))
print("Files on disk:", len(list(folder.glob("*.json"))))
asyncio.run(main())Monday: IDLE_WITH_PENDING_REQUESTS Files on disk: 2 Tuesday, still waiting: refund-A-1042 RefundRequest(order_id='A-1042', amount=89.0, reason='wrong size') Tuesday: ['A-1042: refunded by the manager'] Files on disk: 0
- Monday's run pauses with one open question. Two checkpoint files are written: one at the start and one after the superstep that asked.
- On Tuesday nothing is left in memory.
get_latestloads the newest checkpoint, and itspending_request_info_eventsstill holds the full question, including theRefundRequestobject. run(checkpoint_id=..., responses=...)restores the checkpoint and answers in one call. The workflow was rebuilt by the samebuild_desk()function, so the graph matches.- Checkpoints pile up, one or more per superstep. When a case is finished, delete them with
list_checkpoint_ids()anddelete().
You can also leave the storage out of the builder and pass it per run: workflow.run(checkpoint_id=..., checkpoint_storage=storage).
Your own classes in checkpoints
FileCheckpointStorage saves plain values (text, numbers, lists, dictionaries) as JSON. Other objects are saved with Python's pickle format, and to keep loading safe, only a list of allowed types can be loaded back: basic Python types, Agent Framework's own types and OpenAI SDK types. Your classes must be allowed explicitly, in one of two ways:
register_checkpoint_type(RefundRequest)once at start-up, as in the example. It applies to every storage in the program.FileCheckpointStorage(folder, allowed_checkpoint_types=["my_shop.refunds:RefundRequest"]), with the module and class name. It applies to that storage only.
A class that isn't allowed is refused when the checkpoint is saved, not when it's loaded. The error is only logged, and the workflow keeps running without checkpoints, so check your logs (see Common mistakes).
What a checkpoint contains
A WorkflowCheckpoint is a plain data object. The fields you'll use most:
| Field | What it holds |
|---|---|
checkpoint_id | Its unique ID. The type CheckpointID is simply a str |
workflow_name, graph_signature_hash | Which workflow it belongs to, and a fingerprint of the graph's shape |
messages | Messages sent but not yet processed |
state | The shared state from ctx.set_state, and each executor's saved state |
pending_request_info_events | Open questions, by request ID |
iteration_count, previous_checkpoint_id, timestamp | Where in the run it was taken, and which checkpoint came before |
Shared state is saved automatically, and so is the state of built-in executors such as AgentExecutor. Attributes of your own executor classes are not. To save one, override two methods:
class RefundCounter(Executor):
def __init__(self, id: str):
super().__init__(id=id)
self.refunds_today = 0 # an attribute: not saved on its own
@handler
async def count(self, order_id: str, ctx: WorkflowContext[str]) -> None:
self.refunds_today += 1
ctx.set_state("last_order", order_id) # shared state: saved automatically
await ctx.send_message(f"{order_id} is refund {self.refunds_today} today")
async def on_checkpoint_save(self) -> dict[str, Any]: # called when a checkpoint is made
return {"refunds_today": self.refunds_today}
async def on_checkpoint_restore(self, state: dict[str, Any]) -> None: # called on resume
self.refunds_today = state.get("refunds_today", 0)After two refunds, a new RefundCounter restored from the latest checkpoint continues with "refund 3 today". Without the two methods it says "refund 1 today", because the restored instance starts from __init__.
Every storage has the same six async methods, described by the CheckpointStorage protocol: save, load, list_checkpoints, list_checkpoint_ids, get_latest and delete. Any class with these methods can store checkpoints, for example in your own database. Ready-made options:
| Storage | Where checkpoints live | Cost |
|---|---|---|
InMemoryCheckpointStorage | Program memory, lost on exit | Free |
FileCheckpointStorage | JSON files in a folder | Free |
CosmosCheckpointStorage (package agent-framework-azure-cosmos, preview) | Azure Cosmos DB, shared by many servers | Paid Azure service, with a free tier and a free local emulator |
Common mistakes
Save a checkpoint after every step, then resume the failed run from the latest checkpoint, so that reserve_stock does not run twice.
import json
steps = ["reserve_stock", "charge_card", "send_receipt"]
saved = [] # stands in for checkpoint storage
def run(start_at=0, fail_at=None):
for i in range(start_at, len(steps)):
if i == fail_at:
print("failed at", steps[i])
return
print("ran", steps[i])
# 1. Save a checkpoint here: append json.dumps({"next": i + 1}) to saved.
run(fail_at=1)
# 2. Resume: load the latest checkpoint from saved and call run() from its "next" step.
Your program restarts overnight. In the morning the manager approves a refund that was asked yesterday. What does the new program need to continue the run?
Summary
ctx.request_info(data, response_type=...)pauses a workflow withIDLE_WITH_PENDING_REQUESTS. The answer, sent withrun(responses={request_id: answer}), goes to the executor's@response_handlertogether with the original request.- With
stream=True, questions arrive asrequest_infoevents. Loop: collect them, ask a person, run again with the answers. Agents' tool approvals arrive the same way asfunction_approval_requestcontent. - A checkpoint storage on
WorkflowBuildersaves a checkpoint after every superstep. Resume withrun(checkpoint_id=...), also in a new process withFileCheckpointStorage. Always give the workflow a fixedname. - Allow your own classes with
register_checkpoint_type, save executor attributes withon_checkpoint_saveandon_checkpoint_restore, and only load checkpoints you trust. - A checkpoint fits one graph. A changed workflow raises
WorkflowCheckpointException.
Next: Sequential and Concurrent Orchestration.
Finished reading? Tick it off to track your progress.