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

# Troubleshooting

> Common issues and solutions for PromptGuard integration

> [!NOTE]
>
> This guide covers the most common issues you might encounter when integrating with PromptGuard and provides step-by-step solutions.

## Authentication Issues

### Invalid API Key Error

**Problem**: Getting 401 Unauthorized errors when making requests.

**Symptoms**:

```json theme={"system"}
{
  "error": {
    "message": "Invalid API key provided",
    "type": "authentication_error",
    "code": "invalid_api_key"
  }
}
```

**Solutions**:

> [accordion] Verify API Key Configuration
>
> Check that your API key is properly set:
>
> ```bash theme={"system"}
> # Verify your key is set
> echo $PROMPTGUARD_API_KEY
> # Should show your API key (not empty)
> ```
>
> > [!WARNING]
> >
> > If you're getting authentication errors, verify that:
> >
> > * Your API key is correctly copied (no extra spaces or newlines)
> > * The key is from the correct project
> > * The key hasn't been deleted or deactivated

> [accordion] Check Environment Variables
>
> Ensure your API key is properly set:
>
> ```bash theme={"system"}
> # Check if environment variable is set
> echo $PROMPTGUARD_API_KEY
>
> # For Node.js applications
> console.log('API Key:', process.env.PROMPTGUARD_API_KEY?.substring(0, 10) + '...');
>
> # For Python applications
> import os
> print(f"API Key: {os.environ.get('PROMPTGUARD_API_KEY', 'NOT_SET')[:10]}...")
> ```

