Run an agent loop inside a workflow so a crashed run resumes where it stopped, without calling the model or a tool again.
An agent run can take minutes and a hundred model calls. When its process dies at call 53,
starting over pays for 52 calls again and runs their tools again. A
workflow avoids that: each activity's result is stored, and a resumed run
gets the stored results back instead of running them. But an agent loop is
generate_text in a while loop, not a list of activities.
pyfect.ai.durable.layer closes that gap. Provide it over the LanguageModel a workflow
uses, and every model request and every tool call the model makes inside the workflow runs
as an activity of it. The agent's code does not change. Outside a workflow the layer does
nothing.
from collections import Counter
from typing import TypedDict
import pyfect as fx
from pyfect import schema as S
from pyfect import stream
from pyfect.ai import durable, language_model, prompt, tool, toolkit
from pyfect.ai.ai_error import AiError
from pyfect.ai.language_model import LanguageModel, ProviderOptions
from pyfect.testing import explore
from pyfect.workflow import workflow, workflow_engine
class City(TypedDict):
city: str
class Trip(TypedDict):
cities: list[str]
Weather = tool.make("Weather", parameters=S.Struct(City), success=S.String)
Tools = toolkit.make(Weather)
model_calls: Counter[int] = Counter()
lookups: Counter[str] = Counter()
def weather(params: City, _ctx: object):
return fx.sync(lambda: lookups.update([params["city"]])).as_("sunny")
WeatherLive = Tools.to_layer(Weather.handler(weather))
# A scripted model: it asks for one city's weather a turn, then answers.
def answer(options: ProviderOptions):
asked = sum(1 for message in options.prompt.content if message.role == "tool")
model_calls[asked] += 1
cities = ["Lisbon", "Oslo", "Kyoto"]
usage = {"inputTokens": {"total": 9}, "outputTokens": {"total": 4}}
if asked == len(cities):
return fx.succeed(
[
{"type": "text", "text": "Pack light."},
{"type": "finish", "reason": "stop", "usage": usage},
]
)
call = {
"type": "tool-call",
"id": f"w{asked}",
"name": "Weather",
"params": {"city": cities[asked]},
}
return fx.succeed([call, {"type": "finish", "reason": "tool-calls", "usage": usage}])
Scripted = fx.layer.effect(
LanguageModel, language_model.make(generate_text=answer, stream_text=lambda _: stream.empty)
)
Planner = workflow.make(
"Planner",
payload=S.Struct(Trip),
success=S.String,
error=AiError,
idempotency_key=lambda trip: ",".join(trip["cities"]),
)
# The agent loop is plain LanguageModel code: no activities in sight.
@fx.fn
def plan(trip: Trip, _execution_id: str):
history = prompt.make(f"Plan a trip to {', '.join(trip['cities'])}")
while True:
reply = yield from language_model.generate_text(history, toolkit=Tools)
history = history.concat(prompt.from_response_parts(reply.content))
if not reply.tool_calls:
return reply.text
# durable.layer over the model makes each request and each tool call an activity.
Services = durable.layer.pipe(fx.layer.provide_merge(Scripted)).pipe(
fx.layer.provide_merge(WeatherLive)
)
PlannerLive = (
Planner.to_layer(plan)
.pipe(fx.layer.provide_merge(Services))
.pipe(fx.layer.provide_merge(workflow_engine.layer_memory))
)
# Stop the run after each step, before its result was stored and after, and resume it.
# Each time, count the steps that ran again.
extra_runs: list[int] = []
def check(exit: fx.Exit[str, object]):
extra_runs.append(sum(n - 1 for n in (*model_calls.values(), *lookups.values())))
model_calls.clear()
lookups.clear()
return fx.succeed(None if exit == fx.exit.Success("Pack light.") else f"{exit}")
trip = Trip(cities=["Lisbon", "Oslo", "Kyoto"])
sweep = explore.activity_crashes(Planner, trip, layer=PlannerLive, check=check)
report = fx.run_blocking(sweep.or_die())
for point, extra in zip(report.points[:4], extra_runs[1:5], strict=True):
print(f"{point}: {extra} step(s) ran again")
stored = [extra for point, extra in zip(report.points, extra_runs[1:], strict=True) if point.stored]
print(len(report.points), "crash points; after a stored step,", sum(stored), "steps ran again")A crash after a step's result was stored repeats nothing. A crash after a step ran but before its result was stored repeats that one step: activities run at least once. The tool ledger closes that last gap for tools, below.
How steps are named#
A replay finds a step's stored result by its name, so the name comes from the step's place in the run, not from a counter that a crash would reset somewhere else:
pyfect/ai/<n>/modelis the run'sn-th model request, from 1.pyfect/ai/<n>/tool/<i>is thei-th tool call in the response to requestn.pyfect/ai/handler/<k>is a tool call no response of the run made, such asWithHandler.handlecalled directly.
The numbers follow the order the run makes its requests, which a replay repeats. Tool calls of one response can run at the same time, since each is named by its position in the response. Model requests made concurrently from several fibers of one run cannot: their order must be the same on every replay.
A request made inside an activity, such as a sub-agent in a tool's handler, is not made an activity again. The activity around it already stores its result.
What is stored#
Each step stores its output and a SHA-256 hash of its request. A model request's hash covers the prompt, the tools offered, the tool choice, the response format, and whether it was streamed. A tool call's hash covers the tool's name and the parameters the model sent. The prompt itself is not stored, because the workflow rebuilds it on every replay from the earlier steps' outputs.
So a run's history grows by each turn's output, not by the conversation so far. In a 100-turn run on SQLite, turn 100 adds as many bytes as turn 10 did. Storing each request's prompt would make the history grow with the square of the turns.
When a replay asks something else#
Activities are found by name. If the workflow's code changed under a running execution, say a new system prompt was deployed, the replayed step has the old name and a new request. Its stored result answers the old request.
On replay, each step compares its request's hash with the stored one. A difference dies with
durable.RequestDiverged, naming the step and both hashes, and the model is not called. It
is a defect rather than a typed failure because nothing in the workflow can fix it: the code
and the history disagree. Annotate the workflow with workflow.SuspendOnFailure to keep
such an execution resumable once the old code is back.
The hashes live in the stored value, not in the workflow engine. That way they work on every
engine (workflow_engine.layer_memory, the cluster engine on any SQL database) without
changing what the engine stores. They also cover only what the layer can hash: a request it
built. A plain activity has no request to hash.
Streaming#
A streamed request is one activity too. The layer reads the provider's stream to its end, stores the parts, and gives the caller all of them as one chunk. It does this on the first run and on every replay, so a consumer never sees a part twice when a crash cuts a stream short. The text still arrives, just not token by token. Stream outside the workflow if you need tokens as they come.
Budgets and the tool ledger#
A budget made in the workflow's body, agent.pipe(budget.limit(...)),
starts fresh on every replay. Every step spends it again, replayed or not, at the usage the
first run recorded. So a resumed run stops at the same request a run without a crash stops
at. Skipping replayed steps would let a crashed run spend its budget twice over. A budget
provided from outside the workflow outlives replays, so replayed steps spend it again: make
the budget in the body.
Tools guarded by the tool ledger compose with the layer. The ledger runs inside the tool's activity, so a call whose activity ran but was not stored is answered from the ledger when it runs again, and its handler does not run twice.
Testing it#
explore.activity_crashes (Exploring schedules and crashes) stops
the run after every step and resumes it, as above. For a long run, at= and stored= split
the sweep into one test per step.