Skip to content

Events & Cancellation

Events observe a running turn. Cancellation stops it cooperatively. Together they are the host application’s basic control plane for agent UIs.

Events report what the loop is doing without changing the prompt or model messages. Use them for progress UI, logs, telemetry, and debugging.

Common events include:

EventMeaningTypical payload
thinkingThe model is thinking or reasoning, where surfaced by the runtimetext chunk
statusInformational progress such as retry or steering updatesmessage
tokenStreaming token or text chunk, when supportedtoken text
tool_call_startA tool is about to executetool name, arguments
tool_resultA tool returned a result or error stringtool name, result
messages_updatedThe in-memory message array changedmessages or update metadata
compaction_start / compaction_complete / compaction_failedContext compaction lifecycledropped count, summary length, or failure reason
doneThe turn completed normallyresponse, messages
errorA guardrail denied or another loop error occurredmessage or reason
cancelledCancellation was observediteration or cancellation metadata

Event names are runtime-shaped. TypeScript and Python callbacks receive snake_case event strings and data dictionaries. C# callbacks receive AgentEventType enum values such as ToolCallStart and MessagesUpdated. Rust callbacks receive a single AgentEvent enum value.

Event callbacks should be fast. They should not block the loop or perform heavy UI work inline; enqueue work to your UI/event system instead.

Do not use events to enforce policy or mutate the loop. Use guardrails for policy, cancellation for stop buttons, and steering for model-visible guidance on a future iteration.

Cancellation is cooperative. The loop checks for cancellation:

  • at the top of each iteration;
  • before the LLM call;
  • during retry backoff where supported.

Cancellation does not forcibly kill a tool or provider call that is already inside code the runtime cannot interrupt. It prevents the next safe step from continuing.

from prompty.core import CancellationToken
token = CancellationToken()
result = turn(
agent,
inputs,
tools=tools,
cancel=token,
on_event=lambda event_type, data: print(event_type, data),
)
# From a stop button, timer, or another thread:
token.cancel()

For chat UIs, wire events to:

  1. show status while the model is thinking;
  2. show each tool call and result;
  3. stream tokens when available;
  4. enable a stop button through cancellation;
  5. record the final messages array if you want to continue the thread.