# LoopGain

> An open-source Python library that replaces fixed max_iterations caps in AI agent loops with real-time convergence detection and best-so-far rollback.

LoopGain is an open-source cost controller for AI agent loops, published under the Apache-2.0 license by LoopGain Technologies Inc. It replaces the universal `max_iterations=N` hack with a control-theoretic stop-and-rollback policy grounded in the Barkhausen stability criterion — a foundational result from electrical-engineering feedback-oscillator analysis (1921). The library is pure Python with zero runtime dependencies and supports Python 3.10+.

## What It Is

LoopGain sits inside a running agent loop and watches the error trajectory in real time. When the loop has genuinely converged, it stops it; when the loop is oscillating or diverging, it rolls back to the best output seen so far instead of returning the last (potentially degraded) draft. The core primitive is two calls — `should_continue()` to gate the loop and `observe(errors, output=output)` to feed it the latest error signal — plus a `result` object that carries the outcome, the best output, and a savings count versus a fixed cap.

## Five-State Decision Engine

The classifier reads four features off the full error trajectory each iteration:

- **E_ratio** — cumulative reduction (E_current / E_first)
- **slope_log** — OLS slope of log10(E), the geometric trend direction
- **slope_p** — t-test p-value of the slope, for statistical significance
- **osc_std** — standard deviation of detrended log10(E), the oscillation magnitude

Those four features route the loop into one of five named states: `FAST_CONVERGE` and `CONVERGING` say keep going; `STALLING`, `OSCILLATING`, and `DIVERGING` say stop (with rollback on the latter two). The state itself is the decision — no number to interpret. A legacy single-Aβ-band classifier from v0.1 remains available via `classifier='legacy_bands'` for callers who have empirically tuned those thresholds.

## Framework Adapters and Integration Path

LoopGain ships pre-built adapters for six major agent frameworks, each installable as a pip extra:

- **LangGraph** — drives `graph.stream()` step by step
- **CrewAI** — installs `step_callback` / `task_callback` on a Crew, chains with existing callbacks
- **AutoGen v0.4+** — wraps `team.run_stream()`, supports `observe_sources` filtering
- **LangChain** — duck-types against `create_agent()` and legacy `AgentExecutor`
- **OpenAI Agents SDK** — wraps `Runner.run_streamed().stream_events()`, async-first
- **Claude Agent SDK** — wraps `claude_agent_sdk.query()`, filters to `AssistantMessage` by default

The core wheel has zero runtime dependencies; framework packages are optional extras (`pip install 'loopgain[langgraph]'`, `[crewai]`, `[autogen]`, `[langchain]`, `[openai-agents]`, `[claude-agent-sdk]`, or `[all]`). A Claude Code plugin (`loopgain-plugin`) scans a whole repo for wrappable loops and proposes reviewed diffs one file at a time.

## Benchmark Results and Honest Limits

The project's homepage reports results from a pre-registered 2,000-trial benchmark across 10 workload cells and 6 adapters. According to those vendor-published figures: 92.8% less API spend versus `max_iter=20` ($27.05 → $1.94 total benchmark spend), approximately 15× faster median wall-clock per trial (30.9s → 2.1s), and a 0.678 weighted judge preference across 1,800 pairwise comparisons. The benchmark repository (`loopgain-bench`) is public and reproducible.

The README is explicit about limits: LoopGain detects convergence, not correctness. It stops when the error signal stops improving, not when the answer is right. The project reports a false-stop rate of ≤4.5% on the benchmark's code-gen workload, and notes that quality of the stop is bounded by the quality of the verifier behind the error signal.

## Hosted Dashboard and Telemetry Architecture

An optional hosted dashboard at `dashboard.loopgain.ai` provides six panels — Overview, Loop Health Map, Convergence, Waste Report, Rollback Log, and Alerts — over a shared fleet view. Telemetry is opt-in and off by default; when enabled, it sends only state transitions, smoothed Aβ summary values, rollback flags, iteration counts, savings figures, and a per-iteration trajectory — never prompts, completions, error contents, or output buffers. Both the telemetry receiver (a Cloudflare Worker) and the dashboard are open-source repositories under the `loopgain-ai` GitHub organization, making full self-hosting possible.

## Update: v0.6.3

The current release is v0.6.3, as shown on the homepage badge and in the README. This version adds support for bare `lg.send_telemetry()` calls configured entirely via environment variables (`LOOPGAIN_TELEMETRY_ENDPOINT` and `LOOPGAIN_TELEMETRY_TOKEN`), and introduces `actual_dollars_spent` / `actual_dollars_saved` optional fields for passing genuinely measured cost figures to the dashboard. The project self-describes as alpha software with a stable math and API surface, recommending version pinning before 1.0.

## Features
- Five-state trajectory classifier (FAST_CONVERGE, CONVERGING, STALLING, OSCILLATING, DIVERGING)
- Best-so-far rollback buffer — returns argmin(error), not the last iteration
- Per-run savings_vs_fixed_cap accounting vs a fixed max_iterations cap
- Framework adapters for LangGraph, CrewAI, AutoGen, LangChain, OpenAI Agents SDK, Claude Agent SDK
- Zero runtime dependencies in the core wheel; framework adapters are optional pip extras
- Opt-in telemetry with self-hostable receiver and dashboard
- Legacy single-Aβ-band classifier available via classifier='legacy_bands'
- CLI: loopgain doctor, loopgain telemetry --show/--enable/--disable
- Claude Code plugin (loopgain-plugin) for scanning repos and proposing loop-wrapping diffs
- Hosted fleet dashboard with Loop Health Map, Waste Report, Rollback Log, and Alerts
- Async support across all adapters (arun, astream)
- target_error=None mode for plateau-based stopping without a fixed target
- TrajectoryThresholds customization for domain-specific tuning
- Reproducible public benchmark (loopgain-bench, 2,000 trials)

## Integrations
LangGraph, CrewAI, AutoGen v0.4+, LangChain, OpenAI Agents SDK, Claude Agent SDK (Anthropic), Slack (dashboard alerts), Webhooks (dashboard alerts), Cloudflare Workers (telemetry receiver), PyPI, Claude Code

## Platforms
MACOS, WEB, API, DEVELOPER_SDK, CLI

## Pricing
Open Source, Free tier available

## Version
0.6.3

## Links
- Website: https://loopgain.ai
- Documentation: https://github.com/loopgain-ai/loopgain
- Repository: https://github.com/loopgain-ai/loopgain
- EveryDev.ai: https://www.everydev.ai/tools/loopgain
