Metadata-Version: 2.4
Name: guardrails-api
Version: 0.4.1
Summary: Guardrails API
Author-email: Guardrails AI <contact@guardrailsai.com>
License: ## THE FOLLOWING LICENSE HAS BEEN ADOPTED FROM THE ELSSTIC LICENSE ##
        
        Acceptance
        By using the software, you agree to all of the terms and conditions below.
        
        Copyright License
        The licensor grants you a non-exclusive, royalty-free, worldwide, non-sublicensable, non-transferable license to use, copy, distribute, make available, and prepare derivative works of the software, in each case subject to the limitations and conditions below.
        
        Limitations
        You may not provide the software to third parties as a hosted or managed service, where the service provides users with access to any substantial set of the features or functionality of the software.
        
        You may not move, change, disable, or circumvent the license key functionality in the software, and you may not remove or obscure any functionality in the software that is protected by the license key.
        
        You may not alter, remove, or obscure any licensing, copyright, or other notices of the licensor in the software. Any use of the licensor’s trademarks is subject to applicable law.
        
        Patents
        The licensor grants you a license, under any patent claims the licensor can license, or becomes able to license, to make, have made, use, sell, offer for sale, import and have imported the software, in each case subject to the limitations and conditions in this license. This license does not cover any patent claims that you cause to be infringed by modifications or additions to the software. If you or your company make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
        
        Notices
        You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms.
        
        If you modify the software, you must include in any modified copies of the software prominent notices stating that you have modified the software.
        
        No Other Rights
        These terms do not imply any licenses other than those expressly granted in these terms.
        
        Termination
        If you use the software in violation of these terms, such use is not licensed, and your licenses will automatically terminate. If the licensor provides you with a notice of your violation, and you cease all violation of this license no later than 30 days after you receive that notice, your licenses will be reinstated retroactively. However, if you violate these terms after such reinstatement, any additional violation of these terms will cause your licenses to terminate automatically and permanently.
        
        No Liability
        As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.
        
        Definitions
        The licensor is the entity offering these terms, and the software is the software the licensor makes available under these terms, including any portion of it.
        
        you refers to the individual or entity agreeing to these terms.
        
        your company is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. control means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
        
        your licenses are all the licenses granted to you for the software under these terms.
        
        use means anything you do with the software requiring one of your licenses.
        
        trademark means trademarks, service marks, and similar rights.
Keywords: Guardrails,Guardrails AI,Guardrails API,Guardrails API
Requires-Python: <4.0,>=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: guardrails-ai>=0.10.0
Requires-Dist: guardrails-ai-types>=0.4.0
Requires-Dist: psycopg2-binary<3,>=2.9.9
Requires-Dist: litellm<1.82.6,>=1.39.3
Requires-Dist: typer<1,>=0.9.4
Requires-Dist: requests>=2.32.3
Requires-Dist: aiocache>=0.11.1
Requires-Dist: fastapi>=0.114.1
Requires-Dist: SQLAlchemy>=2.0.34
Requires-Dist: alembic>=1.18.4
Requires-Dist: uvicorn>=0.30.6
Requires-Dist: python-dotenv>=1.2.1
Requires-Dist: openai>=1
Requires-Dist: typing-extensions<5.0.0,>=4.8.0; python_version < "3.11"
Provides-Extra: dev
Requires-Dist: ruff; extra == "dev"
Requires-Dist: coverage; extra == "dev"
Requires-Dist: gunicorn<23,>=22.0.0; extra == "dev"
Requires-Dist: pre-commit; extra == "dev"
Requires-Dist: opentelemetry-distro; extra == "dev"
Requires-Dist: jsonref; extra == "dev"
Requires-Dist: PyYaml; extra == "dev"
Requires-Dist: pyright[nodejs]>=1.1.396; extra == "dev"
Dynamic: license-file

# Guardrails API

