> ## Documentation Index
> Fetch the complete documentation index at: https://docs.promptguard.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Migration from OpenAI

> Step-by-step guide to migrate your existing OpenAI integration to PromptGuard

> [!NOTE]
>
> This guide moves an existing OpenAI integration onto the PromptGuard proxy. The change is a base URL and one header; the rest of your code stays as it is.

## Migration Overview

PromptGuard is a proxy that serves OpenAI's Chat Completions and Responses routes, so the OpenAI SDK talks to it unchanged. The migration is two additions to your client:

1. **Base URL**: route requests through `https://api.promptguard.co/api/v1`
2. **`X-API-Key` header**: authenticate to PromptGuard with your PromptGuard key

Your OpenAI key stays where it is. The SDK sends it as `Authorization: Bearer`, and PromptGuard forwards that header to OpenAI. PromptGuard reads its own key only from `X-API-Key`, so passing the PromptGuard key as the client's `api_key` gets a 401.

```mermaid theme={"system"}
graph LR
    A[Your App] --> B[OpenAI API]
    A2[Your App] --> C[PromptGuard Proxy] --> D[OpenAI API]

    style A fill:#e1f5fe
    style A2 fill:#e8f5e8
    style C fill:#fff3e0
```

## Pre-Migration Checklist

* [ ] OpenAI API integration currently working
* [ ] PromptGuard account created ([sign up](https://app.promptguard.co))
* [ ] PromptGuard API key obtained ([get one here](https://docs.promptguard.co/quickstart.md))
* [ ] Development environment for testing

## Step-by-Step Migration

### Step 1: Environment Setup

Add your PromptGuard API key to your environment. See the [Quickstart](https://docs.promptguard.co/quickstart.md) for detailed setup instructions.

```bash .env theme={"system"}
# Keep existing OpenAI key for rollback capability
OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxx

# Add PromptGuard key
PROMPTGUARD_API_KEY=pg_live_xxxxxxxx
```

### Step 2: Update Client Configuration

Modify your OpenAI client initialization:

```javascript Node.js (Before) theme={"system"}
import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});
```

```javascript Node.js (After) theme={"system"}
import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY, // forwarded to OpenAI
  baseURL: 'https://api.promptguard.co/api/v1',
  defaultHeaders: { 'X-API-Key': process.env.PROMPTGUARD_API_KEY },
});
```

```python Python (Before) theme={"system"}
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ.get("OPENAI_API_KEY")
)
```

```python Python (After) theme={"system"}
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ.get("OPENAI_API_KEY"),  # forwarded to OpenAI
    base_url="https://api.promptguard.co/api/v1",
    default_headers={"X-API-Key": os.environ["PROMPTGUARD_API_KEY"]},
)
```

That's it! Your existing code works unchanged.

### Step 3: Update Error Handling

Enhance your error handling to account for PromptGuard's security features:

```python Python theme={"system"}
import openai

def make_ai_request(messages, model="gpt-5-nano"):
    try:
        completion = client.chat.completions.create(
            model=model,
            messages=messages
        )

        return {
            "success": True,
            "response": completion.choices[0].message.content
        }

    except openai.APIStatusError as error:
        # A PromptGuard block is an HTTP 403 whose error type is policy_violation
        if error.type == "policy_violation":
            return {
                "success": False,
                "error": "security_block",
                "message": "Request blocked by security policy",
                "suggestion": "Please rephrase your request and try again"
            }

        # Re-raise other errors
        raise
```

```javascript Node.js theme={"system"}
async function makeAIRequest(messages, model="gpt-5-nano") {
  try {
    const completion = await openai.chat.completions.create({
      model,
      messages
    });

    return {
      success: true,
      response: completion.choices[0].message.content
    };

  } catch (error) {
    // A PromptGuard block is an HTTP 403 whose error type is policy_violation
    if (error instanceof OpenAI.APIError && error.type === 'policy_violation') {
      return {
        success: false,
        error: 'security_block',
        message: 'Request blocked by security policy',
        suggestion: 'Please rephrase your request and try again'
      };
    }

    // Re-throw other errors
    throw error;
  }
}
```

### Step 4: Test Your Migration

Verify your core use cases work with PromptGuard:

1. **Test basic functionality**: Make a simple request
2. **Test security features**: Try a potentially malicious prompt
3. **Test your models**: Verify all models you use work correctly

See the [Quickstart](https://docs.promptguard.co/quickstart.md) for testing examples.

### Step 5: Monitor Your Migration

After migrating, monitor your requests in the [dashboard](https://app.promptguard.co):

* View security events and blocked requests
* Monitor latency and performance
* Track usage and costs

> [!NOTE]
>
> Every request is scanned before it is forwarded, so expect added latency. Measure it on your own traffic in the dashboard before you switch production over.

## Framework-Specific Examples

### Express.js / Node.js

```javascript Before theme={"system"}
const OpenAI = require('openai');

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY
});
```

```javascript After theme={"system"}
const OpenAI = require('openai');

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
  baseURL: 'https://api.promptguard.co/api/v1',
  defaultHeaders: { 'X-API-Key': process.env.PROMPTGUARD_API_KEY },
});
```

### FastAPI / Python

```python Before theme={"system"}
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ.get("OPENAI_API_KEY")
)
```

```python After theme={"system"}
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ.get("OPENAI_API_KEY"),  # forwarded to OpenAI
    base_url="https://api.promptguard.co/api/v1",
    default_headers={"X-API-Key": os.environ["PROMPTGUARD_API_KEY"]},
)
```

## Rollback Plan

If you need to rollback, simply revert the two changes:

1. Remove the base URL (`baseURL` / `base_url`)
2. Remove the `X-API-Key` default header

Your code will work exactly as before.

Stuck? [Contact support](mailto:support@promptguard.co) or check our [troubleshooting guide](https://docs.promptguard.co/production/troubleshooting.md).

## Next steps

> [card] [SDKs](https://docs.promptguard.co/guides/sdks.md)
>
> The Python and Node.js SDKs, their reference and upgrade guide

> [card] [Security Configuration](https://docs.promptguard.co/security/overview.md)
>
> Customize protection for your use case

> [card] [Monitoring Dashboard](https://docs.promptguard.co/platform/dashboard.md)
>
> Track security events and performance

> [card] [Troubleshooting](https://docs.promptguard.co/production/troubleshooting.md)
>
> Common issues and solutions


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.