Metadata-Version: 2.3
Name: xpbt
Version: 0.0.1
Summary: xpbt: Statistical testing framework for stochastic LLM-based agents (SPRT deployment gates, FSM hard-invariant monitors, Bayesian production monitoring).
Author: Chinmay Kakatkar
License: MIT License
         
         Copyright (c) 2026 Chinmay Kakatkar
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
         in the Software without restriction, including without limitation the rights
         to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
         copies of the Software, and to permit persons to whom the Software is
         furnished to do so, subject to the following conditions:
         
         The above copyright notice and this permission notice shall be included in all
         copies or substantial portions of the Software.
         
         THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
         IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
         FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
         AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
         LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
         OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
         SOFTWARE.
Requires-Dist: scipy>=1.10
Requires-Python: >=3.12
Project-URL: Homepage, https://github.com/ckstash/xpbt
Description-Content-Type: text/markdown

# xpbt

**xpbt** is a Python library for statistical testing of stochastic LLM-based agents. It provides FSM-based hard-invariant monitors, Wald SPRT deployment gates, and Bayesian production monitoring — the three-part framework described in the paper "Beyond Property-Based Testing for Stochastic Agents."

---

## Features

- **FSM hard-invariant monitor** — intercepts tool calls at runtime and raises `HardInvariantViolation` before an illegal state transition executes.
- **SPRT deployment gate** — Wald's Sequential Probability Ratio Test as a CI/CD gate; no fixed sample size required.
- **Beta posterior credible intervals** — calibrated uncertainty reporting for production quality monitoring.
- **`QualityScorer` protocol** — injection point for LLM-as-judge scorers; swap in a `lambda` for deterministic tests.
- Zero ML dependencies (only `scipy`).

---

## Installation

```bash
pip install xpbt
```

Built for Python 3.12 or above.

---

## Quick Start

### 1. Hard-invariant monitor (FSM)

```python
from xpbt import FSMMonitor, HardInvariantViolation

monitor = FSMMonitor(
    states=["s_init", "s_bal_read", "s_posted"],
    initial_state="s_init",
    transitions={
        ("s_init", "read_trial_balance"): "s_bal_read",
        ("s_bal_read", "post_journal"): "s_posted",
    },
)

monitor.step("read_trial_balance")  # ok
monitor.step("post_journal")        # ok

monitor.reset()
try:
    monitor.step("post_journal")    # raises HardInvariantViolation
except HardInvariantViolation as e:
    print(f"Blocked: {e}")
```

### 2. SPRT deployment gate

```python
from xpbt import SPRTGate, SPRTDecision

gate = SPRTGate(theta_null=0.05, theta_alt=0.01)
# A ≈ 2.944, B ≈ -2.944

for trajectory in my_agent_trajectories():
    violation = not quality_check(trajectory)
    decision = gate.update(violation)
    if decision == SPRTDecision.ACCEPT:
        print("Deploy: agent is compliant")
        break
    elif decision == SPRTDecision.REJECT:
        print("Block: agent is noncompliant")
        break
```

### 3. Bayesian production monitoring

```python
from xpbt import beta_credible_interval, violation_rate_summary

lower, upper = beta_credible_interval(k=5, n=1000)
print(f"95% credible interval: [{lower:.4f}, {upper:.4f}]")

summary = violation_rate_summary(k=5, n=1000)
print(summary)
# {'point_estimate': 0.005, 'lower': ..., 'upper': ..., 'n_samples': 1000, 'n_violations': 5}
```

---

## Using a LLM-as-judge quality scorer

The `QualityScorer` protocol accepts any callable `(trajectory: str) -> float`:

```python
import anthropic
from xpbt import SPRTGate, SPRTDecision

client = anthropic.Anthropic()

def llm_judge(trajectory: str) -> float:
    response = client.messages.create(
        model="claude-sonnet-5",
        max_tokens=10,
        messages=[{"role": "user", "content": f"Rate 0-1: {trajectory}"}],
    )
    return float(response.content[0].text.strip())

gate = SPRTGate(theta_null=0.05, theta_alt=0.01)
for traj in trajectories:
    violation = llm_judge(traj) < 0.85
    if gate.update(violation) != SPRTDecision.CONTINUE:
        break
```

In tests, replace `llm_judge` with `lambda traj: 1.0` or a `unittest.mock.Mock`.

---

## API Reference

See [API.md](API.md).

---

## License

MIT License. See [LICENSE](LICENSE).
