---
title: 'AgentAssert: Contract Enforcement for AI Agents'
url: https://www.emergentmind.com/topics/agentassert
type: topic
---

# AgentAssert: Contract Enforcement for AI Agents

AgentAssert is the reference implementation of the Agent Behavioral Contracts (ABC) framework, providing formal, runtime-enforceable behavioral guarantees for autonomous AI agents. It instantiates Design-by-Contract principles for agentic AI, enabling the specification of preconditions, invariants, governance policies, and structured recoveries as first-class artifacts. AgentAssert operationalizes ABC via a modular Python library with low-latency runtime enforcement, supporting rigorous probabilistic satisfaction guarantees, behavioral drift bounding, multi-agent contract composition, and empirical benchmarking.

## 1. Formal Structure: Agent Behavioral Contracts

At the core of AgentAssert is the ABC contract structure, defined as a 4-tuple $C = (P, I, G, R)$. Each component is a first-class, runtime-enforceable artifact:

- **Preconditions ($P$):** Finite set of predicates $p_1, ..., p_m$ over the initial agent state $s_0$ required to hold before execution (e.g., "user identity verified").
- **Invariants ($I$):** Partitioned into:
    - **Hard invariants ($I_{\mathrm{hard}}$):** Safety-critical properties that must be maintained at every step (e.g., "no PII is emitted," "no unauthorized trades").
    - **Soft invariants ($I_{\mathrm{soft}}$):** Desirable but recoverable properties (e.g., "response tone remains professional"), requiring restoration within $k$ steps.
- **Governance Constraints ($G$):** Predicates over agent actions $a_t$, split into:
    - **Hard governance ($G_{\mathrm{hard}}$):** Zero-tolerance constraints (e.g., "no forbidden API calls").
    - **Soft governance ($G_{\mathrm{soft}}$):** Advisory constraints (e.g., cost warnings).
- **Recovery Mechanism ($R$):** Partial function $R: (I_{\mathrm{soft}} \cup G_{\mathrm{soft}}) \times S \rightharpoonup A^*$, where, for a violated soft constraint $c$ and state $s_t$, it yields a bounded sequence of corrective actions to reestablish compliance. Failure to recover triggers a RecoveryFailed event.

In this framework, hard constraints operationalize safety ("nothing bad ever happens"), while soft constraints with bounded recovery provide liveness guarantees ("something good happens within $k$ steps").

## 2. Probabilistic Satisfaction and Compliance Guarantees

AgentAssert extends contract satisfaction to stochastic, non-deterministic agents via $(p, \delta, k)$-satisfaction:

Let $C_{\mathrm{hard}}(t) \in [0,1]$ and $C_{\mathrm{soft}}(t) \in [0,1]$ denote the fraction of hard and soft constraints satisfied at step $t$, for a session of length $T$. An agent $A$ $(p, \delta, k)$-satisfies contract $C$ (notation: $A \models_{p,\delta,k} C$) if, with probability at least $p$:

- **Persistent compliance (Hard guarantee):**

  $$
  P\Bigl[\forall t \in [0,T]:\, C_{\mathrm{hard}}(t) = 1 \;\big|\, P(s_0)\Bigr] \geq p.
  $$

- **Recoverable compliance (Soft guarantee):**
  
  $$
  P\Bigl[\forall t \in [0,T]:\, C_{\mathrm{soft}}(t) < 1-\delta \implies \exists\, t' \in [t, \min(t+k, T)]:\, C_{\mathrm{soft}}(t') \geq 1-\delta \;\big|\, P(s_0)\Bigr] \geq p.
  $$

Here, $\delta \in [0,1]$ bounds tolerable simultaneous soft constraint failures, and $k$ specifies the recovery horizon. These principles correspond to probabilistic computation tree logic (PCTL) statements for safety and liveness under stochastic policy execution.

## 3. Behavioral Drift: Modeling and Theoretical Limits

AgentAssert incorporates behavioral drift modeling to quantify agent deviations from contract compliance. Drift $D(t)$ is modeled as an Ornstein–Uhlenbeck process:

