Skip to main content
rb.middleware() returns a ReasonBlocksMiddleware — a langchain.agents.middleware.AgentMiddleware subclass that also acts as a context manager. You attach it to create_agent like any other middleware. It hooks before_agent, before_model, wrap_model_call, and after_agent to score each step, evaluate trajectory monitors server-side, inject steering text into the system message, and (optionally) route the model based on the FSM state.
1

Install

2

Initialize ReasonBlocks

Create one ReasonBlocks per process and call rb.middleware() per run. Each middleware instance is single-use.
The constructor does not auto-read REASONBLOCKS_API_KEY — your code must pass it explicitly. The base_url default is read from REASONBLOCKS_BASE_URL at import time by reasonblocks._settings; if you set that env var before importing reasonblocks, you can omit base_url here.
3

Wrap your agent in the context manager

The recommended pattern is with mw:. The context manager guarantees that the run_finish telemetry event fires on success, exception, or explicit failure marking.
4

Tag runs for the dashboard

Every parameter on rb.middleware() is optional. Anything not consumed by a named field rides along in metadata on the run row.
When your api_key is a per-org rb_live_* key, the API overrides org_id / project_id with the key’s authoritative scope. Leaving them at "default" is fine.
5

Mark explicit failures

If the agent returns normally but the run was logically a failure (wrong answer, tests still failing), call mark_failure(reason=...) before the with block exits. Exceptions that escape the block are recorded automatically as failure: <ExceptionType>.
6

Inspect step_log

mw.step_log is a list[StepLogEntry] populated as the agent runs. Each entry holds the FSM state, difficulty, resolved model id (when routed), monitors that fired, full intervention text, tool calls, tokens, and latency.
Call entry.as_dict() for a JSON-shaped view.

Add CodebaseMemory tools

make_langchain_tools wraps a CodebaseMemory (and optionally an ImportGraph) into @tool-decorated callables. The agent uses them to recall prior findings before re-reading files and to persist new findings during a run.
The factory adds up to three tools:
  • recall_findings — semantic search over prior findings.
  • store_finding — persist a new finding for future runs (hidden when enable_store=False).
  • impact_analysis — blast-radius lookup via ImportGraph (only added when a graph is passed).
ImportGraph.build_from_files requires networkx. Install with pip install networkx.
See Persist agent findings with CodebaseMemory for the underlying API.

Complete example

Each mw is single-use — call rb.middleware(...) again for the next run.