Skip to content

Declarative Middleware

Middleware intercepts the agent message stream: it compacts context, detects loops, enforces budgets, caches prompts, and more. The middleware: key sets which middleware runs, in what order, and with what config.

Inheritance

abt.yaml config.middleware → abt.yaml agents.<name>.config.middleware → agent frontmatter middleware:

agents.<name>.config is the one scoped override tier in abt.yaml, keyed by the dispatch-time agent name. See Project schema.

Each layer inherits from the one above and overrides entries by name. A same-named entry at a lower layer deep-merges onto the inherited config: fields you set win, and unset fields keep the inherited value. New entries are appended. enabled: false removes an entry from the stack. So you declare only what you change at each level. The agents.<name> tier merges onto the project stack; it does not replace it.

Merged entries keep the position the inherited layer gave them, and abt then orders the merged stack by the ordering constraints.

Subagents

Every agent runs the guardrails declared for it, with counters of its own: model_call_limit, tool_call_limit, token_budget, loop_detection and run_timeout start fresh on each call to a subagent, including parallel calls to the same one. The limits are therefore per call, not a cap across calls: repeated delegation multiplies them, and tool_call_limit: {task: N} bounds the number of delegations. A task subagent from subagents: resolves them from its own layers above. The built-in general-purpose subagent has no layers of its own, so it runs its delegating agent's declared middleware, except rubric, todo_list and code_interpreter.

Full example

# abt.yaml: project defaults
config:
  middleware:
    - tool_retry:
        max_retries: 2
    - compaction:
        trigger: 170_000
    - token_budget:
        max_total_tokens: 500000
    - loop_detection:
        warn_threshold: 5
        critical_threshold: 10

# tighter loop detection and a bigger budget, for db-investigator only
agents:
  db-investigator:
    config:
      middleware:
        - loop_detection:
            warn_threshold: 3
            critical_threshold: 6
        - token_budget:
            max_total_tokens: 800000

In the frontmatter of agents/db-investigator.md, add this to disable compaction and add a rubric:

middleware:
  - compaction:
      enabled: false
  - rubric:
      max_iterations: 5

Resolved stack for db-investigator:

Middleware Source
tool_retry inherited from abt.yaml
token_budget (800k) project entry, overridden by abt.yaml agents.db-investigator.config
loop_detection (warn=3, critical=6) project entry, overridden by abt.yaml agents.db-investigator.config
rubric (max_iterations=5) added by agent frontmatter
~~compaction~~ disabled by agent frontmatter (enabled: false)

enabled: false removes the middleware from the resolved stack entirely, including declarations from higher layers.

YAML syntax

Each entry is a single-key mapping with nested config, such as - tool_retry: {max_retries: 3} or - loop_detection: {warn_threshold: 5}.

Every middleware is disabled unless you declare it in the middleware: list. The exception is prompt caching (Anthropic and Bedrock), which is wired into the tail stack and does nothing for other providers. A middleware with no config, such as todo_list, can be a bare string (- todo_list) in agent frontmatter and in abt.yaml.

Jinja {{ var('name') }} works in config values. Rendered strings are coerced to int, float, or bool when they are numeric or "true"/"false":

middleware:
  - loop_detection:
      warn_threshold: "{{ var('loop_warn') }}"  # "4" → 4

Where to declare

  • Agent frontmatter has the highest priority.
  • abt.yaml agents.<name>.config.middleware applies to one dispatch-time agent, unless its frontmatter overrides it.
  • abt.yaml config.middleware sets the project-wide default.
  • Framework defaults. Agents start with steering, except workflow agents that run after another agent; set enabled: false on it in any layer to remove it. Declare tool_retry to get retries. Once declared, its defaults are max_retries: 2, backoff_factor: 2.0, and initial_delay: 1.0.

Available middleware

Name Purpose
tool_retry Retry failed tool calls with exponential backoff. Only declare it for idempotent tools, because the tool re-runs.
model_retry Retry failed model calls with exponential backoff
collapse (experimental) Collapse sequential tool-call groups to reduce message count
compaction (experimental) Summarize older messages when context approaches limits
progress_tracker Terminate stagnant agents that stop making progress
code_interpreter (experimental) Sandboxed code execution tool
model_call_limit Cap total model invocations per run
model_rate_limit Cap model calls per minute across every worker that shares a Redis
tool_call_limit Cap calls to specific tools per run
token_budget Cap cumulative input and output tokens per run
loop_detection Detect and break stuck tool-call loops
run_timeout Graceful wall-clock timeout with synthesis
rubric Self-evaluation against a rubric after each turn
todo_list Gives the agent a write_todos tool to plan and track a visible todo list
steering On by default: delivers messages sent while the agent runs. See steering

