> ## 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

<Info>
  Migrating to PromptGuard is designed to be seamless. This guide walks you through migrating any existing OpenAI integration with minimal code changes and zero downtime.
</Info>

## Migration Overview

PromptGuard acts as a secure proxy that's 100% compatible with OpenAI's API. The migration typically requires changing just 2 lines of code:

1. **API Key**: Switch from OpenAI key to PromptGuard key
2. **Base URL**: Route requests through PromptGuard's secure proxy

```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](/quickstart))
* [ ] Development environment for testing

## Step-by-Step Migration

### Step 1: Environment Setup

Add your PromptGuard API key to your environment. See the [Quickstart](/quickstart) 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:

<CodeGroup>
  ```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.PROMPTGUARD_API_KEY,
    baseURL: 'https://api.promptguard.co/api/v1'
  });
  ```

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

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

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

  client = OpenAI(
      api_key=os.environ.get("PROMPTGUARD_API_KEY"),
      base_url="https://api.promptguard.co/api/v1"
  )
  ```
</CodeGroup>

That's it! Your existing code works unchanged.

### Step 3: Update Error Handling

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

<CodeGroup>
  ```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) {
      // PromptGuard-specific error handling
      if (error.message.includes('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;
    }
  }
  ```

  ```python Python theme={"system"}
  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 Exception as error:
          error_str = str(error)

          # PromptGuard-specific error handling
          if "policy_violation" in error_str:
              return {
                  "success": False,
                  "error": "security_block",
                  "message": "Request blocked by security policy",
                  "suggestion": "Please rephrase your request and try again"
              }

          # Re-throw other errors
          raise error
  ```
</CodeGroup>

### 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](/quickstart) 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>
  PromptGuard adds minimal latency (typically \~0.15s). Monitor your dashboard to see actual performance impact.
</Note>

## Framework-Specific Examples

### Express.js / Node.js

<CodeGroup>
  ```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.PROMPTGUARD_API_KEY,
    baseURL: 'https://api.promptguard.co/api/v1'
  });
  ```
</CodeGroup>

### FastAPI / Python

<CodeGroup>
  ```python Before theme={"system"}
  from openai import OpenAI

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

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

  client = OpenAI(
      api_key=os.environ.get("PROMPTGUARD_API_KEY"),
      base_url="https://api.promptguard.co/api/v1"
  )
  ```
</CodeGroup>

## Rollback Plan

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

1. Change `PROMPTGUARD_API_KEY` back to `OPENAI_API_KEY`
2. Remove the `baseURL` parameter

Your code will work exactly as before.

## Next Steps

<CardGroup cols={2}>
  <Card title="Integration Guides" icon="code" href="/guides/node-sdk">
    Detailed setup for Node.js, Python, React, and more
  </Card>

  <Card title="Security Configuration" icon="shield" href="/security/overview">
    Customize protection for your use case
  </Card>

  <Card title="Monitoring Dashboard" icon="chart-line" href="/platform/dashboard">
    Track security events and performance
  </Card>

  <Card title="Troubleshooting" icon="life-buoy" href="/production/troubleshooting">
    Common issues and solutions
  </Card>
</CardGroup>

## Need Help?

[Contact support](mailto:support@promptguard.co) or check our [troubleshooting guide](/production/troubleshooting).
