LangChain agent middleware for Cycles — pre-tool-call authorization, fan-out caps, and per-tenant budget enforcement for Python agents using create_agent.
Project description
Cycles for LangChain — AI agent middleware for budget and action authority
LangChain middleware for pre-tool-call authorization, fan-out caps, and per-tenant budget enforcement in create_agent workflows. Provider-neutral: works with any LangChain 1.x agent regardless of model provider, as long as actions flow through LangChain middleware/tool execution.
Built on LangChain's AgentMiddleware API:
wrap_tool_call— tool-call authorization plus optional reserve/commit/release lifecycle around each tool executionbefore_model(with@hook_config(can_jump_to=["end"])) — fan-out caps and external policy halts before another model turn
Model-call reservation via wrap_model_call is on the roadmap but not implemented in v0.1.x. For token-level streaming budget tracking today, use runcycles.stream_reservation directly inside an LLM-spend handler.
Install via pip install langchain-runcycles.
What's in the box
CyclesToolGate— runs before every tool call. Authorizes viaclient.decide()and/or reserves budget viaclient.create_reservation(). Returns aToolMessageon denial so the model can recover gracefully.CyclesFanOutGate— runs before every model turn. Halts the agent (withjump_to: "end") when a turn cap is hit or when an external policy says to stop. Useful for runaway-loop protection and per-tenant burst caps.
Both work with sync or async LangChain agents and the sync (CyclesClient) or async (AsyncCyclesClient) Cycles client.
Installation
pip install langchain-runcycles
Requires Python 3.10+ and langchain >= 1.0.
Quick Start
from langchain.agents import create_agent
from langchain_core.tools import tool
from langchain_runcycles import CyclesToolGate
from runcycles import Action, CyclesClient, CyclesConfig, Subject
@tool
def send_email(to: str, body: str) -> str:
"""Send an email."""
return f"Sent to {to}"
client = CyclesClient(CyclesConfig(base_url="http://localhost:7878", api_key="..."))
gate = CyclesToolGate(
client,
subject=Subject(tenant="acme", agent="researcher"),
action={"send_email": Action(kind="tool.call", name="send_email")},
mode="decide",
)
agent = create_agent(model="claude-sonnet-4-6", tools=[send_email], middleware=[gate])
agent.invoke({"messages": [{"role": "user", "content": "Email alice."}]})
If client.decide() denies the call, send_email is never invoked — the model receives a ToolMessage with the denial reason and can choose another path.
Middleware
CyclesToolGate
Gates each tool call. Three modes:
| Mode | What it does |
|---|---|
"decide" |
Calls client.decide(). Denies the tool call on a non-allow decision. No reservation. |
"reserve" |
Creates a reservation, runs the tool, commits on success / releases on exception. |
"decide+reserve" |
Authorizes via decide(), then reserves+commits. Most strict. |
gate = CyclesToolGate(
client,
subject=Subject(tenant="acme", agent="researcher"),
action={
"search": Action(kind="tool.call", name="search"),
"send_email": Action(kind="tool.call", name="send_email"),
},
mode="decide+reserve",
)
CyclesFanOutGate
Halts the agent when a turn cap or external policy says stop. Optional client argument enables remote policy checks on each turn:
from langchain_runcycles import CyclesFanOutGate
fanout = CyclesFanOutGate(
max_turns=20,
client=client, # optional — for remote policy
subject=Subject(tenant="acme"),
action=Action(kind="model.turn", name="research"),
)
Pair with CyclesToolGate and HumanInTheLoopMiddleware for production-grade agent governance.
Configuration
Subject
Either a static Subject or a callable resolving from request/state:
from runcycles import Subject
# Static
subject = Subject(tenant="acme", agent="bot")
# Per-call extractor (CyclesToolGate: (request, state); CyclesFanOutGate: (state, state))
def per_tenant(request, state):
return Subject(tenant=state["config"]["tenant"], agent="bot")
Action
Static, mapping (per-tool name), or callable:
from runcycles import Action
# Static
action = Action(kind="tool.call", name="any")
# Per-tool mapping
action = {
"send_email": Action(kind="tool.call", name="send_email"),
"search": Action(kind="tool.call", name="search"),
}
# Callable
def derive(request):
return Action(kind="tool.call", name=request.tool_call["name"])
Idempotency-key namespacing (v0.1.3+)
Cycles idempotency keys default to {prefix}-{tool_call_id} — deterministic per tool call so retries land on the same reservation. If your runtime can reuse short tool-call ids across runs (tc_1, tc_2, ...), set idempotency_namespace on the middleware to scope keys by run / workflow / tenant. Keys then become {prefix}-{namespace}-{tool_call_id}.
# Static — same namespace every call
gate = CyclesToolGate(
client,
subject=Subject(tenant="acme"),
action=Action(kind="tool.call", name="send_email"),
idempotency_namespace="run_2026_05_10_abc",
)
# Callable — receives the LangChain ToolCallRequest. Pull the namespace from
# wherever your runtime exposes the run id (a contextvar, your own middleware,
# request metadata, etc.). The exact accessor depends on your LangChain version.
def my_run_id(_request):
# In production: return your_runtime.current_run_id()
return current_run_id_contextvar.get("default")
gate = CyclesToolGate(
client,
subject=Subject(tenant="acme"),
action=Action(kind="tool.call", name="send_email"),
idempotency_namespace=my_run_id,
)
CyclesFanOutGate.idempotency_namespace is the same shape; the callable receives the agent state instead of the tool-call request. Without idempotency_namespace, keys keep the v0.1.2 shape exactly — no behavior change.
Per-call opt-out: a callable that returns None (or empty string) for a particular call disables namespacing for that call only, producing the v0.1.2 shape {prefix}-{tool_call_id}. Useful when some calls should be globally scoped (admin / system tools) while others get run-scoped namespacing — branch on the request and return None from the unscoped path.
Errors in the callable propagate: if your callable raises, the exception surfaces from wrap_tool_call / before_model to the agent. This is intentional — fail-fast on a misconfigured callable rather than silently producing keys with no namespace. Wrap in try/except inside the callable if you want a fallback.
Denial messages
denial_message accepts a format string (placeholders: {reason}, {tool}, {decision}) or a callable receiving the CyclesResponse:
gate = CyclesToolGate(
client,
subject=...,
action=...,
denial_message="Cycles denied {tool}: {reason}",
)
Error handling
- Denied tool calls return a
ToolMessagewith the denial content; the underlying handler is never invoked. The agent's model sees the denial as if a tool returned an error and can recover. - Reservation failures in
"reserve"mode are returned asToolMessage(handler not invoked). - Tool exceptions in
"reserve"mode trigger an automaticrelease_reservation, then the exception propagates. - Async/sync mismatch raises
TypeError— pairCyclesClientwith.invoke()andAsyncCyclesClientwith.ainvoke().
Settlement (commit) failures
In "reserve" and "decide+reserve" modes, the tool runs first, then the reservation is committed. If the commit call itself fails (network blip, server overload, etc.), the tool already ran — its side effect is real. You have two reasonable options, controlled by settlement_error_policy:
| Policy | Behavior | When to choose |
|---|---|---|
"raise" (default) |
Propagate the commit exception to the agent. The tool's return value is lost. | Strict governance — no tool-level cost can go unaccounted. |
"log" |
Log a warning, return the tool result anyway. The reservation will eventually expire via TTL. | UX-first — keep the agent moving, accept best-effort accounting. |
gate = CyclesToolGate(
client,
subject=...,
action=...,
mode="reserve",
settlement_error_policy="log", # opt out of strict default
)
Trade-off worth understanding: "raise" surfaces the commit failure as a tool exception, so a LangChain agent may retry — at which point the tool's side effect (e.g. an email send, a payment, a CRM write) repeats. Choose "log" if your tool's side effects are not safely idempotent on retry.
This only affects commit (success-path settlement); release on tool failure always logs and continues so the original tool exception wins.
Async support
Async middleware variants run automatically when the LangChain agent is invoked with .ainvoke(). Pass an AsyncCyclesClient:
from runcycles import AsyncCyclesClient
async_client = AsyncCyclesClient(CyclesConfig(...))
gate = CyclesToolGate(async_client, subject=..., action=..., mode="decide")
agent = create_agent(model="...", tools=[...], middleware=[gate])
await agent.ainvoke({"messages": [...]})
Examples
examples/tenant_budget_agent.py— single-tenant budget gate with risky-tool denial recovery.examples/multi_agent_fanout.py— multi-agent / HITL flow withCyclesToolGate+CyclesFanOutGate+HumanInTheLoopMiddleware.
Known limitations (v0.1)
- Reserve mode commits at the configured
estimate, not actual usage.mode="reserve"andmode="decide+reserve"reserve the estimate, run the tool, then commit the same amount on success. Per-tool actual-cost instrumentation (analogous toruncycles.stream_reservation'scost_fn) is on the roadmap. Until then, setestimateto the worst-case spend per call you're willing to debit, or usemode="decide"if you only want policy gating without budget movement. - No model-call middleware yet.
wrap_model_callis on the roadmap (planned for v0.2 asCyclesModelGate); v0.1.x covers tool-call gating and fan-out caps only. For LLM-spend tracking today, useruncycles.stream_reservationdirectly inside an LLM-spend handler. - Per-call subject only via the extractor form. Static
Subjectpins one tenant per middleware instance. For per-tenant/per-agent routing in a multi-tenant deployment, supply aSubjectExtractorcallable. - Idempotency keys are deterministic only when
tool_call_idis present. Keys take the shape{prefix}-{tool_call_id}so retries land on the same Cycles reservation. If the upstream omitstool_call_id, the middleware synthesizes a freshmissing-<hex>id (and logs a warning) — that path is non-deterministic across retries because the synthesis itself is random. Conformant LangChain runtimes always supplyid.
Development
pip install -e ".[dev]"
pytest # all tests
pytest --cov=langchain_runcycles # with coverage (gate: ≥95%)
ruff check . && ruff format
mypy langchain_runcycles
Documentation
- LangChain integration page: https://docs.langchain.com/oss/python/integrations/middleware/runcycles (pending PR review)
- Cycles protocol & SDK: https://runcycles.io
- Architecture: see AUDIT.md
Requirements
- Python 3.10+
runcycles >= 0.4.1langchain >= 1.0, < 2.0langchain-core >= 0.3
License
Apache-2.0. See LICENSE.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file langchain_runcycles-0.1.3.tar.gz.
File metadata
- Download URL: langchain_runcycles-0.1.3.tar.gz
- Upload date:
- Size: 44.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9e2c57da46be0493e5ae601b85e968d951e0f16826b632a1c761f277d1708fce
|
|
| MD5 |
75b103076a33b4947afd879bb3daf9fe
|
|
| BLAKE2b-256 |
ad60d5d5d7d20b2bb5ead76484247f3e999940951a0875900ec3804cc560bec4
|
Provenance
The following attestation bundles were made for langchain_runcycles-0.1.3.tar.gz:
Publisher:
python-publish.yml on runcycles/langchain-runcycles
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
langchain_runcycles-0.1.3.tar.gz -
Subject digest:
9e2c57da46be0493e5ae601b85e968d951e0f16826b632a1c761f277d1708fce - Sigstore transparency entry: 1495577524
- Sigstore integration time:
-
Permalink:
runcycles/langchain-runcycles@b2d0f6df027c0de6ad6ba96980de0b928702369e -
Branch / Tag:
refs/tags/v0.1.3 - Owner: https://github.com/runcycles
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@b2d0f6df027c0de6ad6ba96980de0b928702369e -
Trigger Event:
push
-
Statement type:
File details
Details for the file langchain_runcycles-0.1.3-py3-none-any.whl.
File metadata
- Download URL: langchain_runcycles-0.1.3-py3-none-any.whl
- Upload date:
- Size: 19.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
40087073af3ee6c92c88af59c4778e5629f3ee89bb5f188c710f246f67cf53a1
|
|
| MD5 |
2f8109dd56bbeab274ce4266b0dfd153
|
|
| BLAKE2b-256 |
1e2225daf12053f2caf612ec7f5fd0062f54a90d34ecdf5a585ff3e8599ef78c
|
Provenance
The following attestation bundles were made for langchain_runcycles-0.1.3-py3-none-any.whl:
Publisher:
python-publish.yml on runcycles/langchain-runcycles
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
langchain_runcycles-0.1.3-py3-none-any.whl -
Subject digest:
40087073af3ee6c92c88af59c4778e5629f3ee89bb5f188c710f246f67cf53a1 - Sigstore transparency entry: 1495577829
- Sigstore integration time:
-
Permalink:
runcycles/langchain-runcycles@b2d0f6df027c0de6ad6ba96980de0b928702369e -
Branch / Tag:
refs/tags/v0.1.3 - Owner: https://github.com/runcycles
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@b2d0f6df027c0de6ad6ba96980de0b928702369e -
Trigger Event:
push
-
Statement type: