Metadata-Version: 2.4
Name: tryverdictguard-sdk
Version: 1.1.0
Summary: Python SDK for Verdict Core authenticated tool-intent evaluation
License-Expression: Apache-2.0
Project-URL: Homepage, https://www.tryverdictguard.com
Project-URL: Source, https://github.com/pnkr01/verdict/tree/master/verdict-platform/sdks/python
Project-URL: Issues, https://github.com/pnkr01/verdict/issues
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.27.0
Requires-Dist: PyJWT>=2.9.0
Requires-Dist: cryptography>=43.0.0
Dynamic: license-file

# Verdict Python SDK

[![PyPI](https://img.shields.io/pypi/v/tryverdictguard-sdk.svg)](https://pypi.org/project/tryverdictguard-sdk/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](./LICENSE)

The official Python SDK for **Verdict Guard** (`tryverdictguard-sdk`, imported as `tryverdictguard_sdk`). It evaluates proposed AI agent actions against Verdict Core with sub-15ms latency, enforces 5-layer hierarchical policies, provides human-in-the-loop escrow holds, and executes 1-click compensating Saga rollbacks.

Requires Python 3.10 or newer.

## Install

```shell
pip install tryverdictguard-sdk
```

Configure credentials via environment variables:
```shell
export VERDICT_BASE_URL="https://api.tryverdictguard.com"
export VERDICT_CLIENT_ID="your_client_id"
export VERDICT_CLIENT_SECRET="your_client_secret"
export VERDICT_DPOP_PRIVATE_KEY="your_base64_ed25519_key"
```

---

## 1. Declarative Guardrail with Saga Rollback

Wrap sensitive agent tool functions using `@verdict.guard`. If `rollback_fn` is provided, Verdict arms a compensating inverse delta hook. If downstream steps fail or leadership triggers a rollback from the Console, the compensating transaction executes surgically.

```python
import os
from tryverdictguard_sdk import VerdictClient, VerdictPolicyBlockedError

verdict = VerdictClient(
    base_url=os.environ.get("VERDICT_BASE_URL", "https://api.tryverdictguard.com"),
    client_id=os.environ["VERDICT_CLIENT_ID"],
    client_secret=os.environ["VERDICT_CLIENT_SECRET"],
    agent_id="payments-agent",
)

# Start background saga worker to process leadership console rollbacks
verdict.start_rollback_worker(interval=2.0)

def refund_transfer(original_args, execution_output):
    """Compensating Saga Inverse Delta (e.g., after 5 hours or on failure)."""
    transfer_id = execution_output.get("transfer_id")
    print(f"Executing surgical refund for transfer {transfer_id}...")
    stripe.Refund.create(charge=transfer_id)
    return {"status": "REFUNDED", "transfer_id": transfer_id}

@verdict.guard(
    tool_name="payments.create_transfer",
    risk_category="FINANCIAL",
    value_field="amount",
    rollback_fn=refund_transfer,
    rollback_on_exception=True, # Auto-compensates if downstream tool fails!
)
def create_transfer(amount: float, recipient_id: str, currency: str = "USD"):
    # Real-world external side-effect
    return {"status": "SUCCESS", "transfer_id": f"txn_{recipient_id}", "amount": amount}

try:
    result = create_transfer(amount=125.00, recipient_id="vendor_4821")
    print("Action executed:", result)
except VerdictPolicyBlockedError as err:
    print(f"Action blocked by policy ceiling: {err}")
```

---

## 2. Programmatic Exception Recovery & Multi-Step Pipelines

When orchestrating multi-step agent journeys, if step 3 fails, seamlessly revert steps 1 and 2 with an audit reason:

```python
try:
    step1_out = create_invoice(vendor_id="v_101", amount=2500.0)
    step1_id = verdict.last_execution_id

    step2_out = reserve_gpu_instances(nodes=4)
    step2_id = verdict.last_execution_id

    # Downstream failure (e.g. invalid checkpoint or container crash)
    raise RuntimeError("Storage bucket unmounted during initialization")

except Exception as exc:
    # Surgically rollback in reverse order (LIFO)
    verdict.execute_rollback(step2_id, reason=f"Pipeline aborted: {exc}")
    verdict.execute_rollback(step1_id, reason=f"Pipeline aborted: {exc}")
    raise
```

---

## 3. 5-Hour State Safety: Saga vs Physical Database Restore

> **Why Compensating Deltas?**
> If an agent executed an action 5 hours ago and leadership requests a rollback, physical database restoration (e.g., `pg_restore` or disk snapshots) would wipe out all 5 hours of subsequent transactions created by every user across the company. 
> Verdict uses the **Saga Compensating Pattern**: it invokes `rollback_fn(original_args, execution_output)` to apply an exact, surgical inverse delta (e.g., issuing a refund or releasing a reservation), keeping all other data untouched.

---

## 4. Manual Low-Level Evaluation

For custom agent loops or manual policy checks:

```python
decision = verdict.evaluate(
    tool_name="refund_payment",
    original_args={"payment_id": "pay_123", "amount_usd": 25.00},
    session_id="checkout-session-1001",
    end_user_id="user_456",
    risk_category="FINANCIAL",
    monetary_value_usd=25.00,
    pre_flight_snapshot={"payment_status": "captured"},
)

if decision.verdict_status == "ALLOWED":
    # Execute tool
    pass
elif decision.verdict_status == "ESCROW_PENDING":
    # Wait for human reviewer
    pass
```

## Authenticated Endpoints & Security

Every request uses an RFC 9449 Ed25519 DPoP proof:
* `POST /v1/telemetry/intent` - Record raw LLM intent
* `POST /v1/guard/evaluate` - Sub-15ms policy & velocity evaluation
* `GET /v1/guard/escrow/{id}/wait` - Escrow human review long-poll
* `POST /v1/guard/commit-snapshot` - Downstream execution outcome recording
* `POST /v1/guard/executions/{id}/rollback` - Trigger compensating rollback
* `POST /v1/guard/rollback/claim` - Claim pending rollback tasks
* `POST /v1/guard/rollback/{id}/report` - Report compensation status