$$
dD(t) = \bigl(\alpha - \gamma D(t)\bigr) dt + \sigma dW(t),
$$

where:
- $\alpha > 0$: natural drift rate (uncontrolled agent divergence),
- $\gamma > 0$: recovery strength (contract enforcement efficacy),
- $\sigma > 0$: process noise amplitude,
- $W(t)$: standard Wiener process.

The Drift Bounds Theorem establishes:

- **Stationary drift:** $D(\infty) \sim \mathcal{N}(\alpha/\gamma,\, \sigma^2/2\gamma)$,
- **Mean drift bound:** $E[D] = \alpha/\gamma$ (enforcement cap),
- **Variance:** $\operatorname{Var}(D) = \sigma^2/2\gamma$,
- **Tail bound:** $P(D > \alpha/\gamma + \eta) \leq \exp(-\gamma \eta^2 / \sigma^2)$,
- **Exponential convergence:** $E[(D(t)-\alpha/\gamma)^2] = (D_0-\alpha/\gamma)^2 e^{-2\gamma t} + \frac{\sigma^2}{2\gamma}(1-e^{-2\gamma t})$,
- **Contract design criterion:** For drift below $D_{\max}$ with probability $\geq 1-\epsilon$, select
  $$
  \gamma \text{ as the larger root of } D_{\max}^2 \gamma^2 - (2\alpha D_{\max} + \sigma^2 \ln(1/\epsilon)) \gamma + \alpha^2 = 0,
  $$
  with the low-noise limit $\gamma \gtrsim \alpha / D_{\max} + (\sigma \sqrt{2 \ln(1/\epsilon)}) / (2 D_{\max})$.

This formalization enables engineering behavioral contracts with explicit drift and recovery guarantees [2602.22302].

## 4. Contract Composition in Multi-Agent Chains

AgentAssert supports composition of ABCs for multi-agent deployments, with the following guarantees:

- **Serial composition:** Given contracts $C_A$, $C_B$ for agents $A$, $B$, and handoff invariant $I_{\mathrm{handoff}}$, serial composition $C_{A \oplus B}$ is well-formed if:
    - Interface compatibility: $\mathrm{Type}(\mathrm{Post}_A) \subseteq \mathrm{Type}(P_B)$,
    - Assumption discharge: $\mathrm{Post}_A \wedge I_{\mathrm{handoff}} \implies P_B$,
    - Governance consistency: allowed actions of $G_A$ do not conflict with prohibitions in $G_B$,
    - Recovery independence: $R_A$ preserves $P_B$.
- **Probabilistic degradation:** If agent $A$ is $(p_A,\delta_A)$-satisfying and $B$ is $(p_B,\delta_B)$-satisfying, the composed chain $(p_{A\oplus B},\delta_{A\oplus B})$-satisfies its composed contract with:
  $$
  p_{A\oplus B} \geq p_A p_B p_h, \qquad \delta_{A\oplus B} \leq \delta_A + \delta_B + \delta_h,
  $$
  where $p_h, \delta_h$ are success and drift parameters for the handoff.

For $N$-agent chains, $p_{\mathrm{chain}} \geq \prod_{i=1}^{N} p_i \prod_{i=1}^{N-1} p_{h_i}$ and $\delta_{\mathrm{chain}} \leq \sum_{i=1}^{N} \delta_i + \sum_{i=1}^{N-1} \delta_{h_i}$. This formalizes multi-agent reliability under ABC/AgentAssert [2602.22302].

## 5. AgentAssert Architecture and API

AgentAssert is a modular Python library with overhead $<$10 ms per action, designed for practical integration and extensibility. The key layers include:

