Skip to main content

Deterministic verification for autonomous agent loops

Project description

loop-guard

Deterministic verification for autonomous agent loops.

loop-guard catches silent errors in agent loops by re-running code, looking up citations, and checking statistics — not by asking another LLM if the output "looks right."

PyPI Python 3.11+ License: MIT

The Problem

Autonomous agent loops run for hours without human oversight. Agents make intermediate claims — "accuracy is 94%", "tests pass", "p < 0.05" — that compound over hundreds of steps. A wrong claim at step 23 becomes the premise for steps 24–100. Nobody catches the error until a human reviews the final output, if at all.

How loop-guard Works

Agent Loop → Integration Layer → Claim Extractor → Verification Engine → Reporter
                                    (regex-first)     (3 layers)         (terminal/JSON/HTML)

Three verification layers, in order of reliability:

Layer Method Reliability Example
L1: Deterministic Re-execute code, API lookup, re-compute Cannot be wrong Citation lookup, code re-run
L2: Rule-based Pattern matching, sanity checks Rarely wrong p > 1 detection, loop trap
L3: LLM-assisted Soft flagging only May be wrong General claim flagging

Key principle: Verification must be more reliable than the thing being verified. LLMs are used only for claim extraction (a structured task), never for judgment.

Install

pip install loop-guard

# With LLM-based claim extraction (optional)
pip install loop-guard[llm]

Quick Start

Python API (2 lines to integrate)

from loop_guard import LoopGuard

guard = LoopGuard()

# Works with ANY agent loop — OpenAI, Anthropic, Google ADK, LangGraph, custom
for i in range(num_experiments):
    result = agent.run(task)
    findings = guard.step(
        output=result.text,
        code=result.code_executed,       # optional
        files=result.files_modified,     # optional
    )
    for f in findings:
        print(f)  # FAIL/WARN/FLAG with explanation

# Generate report
guard.report(format="html", path="audit.html")

CLI (zero code change)

# Pipe any agent's stdout
python my_agent.py 2>&1 | loop-guard watch

# Watch a log file
loop-guard watch --file agent.log --follow

# Watch git commits (for autoresearch)
loop-guard watch --git-dir ./experiments/ --poll 30

# Check a transcript
loop-guard check --input transcript.txt --format html

What Gets Verified

Verifiers

Verifier Layer What it catches
LoopTrapVerifier L2 Agent stuck retrying the same failing approach
RegressionVerifier L2 Agent reverts a file to a previous version
CitationVerifier L1 Hallucinated academic citations (CrossRef + Semantic Scholar)
StatisticalVerifier L2 Impossible p-values, missing multiple comparison correction, small samples
CodeOutputVerifier L1 Agent claims code produced output X, but re-execution produces Y
MetricVerifier L1 Agent claims metric = X, but re-computation gives Y

Claim Extraction

Claims are extracted from agent output using a regex-first pipeline:

  1. Regex patterns catch citations, metrics, p-values, test results, and file modifications
  2. LLM extraction (optional) handles remaining unstructured text
  3. Claims are typed: CODE_OUTPUT, METRIC, STATISTICAL, CITATION, TEST_RESULT, FILE_STATE, GENERAL

Output

Terminal (real-time)

[loop-guard] Step 4 [FAIL] [L2] Impossible statistical value: accuracy = 105.3% (> 100%)
             Expected: accuracy ∈ [0%, 100%]
             Actual:   105.3%
[loop-guard] Step 3 [WARN] [L1] Citation not found in CrossRef or Semantic Scholar
             Expected: Fakenstein et al. 2025
             Actual:   No matching paper found
[loop-guard] Step 7 [WARN] [L2] Agent appears stuck: 3 consecutive similar outputs

JSON Report

loop-guard check --input transcript.txt --output report.json --format json

HTML Report

loop-guard check --input transcript.txt --output report.html --format html

Produces a styled, shareable HTML report with findings grouped by step, color-coded by severity.

Configuration

guard = LoopGuard(config={
    # Claim extraction
    "use_llm_extraction": True,              # Enable LLM fallback extraction
    "extraction_model": "claude-haiku-4-5-20251001",  # Model for extraction

    # Verification
    "sandbox_dir": "/tmp/loopguard_sandbox", # Code execution sandbox
    "timeout": 60,                           # Sandbox timeout (seconds)

    # Loop trap detection
    "similarity_threshold": 0.8,             # Output similarity threshold
    "consecutive_limit": 3,                  # Consecutive similar outputs to trigger

    # Reporting
    "verbosity": "findings_only",            # all | findings_only | failures_only
})

Architecture

loop_guard/
├── __init__.py          # Public API
├── models.py            # ClaimType, Verdict, Finding, etc.
├── extractor.py         # Regex-first claim extraction
├── engine.py            # Verification routing engine
├── reporter.py          # Terminal, JSON, HTML output
├── guard.py             # LoopGuard (main entry point)
├── cli.py               # CLI (loop-guard watch/check/report)
└── verifiers/
    ├── loop_trap.py     # Stuck loop detection
    ├── regression.py    # File regression detection
    ├── citation.py      # CrossRef + Semantic Scholar lookup
    ├── statistical.py   # Statistical sanity checks
    ├── code_output.py   # Code re-execution
    └── metric.py        # Metric re-computation

What loop-guard Is NOT

  • NOT an LLM-as-judge system. Those share the same failure modes as the agent being judged.
  • NOT a prompt injection detector. Use dedicated security tools for that.
  • NOT a post-hoc evaluation tool. It runs in-loop, catching errors as they happen.
  • NOT a replacement for human review. It flags issues for humans to investigate.

Examples

See the examples/ directory:

  • autoresearch_demo.py — ML experiment loop with metric/citation/loop-trap verification
  • openai_sdk_demo.py — Coding agent integration pattern
  • adk_demo.py — Data analysis agent with statistical verification

Contributing

git clone https://github.com/ybkim95/loop-guard
cd loop-guard
pip install -e ".[dev]"
pytest

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

loopguard_ai-0.1.0.tar.gz (77.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

loopguard_ai-0.1.0-py3-none-any.whl (48.6 kB view details)

Uploaded Python 3

File details

Details for the file loopguard_ai-0.1.0.tar.gz.

File metadata

  • Download URL: loopguard_ai-0.1.0.tar.gz
  • Upload date:
  • Size: 77.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.12

File hashes

Hashes for loopguard_ai-0.1.0.tar.gz
Algorithm Hash digest
SHA256 223d9e7549c6b0415e8d3e29b892285b3452a8a7ba952b48652dd8bcd5f60756
MD5 a1d76ea1ebefbee107adc3921da0c2a0
BLAKE2b-256 2cba28625d9694e5ce76deec0ba0e835c325b15c250970614cf880fe50d9f1f0

See more details on using hashes here.

File details

Details for the file loopguard_ai-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: loopguard_ai-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 48.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.12

File hashes

Hashes for loopguard_ai-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 18ddbace5dc97822aba7319dab651f5fa7eb26eeb5a94b8d1003d04033c54a5b
MD5 3767f21bf52668596f9304a16f091056
BLAKE2b-256 3c7ea237e1405a863f66d6df976ba9be0888487487e69c8063d450b239c9cc84

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page