Keep a chat's history valid when a turn is cancelled or fails, and finish the turn later with resume.
A chat records a turn when the call succeeds, as Effect's Chat
does. When a turn is cancelled or fails half way, nothing is recorded, so the results of
tools that already ran are lost. A streamed turn keeps the parts it streamed, which can
leave a tool call with no result, and providers reject a history like that on every later
request.
chat.interrupt_safe(session) gives back the same chat (same history, same lock, same
saves) with turns that are recorded however they end. A turn that is interrupted or fails
adds:
- the user's prompt;
- the model's output that arrived: its text, and the tool calls it made;
- each of those tool calls with its result, if the handler finished, or with an
execution-interruptedresult, if it did not.
So every tool call has exactly one result, and the next request is valid for Anthropic,
OpenAI's Responses API and Chat Completions alike. A turn that finishes is recorded
exactly as a plain chat records it. Calls the application answers itself are left as a
finished turn leaves them: calls to execution="client" tools, calls waiting for
approval, and calls made with disable_tool_call_resolution=True. A provider-executed
call that has no result is dropped, because only the provider can answer it.
generate_text, generate_object and stream_text all work this way. The partial turn is
written in the call's finalizer, before a persisted chat saves, so chat.Persistence,
export_json and chat.from_json keep it like any other turn: wrap a chat from
get_or_create or from_json in interrupt_safe to get the same behaviour back.
Finishing a turn with resume#
session.resume(toolkit=...) runs again the calls of the last turn that ended with an
execution-interrupted result, and puts their results in place. Results that finished
are kept and not run again. It returns the new results, and does nothing when there is
nothing to finish. A call that needs approval gets its approval request instead. If
resume is cut short too, the results that finished are kept again.
A handler can finish just before the turn is cut short, but too late for the chat to see
its result. Running that call again would do its work twice. Pass a toolkit behind
tool_ledger.guard to both the turn and resume: the ledger
answers a call that ran with the result it recorded, and a call that started but has no
recorded result runs again only if its tool is Idempotent or Readonly. Any other tool
gets a ToolOutcomeUnknown instead. Together, a resumed turn runs no tool twice and loses
no result that finished.
from typing import TypedDict
import pyfect as fx
from pyfect import schema as S
from pyfect import stream
from pyfect.ai import chat, language_model, prompt, tool, tool_ledger, toolkit
from pyfect.ai.language_model import LanguageModel, ProviderOptions
class City(TypedDict):
city: str
# A lookup is safe to run again, so the ledger lets a call cut short run on resume.
Weather = tool.make("Weather", parameters=S.Struct(City), success=S.String).annotate(
tool.Readonly, True
)
Tools = toolkit.make(Weather)
ran: list[str] = []
slow = {"Oslo"} # Oslo's lookup hangs until the first turn is cancelled
def look_up(params: City) -> fx.Effect[str]:
city = params["city"]
done = fx.sync(lambda: ran.append(city)).as_(f"sunny in {city}")
return fx.suspend(lambda: fx.never if city in slow else done)
WeatherLive = Tools.to_layer(Weather.handler(lambda params, _ctx: look_up(params)))
Guarded = tool_ledger.guard(Tools, on_unknown="tell_model")
# A scripted model that asks for two lookups.
def answer(_options: ProviderOptions):
usage = {"inputTokens": {"total": 9}, "outputTokens": {"total": 4}}
return fx.succeed(
[
{"type": "text", "text": "Checking both."},
{"type": "tool-call", "id": "w1", "name": "Weather", "params": {"city": "Rome"}},
{"type": "tool-call", "id": "w2", "name": "Weather", "params": {"city": "Oslo"}},
{"type": "finish", "reason": "tool-calls", "usage": usage},
]
)
Scripted = fx.layer.effect(
LanguageModel, language_model.make(generate_text=answer, stream_text=lambda _: stream.empty)
)
def show(history: prompt.Prompt) -> None:
for message in history.content:
if isinstance(message, prompt.ToolMessage):
for part in message.content:
if isinstance(part, prompt.ToolResultPart):
print(" ", part.id, part.result)
else:
print(message.role)
@fx.fn
def program():
session = chat.interrupt_safe((yield from chat.empty))
turn = yield from session.generate_text("Weather in Rome and Oslo?", toolkit=Guarded).fork()
for _ in range(20):
yield from fx.yield_now()
yield from turn.interrupt() # the user cancels while Oslo is still running
print("after the cancel:")
show((yield from session.history.get()))
slow.clear()
yield from session.resume(toolkit=Guarded)
print("after resume:")
show((yield from session.history.get()))
fx.run_blocking(
program()
.pipe(fx.provide(tool_ledger.layer_memory))
.pipe(fx.provide(WeatherLive))
.pipe(fx.provide(Scripted))
.or_die()
)
# Rome ran once: its result was kept, and resume ran only Oslo.
assert ran == ["Rome", "Oslo"]When the turn fails before the model answers#
If the request fails or is cancelled before the model answers, the turn adds only the
user's prompt, as a chat app keeps a message whose reply never came. Retrying that call
with .retry(...) sends the prompt again, so it then appears twice. To ask again, call
session.generate_text([], ...) with no new message: the prompt is already in the
history.