- **Parser & Validator:** Loads ContractSpec YAML contracts, validates schema consistency.
- **Constraint Evaluator:** Checks $P, I_{\mathrm{hard}}, I_{\mathrm{soft}}, G_{\mathrm{hard}}, G_{\mathrm{soft}}$ predicates against agent state/action; computes $C_{\mathrm{hard}}(t)$, $C_{\mathrm{soft}}(t)$.
- **Metric Tracker:** Maintains JSD-based drift $D(t)$, compliance time series, recovery logs, and stress resilience index $S$.
- **Runtime Monitor:** Orchestrates enforcement per agent turn—evaluates constraints; updates drift and compliance; emits violation/drift events; handles recovery via $R$ if needed; resets state on re-satisfaction.
- **Recovery Executor:** Dispatches corrective actions per a taxonomy (LLM re-prompt, tool call, human escalation).
- **Integration Hooks:** Framework-agnostic adapters for LangChain, AutoGen, and custom agent infrastructure.
- **Benchmark Runner:** Supports evaluation on synthetic AgentContract-Bench and live agent sessions.

**Example API usage (pseudocode):**
```python
from agentassert import Contract, SessionMonitor

# Load contract specification
contract = Contract.load("financial-advisor.yaml")

# Create a session monitor for an agent loop
monitor = SessionMonitor(contract)

# Inside agent’s turn loop:
for turn in range(max_turns):
    state = agent.get_state()
    action = agent.call_llm(state)

    # Enforce contract
    report = monitor.enforce(state, action)

    # If recovery suggested, apply corrective action
    if report.soft_violations:
        action = agent.call_llm(report.recovery_prompt)

    agent.accept(action)
```
Under typical enterprise contracts ($k \approx 50$ constraints, $|A| \approx 30$ action types), the total overhead is 5–10 ms per action, much less than LLM inference latency (200–2000 ms) [2602.22302].

## 6. Benchmarking and Empirical Results

AgentAssert is evaluated on AgentContract-Bench, comprising 200 scenarios across five domains, 50 governance stress profiles, and 50 composition cases. Each scenario consists of a 5–8 step trace with ground-truth violation annotations.

| Metric                    | Value/Range                              | Notes                                             |
|---------------------------|------------------------------------------|---------------------------------------------------|
| Detection Accuracy        | 1.0000 (all scenarios)                   | All annotated violations flagged                  |
| Hard Compliance ($C_{\mathrm{hard}}$) | $0.96$–$0.98$ (domains), $0.95$ (stress), $0.86$ (composition) | Safety-critical constraint adherence              |
| Soft Compliance ($C_{\mathrm{soft}}$) | $0.93$–$0.97$ (domains), $0.75$ (composition)      | Liveness property adherence                       |
| Mean Drift ($\bar{D}$)    | $0.027$–$0.054$ (domains), $0.184$ (composition) | Behavioral divergence measure                     |
| Reliability Index ($\Theta$) | $0.967$–$0.985$ (domains), $0.887$ (composition) | Composite performance score (Def. 3.12)           |
| Overhead                  | $<$10 ms/action                          | $k \leq 100$ constraints                          |

In 1,980 live E1 sessions across seven LLM models and six vendors, contracted agents surface 5.2–6.8 soft violations/session vs. 0.0–0.3/session (uncontracted), with $p < 0.0001$ (Welch's $t$-test, Bonferroni correction), $d=6.7$–$33.8$, and power $>0.99$. Hard constraint compliance under stress is 88–100%; behavioral drift is bounded to $D^* < 0.27$; 100% recovery is observed for frontier models ($\gamma > \alpha$), and 17–100% across all models, all at sub-10 ms enforcement overhead [2602.22302].

## 7. Significance and Applications

AgentAssert enables practitioners to specify, enforce, and monitor behavioral properties of autonomous agents with millisecond-level runtime checks, using formal YAML contracts and integration with popular LLM agent frameworks. The provision of probabilistic compliance guarantees and empirical drift bounding supports reliable agentic deployments under uncertainty and across composed workflows. As empirical results on AgentContract-Bench and live LLM deployments show, AgentAssert provides effective detection, high compliance, bounded behavioral drift, and robust recovery, addressing key governance and control gaps in agentic AI systems [2602.22302].

Source: https://www.emergentmind.com/topics/agentassert