> [accordion] Verify Key Status
>
> Check if your API key is active in the dashboard:
>
> 1. Login to [app.promptguard.co](https://app.promptguard.co)
> 2. Navigate to [**Connect → API Keys**](https://app.promptguard.co/dashboard/api-keys)
> 3. Verify the key exists and is not revoked
> 4. Check your subscription is active and within request limits

### Subscription or Quota Errors

**Problem**: Request blocked due to subscription tier or monthly limit.

**Symptoms**:

* `429 Too Many Requests` with `monthly_quota_exceeded` in the response body when the month's usage credit is spent (Free hard limit), `spending_limit_exceeded` when usage past the credit has reached its spending cap, or `subscription_inactive` when the subscription has lapsed.
* Access to certain features (e.g. custom policies, ML detection) requires Developer or higher.

**Solutions**:

1. Check usage and limits in the dashboard (Billing / Usage)
2. Upgrade your plan if you need higher limits or more features
3. Ensure the API key belongs to a user with an active subscription

## Connection Issues

### Network Timeout Errors

**Problem**: Requests timing out or failing to connect.

**Symptoms**:

* Connection timeout errors
* Network unreachable errors
* DNS resolution failures

**Solutions**:

> [accordion] Check Network Connectivity
>
> Test basic connectivity to PromptGuard:
>
> ```bash theme={"system"}
> # Test DNS resolution
> nslookup api.promptguard.co
>
> # Test HTTP connectivity
> curl -I https://api.promptguard.co/api/v1/models
>
> # Test with your API key (and your OpenAI key, unless one is stored for the project)
> curl https://api.promptguard.co/api/v1/models \
>   -H "X-API-Key: $PROMPTGUARD_API_KEY" \
>   -H "Authorization: Bearer $OPENAI_API_KEY"
> ```

> [accordion] Adjust Timeout Settings
>
> Increase timeout values in your client:
>
> ```javascript theme={"system"}
> // Node.js
> 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 },
>   timeout: 60000 // 60 seconds
> });
> ```
>
> ```python theme={"system"}
> # Python
> client = OpenAI(
>     api_key=os.environ.get("OPENAI_API_KEY"),
>     base_url="https://api.promptguard.co/api/v1",
>     default_headers={"X-API-Key": os.environ.get("PROMPTGUARD_API_KEY")},
>     timeout=60.0
> )
> ```

> [accordion] Check Firewall/Proxy Settings
>
> Ensure your network allows outbound HTTPS connections:
>
> * Whitelist `api.promptguard.co` in firewall
> * Configure proxy settings if required
> * Check corporate network restrictions

## Security Policy Issues

### Unexpected Request Blocks

**Problem**: Legitimate requests being blocked by security policies.

**Symptoms**:

```json theme={"system"}
{
  "error": {
    "message": "Request blocked by security policy",
    "type": "policy_violation",
    "code": "prompt_injection_detected"
  }
}
```

**Solutions**:

> [accordion] Review Security Events
>
> 1. Open [app.promptguard.co](https://app.promptguard.co)
> 2. Navigate to **Security > Events**
> 3. Find the blocked request
> 4. Review the detection reason
> 5. Determine if it's a false positive

> [accordion] Adjust Security Level
>
> If you're getting too many false positives:
>
> 1. Go to **Projects > \[Your Project] > Guardrails**
> 2. Switch to a more permissive preset (e.g., from RAG System to Default)
> 3. Test your application
> 4. Gradually increase security as needed

> [accordion] Create Whitelist Rules
>
> For legitimate patterns being blocked:
>
> 1. Navigate to **Security > Custom Rules**
> 2. Create an "Allow" rule for the specific pattern
> 3. Test to ensure the rule works correctly

### High False Positive Rate

**Problem**: Too many legitimate requests being flagged as threats.

**Solutions**:

1. **Start with Default preset** during development
2. **Gradually increase security** in staging
3. **Monitor false positive rate** in dashboard
4. **Create custom whitelist rules** for your use cases
5. **Contact support** for policy tuning assistance

### Detection issues

Each of these is decided by the project's preset and guardrails, which you
change in the dashboard:

* **False positives.** Move the project to a more permissive
  [strictness level](https://docs.promptguard.co/security/policy-presets.md#strictness-levels), set a lower
  level on the one guardrail that fires
  ([per-guardrail configuration](https://docs.promptguard.co/security/policy-presets.md)), or add an allow
  rule for the legitimate pattern ([custom rules](https://docs.promptguard.co/security/custom-rules.md)).
* **A threat that was not caught.** Use a stricter level on that guardrail, or
  add a [custom rule](https://docs.promptguard.co/security/custom-rules.md) for the pattern your application
  sees. Some attacks no detector catches reliably:
  [Detection limits](https://docs.promptguard.co/security/detection-limits.md) lists them and the controls
  that do not depend on detection.
* **Slow scans.** Which detectors are slow and why, and how to keep the guard
  call fast: [Latency budgets](https://docs.promptguard.co/production/latency-budgets.md).

## Performance Issues

### High Latency

**Problem**: Requests taking longer than expected.

**Expected Performance**:

* PromptGuard overhead: the deterministic fast path runs in under 10 ms (measured). By default a request it finds clean continues to the ML classifiers, which is materially slower; see [latency budgets](https://docs.promptguard.co/production/latency-budgets.md) for the measured figures and how to measure your own traffic
* Total latency: OpenAI/Anthropic latency + the overhead above, which depends on your escalation rate rather than on a detection-mode constant

**Troubleshooting**:

> [accordion] Measure Latency Components
>
> ```javascript theme={"system"}
> async function measureLatency() {
>   const start = Date.now();
>
>   try {
>     const response = await openai.chat.completions.create({
>       model: "gpt-5-nano",
>       messages: [{ role: 'user', content: 'Hello!' }]
>     });
>
>     const total = Date.now() - start;
>     const pgOverhead = response.headers['x-promptguard-latency'];
>
>     console.log(`Total: ${total}ms, PromptGuard: ${pgOverhead}ms`);
>
>   } catch (error) {
>     console.error('Request failed:', error);
>   }
> }
> ```

> [accordion] Optimize Client Configuration
>
> ```javascript theme={"system"}
> // Use connection pooling
> import https from 'https';
>
> const agent = new https.Agent({
>   keepAlive: true,
>   maxSockets: 20
> });
>
> 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 },
>   httpAgent: agent
> });
> ```

> [accordion] Implement Request Caching
>
> Cache responses for identical requests:
>
> ```javascript theme={"system"}
> const cache = new Map();
>
> async function cachedRequest(prompt) {
>   const cacheKey = `${prompt}:gpt-5-nano`;
>
>   if (cache.has(cacheKey)) {
>     return cache.get(cacheKey);
>   }
>
>   const response = await openai.chat.completions.create({
>     model: "gpt-5-nano",
>     messages: [{ role: 'user', content: prompt }]
>   });
>
>   cache.set(cacheKey, response);
>   return response;
> }
> ```

## Rate Limiting Issues

### Too Many Requests Error

**Problem**: Hitting rate limits.

**Symptoms**:

```json theme={"system"}
{
  "error": {
    "message": "Rate limit exceeded. Please retry later.",
    "type": "rate_limit_exceeded",
    "code": "rate_limit_exceeded",
    "retry_after": 60
  }
}
```

**Solutions**:

> [accordion] Implement Exponential Backoff
>
> ```javascript theme={"system"}
> async function requestWithBackoff(requestFn, maxRetries = 3) {
>   for (let attempt = 0; attempt < maxRetries; attempt++) {
>     try {
>       return await requestFn();
>     } catch (error) {
>       if (error.status === 429 && attempt < maxRetries - 1) {
>         const delay = Math.pow(2, attempt) * 1000 + Math.random() * 1000;
>         await new Promise(resolve => setTimeout(resolve, delay));
>         continue;
>       }
>       throw error;
>     }
>   }
> }
> ```

> [accordion] Check Rate Limit Headers
>
> Monitor rate limit status:
>
> ```javascript theme={"system"}
> const response = await openai.chat.completions.create({...});
>
> console.log('Rate Limit Headers:');
> console.log('Remaining:', response.headers['x-ratelimit-remaining']);
> console.log('Reset:', response.headers['x-ratelimit-reset']);
> console.log('Limit:', response.headers['x-ratelimit-limit']);
> ```

> [accordion] Distribute Load
>
> Use multiple API keys to increase limits:
>
> ```javascript theme={"system"}
> const apiKeys = [
>   process.env.PROMPTGUARD_API_KEY_1,
>   process.env.PROMPTGUARD_API_KEY_2,
>   process.env.PROMPTGUARD_API_KEY_3
> ];
>
> function getClient() {
>   const keyIndex = Math.floor(Math.random() * apiKeys.length);
>   return new OpenAI({
>     apiKey: apiKeys[keyIndex],
>     baseURL: 'https://api.promptguard.co/api/v1'
>   });
> }
> ```

## Model and Provider Issues

### Model Not Found Error

**Problem**: Specified model is not available.

**Symptoms**:

```json theme={"system"}
{
  "error": {
    "message": "Model 'invalid-model' not found",
    "type": "invalid_request_error",
    "code": "model_not_found"
  }
}
```

**Solutions**:

> [accordion] Check Supported Models
>
> Verify the model name is correct:
>
> ```bash theme={"system"}
> # List OpenAI's models (your OpenAI key, unless one is stored for the project)
> curl https://api.promptguard.co/api/v1/models \
>   -H "X-API-Key: $PROMPTGUARD_API_KEY" \
>   -H "Authorization: Bearer $OPENAI_API_KEY"
> ```
>
> Which model ids go to which provider is on each provider's page under [Integrations](https://docs.promptguard.co/integrations/overview.md). A model id no provider claims is refused rather than guessed.

> [accordion] Verify Provider Configuration
>
> Ensure your provider API keys are configured:
>
> 1. Go to [app.promptguard.co](https://app.promptguard.co)
> 2. Navigate to **Settings > Provider Keys**
> 3. Add your OpenAI and/or Anthropic API keys
> 4. Test the connection

### Provider API Key Issues

**Problem**: Underlying provider (OpenAI/Anthropic) API key is invalid.

**Solutions**:

1. **Update provider keys** in PromptGuard dashboard
2. **Verify keys are active** in provider's dashboard
3. **Check subscription tier** for the models/features you're using
4. **Ensure sufficient credits** in provider account

## Streaming Issues

### Streaming Responses Cut Off

**Problem**: Streaming responses stop unexpectedly.

**Solutions**:

> [accordion] Increase Function Timeouts
>
> For serverless deployments:
>
> ```json theme={"system"}
> // vercel.json
> {
>   "functions": {
>     "api/chat/stream.js": {
>       "maxDuration": 300
>     }
>   }
> }
> ```

> [accordion] Handle Stream Errors
>
> ```javascript theme={"system"}
> async function handleStream(stream) {
>   try {
>     for await (const chunk of stream) {
>       const content = chunk.choices[0]?.delta?.content;
>       if (content) {
>         process.stdout.write(content);
>       }
>     }
>   } catch (error) {
>     console.error('Stream error:', error);
>     // Implement fallback or retry logic
>   }
> }
> ```

## Integration-Specific Issues

### Next.js API Routes

**Problem**: Issues with Next.js API integration.

**Common Solutions**:

> [accordion] Environment Variables
>
> Ensure proper environment variable setup:
>
> ```bash theme={"system"}
> # .env.local
> PROMPTGUARD_API_KEY=your_key_here
> ```
>
> ```javascript theme={"system"}
> // Check in API route
> console.log('API Key available:', !!process.env.PROMPTGUARD_API_KEY);
> ```

> [accordion] CORS Issues
>
> Configure CORS for frontend requests:
>
> ```javascript theme={"system"}
> // api/chat.js
> export default async function handler(req, res) {
>   // Add CORS headers
>   res.setHeader('Access-Control-Allow-Origin', '*');
>   res.setHeader('Access-Control-Allow-Methods', 'POST');
>   res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
>
>   if (req.method === 'OPTIONS') {
>     res.status(200).end();
>     return;
>   }
>
>   // Your API logic here
> }
> ```

## Getting Help

### Diagnostic Information

When contacting support, include:

```bash theme={"system"}
# System information
node --version
npm --version

# Test basic connectivity
curl -I https://api.promptguard.co/api/v1/models

# Check API key is set
echo $PROMPTGUARD_API_KEY | head -c 10

# Recent error logs
tail -n 50 /path/to/your/app.log
```

### Support Channels

> [card] [Email Support](mailto:support@promptguard.co)
>
> Technical support for integration issues

> [card] [System Health](https://api.promptguard.co/health)
>
> Check API status in real-time

> [card] [Integration Guides](https://docs.promptguard.co/guides/node-sdk.md)
>
> Complete integration guides and examples

> [card] [Examples](https://docs.promptguard.co/cookbooks/chatbot-protection.md)
>
> See working code examples

### Debug Mode

Enable debug logging for detailed troubleshooting:

```javascript theme={"system"}
// Node.js
process.env.DEBUG = 'openai:*';

// Or use console logging
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 },
  dangerouslyAllowBrowser: false, // Security check
  organization: undefined,
  project: undefined,
  defaultHeaders: {
    'X-Debug': 'true'
  }
});
```

Most issues can be resolved by following these troubleshooting steps. If you continue to experience problems, don't hesitate to reach out to our support team with the diagnostic information above.


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