Skip to main content

Drift

PyPI version Python License: MIT

Statistical anomaly detection for AI agent workflows.
Catch silent failures before they corrupt your data.

pip install drift-detection

Your AI agents are failing silently. A tool call takes 10x longer than usual. The agent calls delete_file when it's never done that before. Output quality gradually degrades over hundreds of runs. Traditional monitoring tools weren't built for non-deterministic systems — Drift is.

What it does

Drift hooks into your agent's execution and applies statistical anomaly detection to the event stream:

  • Latency & token SPC — Flags when a tool call or LLM response takes significantly longer or uses significantly more tokens than its rolling baseline. Catches hung API calls, runaway generation, and upstream provider issues.

  • Sequence anomaly detection — Builds a transition matrix of tool-call sequences and flags when the agent takes a path that's never or rarely been seen. Catches agents going off-script, skipping required steps, or entering novel execution paths.

  • Output drift detection — Tracks output length, vocabulary diversity, and structural patterns over time. Flags when outputs shift significantly from baseline. Catches hallucination drift, prompt injection effects, and gradual quality degradation.

Install

pip install drift-detection

With LangChain support:

pip install "drift-detection[langchain]"

Quickstart

With LangChain

from drift import DriftGuard
from drift.callbacks.langchain import DriftCallbackHandler

guard = DriftGuard(on_anomaly=lambda a: print(f"🚨 {a}"))
handler = DriftCallbackHandler(guard)

# Pass the handler to any LangChain chain or LLM
chain.invoke("your query", config={"callbacks": [handler]})

# See what happened
guard.report()

Standalone (no framework required)

from drift import DriftGuard, AgentEvent, EventType

guard = DriftGuard(on_anomaly=lambda a: print(f"🚨 {a}"))

# Feed events from any source
guard.ingest(AgentEvent(
    event_type=EventType.TOOL_END,
    name="search_web",
    latency_ms=150.0,
    token_count=85,
    output_text="Found 3 results for query...",
))

guard.report()

Run the demo

python examples/demo.py

This simulates normal agent operation, builds baselines, then injects latency spikes, sequence anomalies, and output drift — showing each detector catching real failure modes.

Architecture

drift/
├── core.py              # DriftGuard engine — orchestrates detectors
├── models.py            # AgentEvent, Anomaly, Severity data models
├── detectors/
│   ├── latency.py       # Statistical process control on latency/tokens
│   ├── sequence.py      # Action transition probability anomalies
│   └── output_drift.py  # Output distribution shift detection
└── callbacks/
    └── langchain.py     # LangChain callback integration

Design principles:

  1. Zero-overhead default — Detectors use numpy for fast rolling statistics. No embedding models, no external services, no network calls.
  2. Per-tool baselines — Each tool and model gets its own statistical baseline, so a slow tool won't pollute the baseline for a fast one.
  3. Framework-agnostic core — The detection engine works with raw AgentEvent objects. Framework integrations (LangChain, CrewAI, etc.) are thin adapters that translate framework callbacks into events.
  4. Non-blocking — Drift never throws exceptions that would crash your agent. Detector errors are caught and logged to stderr.

Detectors

Detector What it catches Method
LatencyDetector Hung calls, slow APIs, runaway generation Rolling z-score on latency and token counts
SequenceDetector Off-script behavior, unexpected tool calls First-order Markov transition probabilities
OutputDriftDetector Hallucination drift, prompt injection, quality degradation Output length, vocab diversity, structural pattern tracking

Configuration

Each detector is independently configurable:

from drift import DriftGuard
from drift.detectors.latency import LatencyDetector, LatencyDetectorConfig
from drift.detectors.sequence import SequenceDetector, SequenceDetectorConfig

guard = DriftGuard(detectors=[
    LatencyDetector(LatencyDetectorConfig(
        window_size=100,     # Longer baseline window
        z_threshold=2.5,     # More sensitive
        min_samples=10,      # Require more data before alerting
    )),
    SequenceDetector(SequenceDetectorConfig(
        min_observations=20, # Require more transitions before flagging
    )),
])

Roadmap

  • CrewAI callback handler
  • OpenAI Agents SDK integration
  • Slack / PagerDuty alerting
  • Persistent baselines (save/load detector state)
  • Embedding-based output drift (optional dependency)
  • Web dashboard
  • Cost anomaly detection (track spend per run)

Contributing

Issues and PRs welcome. Run tests with:

pip install -e ".[dev]"
pytest

License

MIT

Metadata

Release files for drift-detection 0.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 drift-detection 0.1.1
File Size Uploaded Provenance Actions
drift_detection-0.1.1.tar.gz 17.0 kB With provenance Details for drift_detection-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for drift-detection 0.1.1
File Interpreter ABI Platform Actions
drift_detection-0.1.1-py3-none-any.whl Python 3 none any Details for drift_detection-0.1.1-py3-none-any.whl

Total release size: 34.1 kB

Release files / drift_detection-0.1.1.tar.gz

Download URL drift_detection-0.1.1.tar.gz
Size 17.0 kB
Tags Source
SHA-256 checksum
How to use checksums
56246e95aa1f22e587370df7f37426447e833b7f6e145660f46ffd4247a119c0
BLAKE2b-256 checksum
How to use checksums
6ae26fd061017ec0ebea7f8ee333ecc014584111cfc9984c90f01e6c87c35c18
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.

Transparency log

Release files / drift_detection-0.1.1-py3-none-any.whl

Download URL drift_detection-0.1.1-py3-none-any.whl
Size 17.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
da3290c99d0067cf4deffa62e55f8d3ebbfd034cd762611cb0d6c50ae002d9e5
BLAKE2b-256 checksum
How to use checksums
dfd15d10f619f157900c6c490b35be88c1ee756e7e370d10d7f1d4a00798762a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.

Transparency log

Security for drift-detection 0.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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for drift_detection-0.1.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.

Transparency log

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.

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files Full provenance

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