steering

A message sent to a conversation while its agent works reaches the agent at its next model call, as a user message, instead of waiting for the run to finish. A task subagent reads it too, and starts with it only when its parent does (unless the subagent declares steering itself). Agents have it by default; turn it off for one that must never be interrupted:

middleware:
  - steering:
      enabled: false

In a workflow, the first stage reads messages and every agent that runs after another agent (a formatter, a follow-up step) starts without steering. A message meant for the earlier work is then not answered by the step that only formats it. abt config show has no workflow context and lists the default. Declare steering on a later agent to let it read messages too (a declaration in abt.yaml applies to every stage):

middleware:
  - steering

A message the run ended without reading runs as its own turn. The chat API served by abt docs serve answers 202 with {"status": "steered"} and reports an unread one on the stream as steer_undelivered. abt watch hands a Slack thread reply to the run in flight, also through produce and consume. A custom producer calls abt.contracts.steer(thread_id, SteeringMessage(text, on_undelivered=...)).

Ordering constraints

abt orders the stack for you. Declare the entries you want in any order; each agent runs them sorted by these constraints:

  • steering runs before collapse, compaction, model_call_limit, token_budget, loop_detection, rubric
  • collapse runs before compaction, loop_detection, token_budget, rubric
  • compaction runs before loop_detection, token_budget, rubric
  • model_call_limit runs before loop_detection
  • model_rate_limit runs after model_retry, so each retry takes its own slot
  • token_budget runs before loop_detection
  • loop_detection runs after collapse, compaction, model_call_limit, token_budget
  • rubric runs after collapse, compaction, loop_detection, token_budget

Among the entries that can run next, the one you declared first goes first, so entries with no constraint between them keep your order. abt config show --agent <name> --middleware prints the resolved order.

middleware:
  - loop_detection: {}
  - token_budget: {max_total_tokens: 100000}
  - compaction: {trigger: 3000}

runs as compaction, token_budget, loop_detection.

abt compile fails with E_MIDDLEWARE_ORDERING only when project-local or third-party constraints contradict each other in an agent's merged stack (project defaults, then agents.<name> overrides, then agent overrides, with disabled entries removed):

ERROR: Agent 'a': middleware ordering conflict: constraints cannot all be satisfied among first, second

Project-local middleware

Create custom middleware in middlewares/ at the project root, the same way as tools/:

# middlewares/rate_limiter.py
from langchain.agents.middleware import AgentMiddleware

from abt.middleware import middleware


@middleware("rate_limiter")
class RateLimiterMiddleware(AgentMiddleware):
    def __init__(self, config: dict, ctx):
        self.max_rpm = config.get("max_rpm", 60)

    async def abefore_model(self, state, runtime):
        # rate limiting logic
        return None
middleware:
  - rate_limiter:
      max_rpm: 30
  - loop_detection: {}

abt compile rejects unknown middleware names and lists the available ones, project-local included. It also rejects unknown keys, wrong types, and out-of-range values in builtin config, and names the key. Register project and third-party middleware with config_model= (a pydantic model) for full validation. Values containing {{ ... }} render at run time, so only their keys are checked at compile.

Third-party middleware

A package that registers under the abt.middleware entry point is discovered the same way as a project-local file. The entry-point setup and wrap_middleware are in Extending abt.

Pass build= to wrap_middleware when the class needs something from FactoryContext, such as the resolved model through ctx.get_model, rather than only its declared config.

Configuration reference

Keys and defaults for each built-in middleware follow. Where a guide lists the full keys, the entry links to it.

tool_retry

Retry failed tool calls with exponential backoff.

Key Default Description
max_retries 2 Max retry attempts per tool call
backoff_factor 2.0 Multiplier for exponential backoff
initial_delay 1.0 Initial delay in seconds
on_failure continue After all retries: continue (return the error to the model) or error (raise)

The final error gets the same formatting as any tool error (root cause of an ExceptionGroup, HTTP status classification, credential redaction), with either on_failure.

