# Composable Termination Conditions

> Express agent stop criteria as small single-purpose conditions composed with AND/OR into one explicit termination contract instead of ad-hoc loop g...

- **Category**: Agentic AI
- **Subcategory**: Safety & Control
- **Canonical URL**: https://designpattern.fyi/patterns/composable_termination_conditions/

---

## Description
**Intent**: Express agent stop criteria as small single-purpose conditions composed with AND/OR into one explicit termination contract instead of ad-hoc loop guards.
**Context**: An agent or orchestrator loops over model calls, tool invocations, and message exchanges until something tells it to stop. The realistic stop criteria are heterogeneous: a max number of messages, a token budget, a phrase the model emitted, a particular tool call (e.g. submit_final), a handoff to another agent, a timeout, an external operator signal, or a user cancellation.
**Solution**: Define a small set of primitive termination conditions: MaxMessages, TokenBudget, TextMention, FunctionCall, Handoff, Timeout, ExternalSignal, Cancellation. Each implements a single method `is_terminated(state) -> bool, reason`. Define a Composite that combines conditions with `any` (OR) or `all` (AND) semantics. The orchestrator loop consults the composite once per step. The trip cause (which leaf condition fired) is logged with the termination event.


## Use Cases
- An agent loop must combine multiple heterogeneous stop criteria.
- Operators need structured trip-cause for postmortem.
- External signals (cancellation, kill-switch) need to share termination semantics with intrinsic stops.





## Trade-offs


### Advantages

- Stop criteria are testable in isolation.

- AND/OR composition reads as a single contract per loop.

- External operator signals are expressible as conditions, unifying termination paths.

- Trip cause is structured for postmortem.




### Considerations & Drawbacks

- An expressive DSL invites complex compositions that surprise on edge cases.

- Polling-based conditions (timeout, external signal) need a clock the loop trusts.







---
**Reference**: [Original Source](https://www.agentpatternscatalog.org/patterns/composable-termination-conditions/)