A FastAPI server that hosts [Guardrails AI](https://github.com/guardrails-ai/guardrails) in your own environment, providing OpenAI-compatible endpoints for applying guards to LLM interactions.

## Installation

**Requirements:** Python 3.10–3.13

```bash
pip install guardrails-api
```

For development:

```bash
git clone https://github.com/guardrails-ai/guardrails-api.git
cd guardrails-api
pip install -e ".[dev]"
```

## Quick Start

### 1. Install Guardrails Hub validators

```bash
guardrails hub install hub://guardrails/detect_pii
```

### 2. Set up your guards

**Option A — Config file (in-memory, no database required)**

Create a `config.py` that defines your guards:

```python
from guardrails import Guard
from guardrails.hub import DetectPII

guard = Guard(name="pii-guard")
guard.use(DetectPII(pii_entities=["EMAIL_ADDRESS", "PHONE_NUMBER"]))
```

Add any additional server settings to your `.env` file:

```bash
PORT=8000
GUARDRAILS_LOG_LEVEL=INFO
```

Guards are loaded at startup and the API is read-only. Suitable for local development and static deployments.

**Option B — PostgreSQL (persistent, full CRUD)**

Add database credentials to your `.env` file using individual variables:

```bash
PGHOST=localhost
PGPORT=5432
PGDATABASE=guardrails
PGUSER=postgres
PGPASSWORD=password
```

Or a single connection URL:

```bash
DB_URL=postgresql://postgres:password@localhost:5432/guardrails
```

When a database is configured, schema migrations run automatically on startup and guards can be created, updated, and deleted via the API.

### 3. Start the server

```bash
guardrails-api start --env .env
```

The server will be available at `http://localhost:8000`.

- Swagger UI: `http://localhost:8000/docs`
- Health check: `http://localhost:8000/health-check`

## CLI Reference

### `guardrails-api start`

Start the API server.

```
guardrails-api start [OPTIONS]
```

| Option | Default | Description |
|--------|---------|-------------|
| `--env` | `.env` | Path to environment file |
| `--config` | `""` | Path to config file defining guards |
| `--port` | `8000` | Port to listen on |
| `--middleware` | `""` | Path to middleware file |
| `--env-override` | `False` | Override existing env vars with values from `--env` |

**Examples:**

```bash
# Basic startup
guardrails-api start

# Custom port and config
guardrails-api start --port 9000 --config ./my_guards.py

# Custom env file with override
guardrails-api start --env ./production.env --env-override
```

### `guardrails-api db upgrade`

Upgrade the database schema (PostgreSQL only).

```
guardrails-api db upgrade [REVISION] [OPTIONS]
```

| Argument/Option | Default | Description |
|-----------------|---------|-------------|
| `revision` | `head` | Target revision |
| `--env` | `.env` | Path to environment file |
| `--env-override` | `False` | Override existing env vars |

```bash
guardrails-api db upgrade
guardrails-api db upgrade abc123ef
```

### `guardrails-api db downgrade`

Downgrade the database schema (PostgreSQL only).

```
guardrails-api db downgrade [REVISION] [OPTIONS]
```

| Argument/Option | Default | Description |
|-----------------|---------|-------------|
| `revision` | `-1` | Target revision (use `-1` to roll back one step) |
| `--env` | `.env` | Path to environment file |
| `--env-override` | `False` | Override existing env vars |

```bash
guardrails-api db downgrade
guardrails-api db downgrade -2
```

### `guardrails-api --version`

Print the installed version.

```bash
guardrails-api --version
```

## Configuration

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `PORT` | `8000` | Server port |
| `HOST` | `http://localhost` | Host address |
| `GUARDRAILS_LOG_LEVEL` | `INFO` | Log level for Guardrails |
| `LOGLEVEL` | `INFO` | Application log level |
| `GUARDRAILS_API_KEY` | — | API key for authenticating requests |
| `APP_ENVIRONMENT` | `local` | Deployment environment label |

### PostgreSQL (optional)

By default the server uses in-memory storage. To enable persistence, set database connection variables:

```bash
# Individual variables
PGHOST=localhost
PGPORT=5432
PGDATABASE=guardrails
PGUSER=postgres
PGPASSWORD=password

# Or a full connection URL
DB_URL=postgresql://postgres:password@localhost:5432/guardrails

# Optional connection extras
DB_EXTRAS=?sslmode=verify-ca
```

When `PGHOST` (or `DB_URL`) is set, the server will automatically run schema migrations on startup and enable full CRUD operations on guards via the API.

### Custom Middleware

Pass a middleware file to register custom Starlette middleware:

```python
# middleware.py
from starlette.middleware.base import BaseHTTPMiddleware

class AuthMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        # add custom auth logic here
        return await call_next(request)
```

```bash
guardrails-api start --middleware middleware.py
```

## Running in Production

For production, run directly with uvicorn or gunicorn:

```bash
# uvicorn
uvicorn --factory 'guardrails_api.app:create_app' --host 0.0.0.0 --port 8000 --workers 4

# gunicorn
gunicorn -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000 "guardrails_api.app:create_app()"
```

## API Endpoints

| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/health-check` | Server health status |
| `GET` | `/guards` | List all guards |
| `POST` | `/guards` | Create a guard (requires PostgreSQL) |
| `GET` | `/guards/{guard_name}` | Get a guard by name |
| `PUT` | `/guards/{guard_name}` | Update a guard (requires PostgreSQL) |
| `DELETE` | `/guards/{guard_name}` | Delete a guard (requires PostgreSQL) |
| `POST` | `/guards/{guard_name}/validate` | Run validation against a guard |
| `POST` | `/guards/{guard_name}/openai/v1/chat/completions` | OpenAI ChatCompletion compatiable endpoint for guarded LLM interactions. |

## Storage Modes

**In-memory (default):** Guards are loaded from `config.py` at startup. The API is read-only — guards cannot be created or updated via the API.

**PostgreSQL:** Full CRUD via the API. Guards defined in `config.py` are seeded on startup. Schema migrations run automatically.
