Skip to main content

Real-time AI safety monitoring — detect hallucinations, drift, and anomalies in your AI responses.

Project description

# PsiGuard Python SDK

**Real-time AI safety monitoring.** Detect hallucinations, drift, and cognitive anomalies in your AI responses before they reach your users.

[![PyPI version](https://img.shields.io/pypi/v/psiguard.svg)](https://pypi.org/project/psiguard/)
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)

---

## Install

```bash
pip install psiguard
```

---

## Quick Start

```python
from psiguard import PsiGuard

# Initialize with your API key
pg = PsiGuard(api_key="pg_...")
# Or set PSIGUARD_API_KEY in your environment and call PsiGuard() with no args

# Monitor an AI response
result = pg.check(
prompt="What is the capital of France?",
response="The capital of France is Paris.",
thread_id="session-abc123", # use same ID across a conversation
)

if result.should_block:
print("Blocked:", result.explanation)
else:
print(f"Safe | risk={result.risk_score}/100 | state={result.state}")
```

---

## API Reference

### `PsiGuard(api_key, base_url, timeout)`

| Param | Type | Default | Description |
|-------|------|---------|-------------|
| `api_key` | str | `PSIGUARD_API_KEY` env var | Your `pg_...` key from the dashboard |
| `base_url` | str | PsiGuard API | Override for testing |
| `timeout` | int | `15` | HTTP timeout in seconds |

---

### `.check(prompt, response, thread_id, risk_threshold) → CheckResult`

Monitor an AI response in real time.

```python
result = pg.check(
prompt="Explain quantum tunneling.",
response="Quantum tunneling is a phenomenon where...",
thread_id="chat-session-42",
risk_threshold=70, # block if risk_score > 70 (default)
)
```

**CheckResult fields:**

| Field | Type | Description |
|-------|------|-------------|
| `should_block` | bool | `True` = suppress this response |
| `state` | str | `WARMING_UP`, `STABLE`, `ANALYZING`, `UNSTABLE`, `ANOMALY`, `DRIFT`, `CRITICAL`, `BLOCKED` |
| `risk_score` | int | 0–100. Higher = more risk |
| `confidence` | float | 0.0–1.0. Engine confidence in its verdict |
| `warnings` | list[str] | Human-readable warning messages |
| `explanation` | str | Plain-English explanation of the decision |
| `timestamp` | float | Unix timestamp from the server |

---

### `.thread_reset(thread_id) → bool`

Clear a thread's monitoring history. Call at the start of each new conversation.

```python
pg.thread_reset("chat-session-42")
```

---

### `.thread_summary(thread_id) → ThreadSummary`

Get aggregated risk stats for a conversation thread.

```python
summary = pg.thread_summary("chat-session-42")
print(f"Steps: {summary.total_steps} | Avg risk: {summary.mean_risk} | Peak: {summary.max_risk}")
```

**ThreadSummary fields:** `total_steps`, `mean_risk`, `max_risk`, `state_counts`

---

### Exceptions

| Exception | When |
|-----------|------|
| `PsiGuardAuthError` | Missing, invalid, or inactive API key |
| `PsiGuardRateLimitError` | Monthly limit reached (Playground plan) |
| `PsiGuardError` | Any other API or network error |

All exceptions expose a `.status_code` attribute with the HTTP status.

---

## Real-World Example

```python
import openai
from psiguard import PsiGuard, PsiGuardError

pg = PsiGuard() # reads PSIGUARD_API_KEY from env
client = openai.OpenAI()

def safe_chat(user_message: str, session_id: str) -> str:
ai_response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": user_message}],
).choices[0].message.content

try:
result = pg.check(
prompt=user_message,
response=ai_response,
thread_id=session_id,
)
if result.should_block:
return "I'm sorry, I can't help with that."
except PsiGuardError as e:
print(f"PsiGuard warning: {e}") # fail open — don't break the app

return ai_response
```

---

## Plans

| Plan | Checks/month | Price |
|------|-------------|-------|
| Playground | 50 | Free |
| Pro | Unlimited | [psiguard.ai/pricing](https://psiguard.ai/pricing) |

Get your API key at **[psiguard.ai](https://psiguard.ai)**

---

## License

MIT © PsiCo LLC

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

psiguard-0.1.4.tar.gz (6.4 kB view details)

Uploaded Source

Built Distribution

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

psiguard-0.1.4-py3-none-any.whl (6.9 kB view details)

Uploaded Python 3

File details

Details for the file psiguard-0.1.4.tar.gz.

File metadata

  • Download URL: psiguard-0.1.4.tar.gz
  • Upload date:
  • Size: 6.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.2

File hashes

Hashes for psiguard-0.1.4.tar.gz
Algorithm Hash digest
SHA256 a1dbf291d8217908281f4c443e3ff080866d16d5d2e374e5d4013d0179d781a7
MD5 30411358cb755ba1ccd2179d993edc95
BLAKE2b-256 696ee7d264e18626499c72b5512162f6375c5176fbf0403c317ad012e22c065d

See more details on using hashes here.

File details

Details for the file psiguard-0.1.4-py3-none-any.whl.

File metadata

  • Download URL: psiguard-0.1.4-py3-none-any.whl
  • Upload date:
  • Size: 6.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.2

File hashes

Hashes for psiguard-0.1.4-py3-none-any.whl
Algorithm Hash digest
SHA256 97a10fd0b9dcb088ffb3b5f636a6198b0c6158201807837d7bbe275a5b7dba10
MD5 86cb97d9019c7456e668bb29b697a0b7
BLAKE2b-256 c85aaef77e6655606e31a5abfd25236b4b5d0c491601c9cce32b01469ae132e5

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