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.3.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.3-py3-none-any.whl (6.8 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: psiguard-0.1.3.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.3.tar.gz
Algorithm Hash digest
SHA256 e2b6ac0f3f4ff9be27fd4879064306fcd9314bb9efa83e1be8b162666d2cb62d
MD5 012287c45ae1bd543801c5ea83473a0b
BLAKE2b-256 a48f5f31497637cf7d9483718198b20f0a9ab64ecdb9549abb2e1a2dfa84207b

See more details on using hashes here.

File details

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

File metadata

  • Download URL: psiguard-0.1.3-py3-none-any.whl
  • Upload date:
  • Size: 6.8 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.3-py3-none-any.whl
Algorithm Hash digest
SHA256 e7d622695aaf1bb691edd541f0a9a306623aa8ce673d4a0601dfbb9b1e1173f8
MD5 356f906a6cbd74c24f2adb84e202247a
BLAKE2b-256 480224527e490d6f80d61c990dbe13637ed613484c4807bba063aa9c6f995dd3

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