# External Stops and Cancellation — Agent Loops, Stop Conditions and Token Budgets

Source: https://www.geekswithgeeks.com/en/agent-loops/stop-external

> Let users and systems cancel a running loop cleanly.

## Check a flag between steps

Users press Cancel, servers shut down, and parent jobs time out. The loop should check a **cancellation flag** at a safe point between turns, not in the middle of writing a file. When set, it stops, saves its state and reports "cancelled" rather than failing mysteriously.

## A cancellation event

`threading.Event` is a thread-safe flag. Another thread (a request handler, a signal handler) calls `cancel.set()`.

```python
import threading
cancel = threading.Event()

for step in range(max_steps):
    if cancel.is_set():
        save_state(messages)
        return {"status": "cancelled", "step": step}
    ...  # call, inspect, act, append
```

**Quiz:** Where is the safest place to check a cancel flag?

- [ ] In the middle of a file write
- [x] Between turns, at a safe point
- [ ] Never
- [ ] Only after the process exits

*Answer:* Between turns, at a safe point. Checking between turns avoids leaving half-finished side effects.