An agent with confirmation-gated tools (confirmation_required: true) drops tool_retry and logs a warning, because a retry would re-execute an approved call without asking again. Set - tool_retry: {enabled: false} on such agents to make that explicit.

model_retry

Retries failed model calls (rate limits, transient network errors) with exponential backoff. Like every entry on this page, it runs only when declared. It works at the model-call level, on top of the run-level stream retry, which always runs.

Its keys match tool_retry: max_retries (2), backoff_factor (2.0), initial_delay (1.0), and on_failure (continue). It adds max_delay (60.0), the cap on any single delay.

model_rate_limit

Caps model calls per minute across every worker that shares one provider quota. Provider SDKs back off per client, so many workers on one quota still throttle each other. This entry admits at most requests_per_minute calls per scope fleet-wide, from a counter in Redis, and holds the rest until the next one-minute window. A window admits up to the limit at once when it opens.

config:
  middleware:
    - model_retry
    - model_rate_limit:
        requests_per_minute: 600
Key Default Meaning
requests_per_minute required Calls admitted per scope per minute
scope the agent's model id Calls with the same scope share one limit. Set one scope on agents that use different models under one quota
max_wait_seconds 120 A call that gets no slot in this time is sent anyway and left to the provider's own backoff
redis_url_env ABT_WATCH_QUEUE Env var holding the Redis URL. Needs the queue extra

abt watch consume --queue URL does not set ABT_WATCH_QUEUE. Export it in the pod, or point redis_url_env at a variable that holds the URL.

It needs Redis 7.0 or newer, like the watch queue. With no Redis URL, or with Redis unreachable, the call goes through and abt logs a warning once, so the same agent files run unchanged on a laptop. After a failure, calls skip Redis for 30 seconds before trying it again. It must come after model_retry in the list, so each retry takes its own slot. It limits requests, not tokens. Waits show up as the abt.model.rate_limit.waited counter and abt.model.rate_limit.wait_seconds histogram when observability is on.

collapse (experimental)

Collapses sequential tool-call groups to reduce message count. Experimental: it needs the collapse extra and its API may change. Keys and defaults: Collapse reference and the Message collapse guide.

compaction (experimental)

Summarizes older messages when context approaches window limits, and can shorten large tool-call arguments and clear stale tool results first. Experimental: its keys may change. The Context compaction guide covers examples, per-agent overrides and where summarized history goes.

Key Default Description
trigger 170000 Absolute accumulated-token count that triggers compaction
keep_messages 20 Recent messages kept uncompacted
model_id (agent model) Override model for summarization
clear_tool_results enabled: false, trigger: 100000, keep_recent: 5, exclude_tools: [] Replaces old tool results (except those of exclude_tools) with a placeholder once trigger tokens accumulate (no model call)
truncate_args enabled: true, max_length: 2000, trigger unset (off) Shortens large write_file / edit_file arguments in older turns once trigger is reached
custom_instructions (none) Custom summarization instructions
enable_manual_tool false Exposes a compact_conversation tool to the agent

progress_tracker

Terminates stagnant agents that stop making progress.

Key Default Description
warmup_calls 10 Model calls before tracking starts
check_interval 5 Check every N model calls
min_progress_rate 0.3 Minimum progress rate (0.0–1.0) to avoid termination

Only the current turn counts. Earlier turns of a checkpointed thread are excluded from warmup_calls and the progress rate.

code_interpreter (experimental)

Sandboxed JavaScript (QuickJS) execution tool. Experimental. Every key, with defaults: Code interpreter guide, configuration reference.

- code_interpreter:
    timeout: 30
    max_result_chars: 5000

model_call_limit

Caps total model invocations per run.

Key Default Description
max_model_calls (none) Max model calls per run
grace_turn false On limit, nudge for one final real turn instead of ending immediately

When the limit ends the run and a synthesis_model is configured, that model writes the answer from the thread; otherwise the answer is empty and the run is reported as stopped.

- model_call_limit:
    max_model_calls: 50
    grace_turn: true

max_model_calls sets a floor on recursion_limit. Each model round-trip costs several graph steps, and every middleware with a before_model or after_model hook adds one. The example above fails abt compile at the default recursion_limit of 150, with Set recursion_limit >= 160, or lower max_model_calls. Raise recursion_limit under config: or in the agent's frontmatter. The step-counting rules are in Loop detection.

