Skip to main content

BehaviorWeave

Async behavioral policies and interventions for LangGraph and LangChain agents.

CI PyPI Python Docs License

Agents repeat tool calls, retry failing dependencies, and bounce work between specialists. BehaviorWeave detects these patterns deterministically and returns typed interventions: your application decides when to nudge, escalate, request review, or stop.

BehaviorWeave architecture

Highlights

  • Deterministic and explainable: pattern, count, threshold, policy, and provenance; no model call is needed to evaluate a policy.
  • Async-first: engine, storage, audit, and lifecycle operations are awaitable.
  • LangChain middleware: guard create_agent and Deep Agents tool calls; scope by thread, append guidance, block configured kinds, and track outcomes.
  • Customizable: ABCs for patterns, stores, and sinks; inject every agxai capability, plugin, configuration, and exporter.
  • Durable history: LangGraph BaseStore adapter and PostgreSQL/Redis reference stores; persisted middleware halts and reusable conformance tests.
  • Reliable: scope isolation, idempotent redelivery, atomic state transitions, and 100% source line and branch coverage.

Install

pip install behaviorweave

Or uv add behaviorweave. Supports Python 3.12 through 3.15.

Quickstart

import asyncio
from behaviorweave import BehaviorEngine, BehaviorEvent, InterventionType, PolicyRule


async def main():
    async with BehaviorEngine(
        policies=[
            PolicyRule("nudge", "repeated_tool_call", 2, InterventionType.NUDGE),
            PolicyRule("stop", "repeated_tool_call", 3, InterventionType.STOP),
        ]
    ) as engine:
        kinds = []
        for _ in range(3):
            decision = await engine.process(
                BehaviorEvent.tool_call("get_alarm", {"machine": "ETCH-3"}, scope="incident-42")
            )
            kinds.append(decision.intervention.kind.value)
        print(kinds)  # ['noop', 'nudge', 'stop']


asyncio.run(main())

Guard a LangChain agent

from langchain.agents import create_agent
from behaviorweave.integrations.langchain import BehaviorWeaveMiddleware

agent = create_agent(model, tools=[get_alarm], middleware=[BehaviorWeaveMiddleware(engine)])
result = await agent.ainvoke(
    {"messages": [{"role": "user", "content": "Inspect ETCH-3."}]},
    config={"configurable": {"thread_id": "incident-42"}},
)

The second identical call receives [BehaviorWeave:nudge] guidance. The third is blocked before the tool runs. The engine returns decisions; enforcement belongs to the middleware or your host application.

Built-in patterns

Pattern Detects
repeated_tool_call Consecutive identical tool calls.
repeated_node_execution Consecutive executions of one node.
failure_streak, retry_streak, success_streak Consecutive outcomes.
delegation_streak Repeated delegation to one agent.
oscillation Back-and-forth handoffs or delegations.
event_frequency Total occurrences of each event identity.

Policies select thresholds, priorities, per-policy cooldowns, once-only behavior, and intervention kinds. Configure the built-in pattern classes or subclass the Pattern ABC.

Integrations and customization

Surface Available customization
LangChain Scope, block kinds, sync/async decision hook, formatter, middleware name.
LangGraph Host-owned routing/checkpoints, event adapters, BaseStore namespace and TTL.
agxai Config, registry, identity, plugins, custom capture, store, exporter, attribution, explanation, disclosure and capture policies.
Audit Async AuditSink, in-memory sink, CompositeAuditSink fan-out, and AgxaiAuditSink for semantic decisions.
Metrics OpenTelemetryMetricsSink counts decisions on any MeterProvider (otel extra).
Storage Async BehaviorStateStore ABC with scope release, and PostgreSQL/Redis reference implementations.
MCP / Swarm / Deep Agents Guards at real tool, delegation, and handoff boundaries.

See the downstream inventory. agxai is used for provenance and explanations; BehaviorWeave owns behavioral decisions.

Examples and Agent Skills

The twenty async examples cover middleware, MCP, graph loops, Swarm, Deep Agents, concurrent runs, durable databases, agxai semantic audit, OpenTelemetry traces and metrics, and batch replay. Configure model credentials through environment variables; database/OTel examples support local Podman services.

The Agent Skills teach agents how to integrate and extend the package, with executable checks and evaluations.

Documentation and project

Apache License 2.0. See LICENSE.

Metadata

Release files for behaviorweave 1.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for behaviorweave 1.1.1
File Size Uploaded Provenance Actions
behaviorweave-1.1.1.tar.gz 706.2 kB Without provenance Details for behaviorweave-1.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for behaviorweave 1.1.1
File Interpreter ABI Platform Actions
behaviorweave-1.1.1-py3-none-any.whl Python 3 none any Details for behaviorweave-1.1.1-py3-none-any.whl

Total release size: 769.4 kB

Release files / behaviorweave-1.1.1.tar.gz

Download URL behaviorweave-1.1.1.tar.gz
Size 706.2 kB
Tags Source
SHA-256 checksum
How to use checksums
e2032e927c56d354d45a76cb21c700b5169a1ef7f6bff2142a138e8a27219938
BLAKE2b-256 checksum
How to use checksums
d3d1f966093996684cf2374c6d87086c5f8eaacae0fbabcb11572b2fa5c049d3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.15 {"installer":{"name":"uv","version":"0.12.15","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / behaviorweave-1.1.1-py3-none-any.whl

Download URL behaviorweave-1.1.1-py3-none-any.whl
Size 63.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7f61fd86ef78bca6cd4ebd60b404626cc53944c108235d84993c5a9af0e99365
BLAKE2b-256 checksum
How to use checksums
5250d979feee487930dc6eede650cf0c0c2e3a4a30b62bb4999767f2d8f61f3c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.15 {"installer":{"name":"uv","version":"0.12.15","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for behaviorweave 1.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page