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

Uploaded Python 3

File details

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

File metadata

  • Download URL: psiguard-0.1.5.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.5.tar.gz
Algorithm Hash digest
SHA256 be09e3a86634e237303987ff80559869a36f5efcb156208507537752432270cc
MD5 6efa3dd3f92dbfe06d0265e7fdf53943
BLAKE2b-256 c17d2c80a2a72e38e0e8c2f5acf3b184b15ce56d1d1a71c2d2700b8e9d6a320d

See more details on using hashes here.

File details

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

File metadata

  • Download URL: psiguard-0.1.5-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.5-py3-none-any.whl
Algorithm Hash digest
SHA256 b49e18d1f33967c50b14fc972007dd59a695807248a7b3fddcd65a98caa501e4
MD5 8f9e89bba4e6bc055f638fe2dc68c1c8
BLAKE2b-256 5c76fcd5e21d20aa26938a85ff60f4f421e914ee7ccc992aa1d0e05d67cf9489

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