By default, hitting max_model_calls ends the run at once with a canned message and output: null. A structured output a caller waits for, such as a task-tool dispatch, is lost.

With grace_turn: true, the first hit injects a "wrap up now" nudge (naming the output_schema tool when one is set) and gives the model one real turn. A second hit ends the run normally. That turn costs at most one extra round-trip, so leave recursion_limit headroom.

tool_call_limit

Caps calls to specific tools per run, independent of model_call_limit. The config is a flat {tool_name: max_calls} map with no wrapper key. A key can be written like a tools: entry (<server>__getAlerts): it resolves to the name the MCP tool is bound under (get_alerts). A key no bound tool matches is logged as a warning and never applies. A tool at its limit returns a short-circuited error ToolMessage. Parallel calls in one model step each use a slot. A tool with a limit is not exposed to code_interpreter's ptc, because tools.* calls would skip the limit.

The limit counts the name the model emits. abt normally repairs a misspelled tool name (message_post_slack for slack_post_message) and runs the real tool; for a tool with a limit it does not, so every spelling of the name takes the same slot: the call returns an invalid-tool error and the model retries with the real name.

A call counts once it reaches the tool, whether it returned or raised. Calls served from tool_result_cache, calls the limit blocked, calls interrupted for an approval, and tool_retry re-runs are uncounted. A run that pauses for approval keeps its count when it resumes. Each new turn on the thread starts at zero.

- tool_call_limit:
    atlassian__confluence_search: 8
    montecarlo__runTroubleshootingAgent: 1

token_budget

Caps the input and output tokens an agent may spend. Hitting the budget triggers synthesis.

Key Default Description
max_total_tokens (none) Budget ceiling. Without it, the middleware does nothing.
scope run run: every turn gets the full budget, so a long Slack thread never runs dry. thread: one cap for the whole conversation. Unset falls back to the workflow's token_budget_scope, then abt.yaml, then ABT_TOKEN_BUDGET_SCOPE, then run.
- token_budget:
    max_total_tokens: 500000
    scope: run

To set the default for every agent without editing them, set ABT_TOKEN_BUDGET_SCOPE=thread (or run). A scope: on the middleware wins over the env var. To set it for one workflow, use token_budget_scope:. For a checkpointed thread, see Checkpointing.

loop_detection

Detects and breaks stuck tool-call loops. The detectors, thresholds, handler modes, and reflection and synthesis settings are in the Loop detection guide. The main keys:

Key Default Description
warn_threshold 5 Consecutive similar calls before a warning
critical_threshold 10 Consecutive similar calls before action
on_warning advise advise, terminate, synthesize, reflect, or rollback
on_critical terminate terminate, synthesize, reflect, or rollback
thread_chars_threshold (none) Character count that triggers early thread-size detection when set. A size limit, not a loop: it never uses rollback
detectors (all enabled) Per-detector toggles or overrides
- loop_detection:
    warn_threshold: 5
    critical_threshold: 10
    on_warning: advise
    on_critical: synthesize

run_timeout

Graceful wall-clock timeout with optional synthesis.

Key Default Description
graceful_timeout_seconds (none) Seconds before graceful stop and synthesis
hard_timeout_seconds graceful + 60s Hard asyncio.wait_for kill cap. Derived when omitted.
- run_timeout:
    graceful_timeout_seconds: 120

A tool call still running at the graceful deadline is cancelled and returns an [ABT_RUN_DEADLINE] error, so the model can still write its answer before the hard timeout. Results of the step's other tool calls are kept. A tool's own execution_timeout applies too; the shorter limit wins. A call that starts after the deadline is not cut off by it; set tools.defaults.execution_timeout well below the graceful budget to bound those. Delegation to a subagent is not cut off either: the subagent is bounded by its own run_timeout.

rubric

Self-evaluation against a rubric after each turn. The full key list, defaults, and ranges are in the Rubric middleware guide.

- rubric:
    max_iterations: 3
    grader_model_id: eu.anthropic.claude-sonnet-4-20250514-v1:0

Middleware catalog in docs UI

abt docs generate && abt docs serve includes a Middleware tab. It lists every registered middleware (builtin, project-local, and entry-point) with its config keys, ordering constraints, and source. New middleware appears there without manual docs.