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

<Info>
  This guide covers the most common issues you might encounter when integrating with PromptGuard and provides step-by-step solutions.
</Info>

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

<AccordionGroup>
  <Accordion title="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
    </Warning>
  </Accordion>

  <Accordion title="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>

  <Accordion title="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 **Settings > API Keys**
    3. Verify the key exists and is not revoked
    4. Check your subscription is active and within request limits
  </Accordion>
</AccordionGroup>

### Subscription or Quota Errors

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

**Symptoms**:

* `402 Payment Required` with `quota_exceeded` or similar in the response body when over monthly request limit (Free/Pro hard limit).
* Access to certain features (e.g. custom policies, ML detection) requires Pro 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**:

<AccordionGroup>
  <Accordion title="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
    curl https://api.promptguard.co/api/v1/models \
      -H "X-API-Key: $PROMPTGUARD_API_KEY"
    ```
  </Accordion>

  <Accordion title="Adjust Timeout Settings">
    Increase timeout values in your client:

    ```javascript theme={"system"}
    // Node.js
    const openai = new OpenAI({
      apiKey: process.env.PROMPTGUARD_API_KEY,
      baseURL: 'https://api.promptguard.co/api/v1',
      timeout: 60000 // 60 seconds
    });
    ```

    ```python theme={"system"}
    # Python
    client = OpenAI(
        api_key=os.environ.get("PROMPTGUARD_API_KEY"),
        base_url="https://api.promptguard.co/api/v1",
        timeout=60.0
    )
    ```
  </Accordion>

  <Accordion title="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
  </Accordion>
</AccordionGroup>

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

<AccordionGroup>
  <Accordion title="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>

  <Accordion title="Adjust Security Level">
    If you're getting too many false positives:

    1. Go to **Security > Security Rules**
    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>

  <Accordion title="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
  </Accordion>
</AccordionGroup>

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

## Performance Issues

### High Latency

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

**Expected Performance**:

* PromptGuard proxy overhead: \~30ms, with ML detection: \~150ms (under 200ms P95)
* Total latency: OpenAI/Anthropic latency + 30-150ms depending on detection mode

**Troubleshooting**:

<AccordionGroup>
  <Accordion title="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>

  <Accordion title="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.PROMPTGUARD_API_KEY,
      baseURL: 'https://api.promptguard.co/api/v1',
      httpAgent: agent
    });
    ```
  </Accordion>

  <Accordion title="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;
    }
    ```
  </Accordion>
</AccordionGroup>

## Rate Limiting Issues

### Too Many Requests Error

**Problem**: Hitting rate limits.

**Symptoms**:

```json theme={"system"}
{
  "error": {
    "message": "Rate limit exceeded",
    "type": "rate_limit_error",
    "code": "too_many_requests"
  }
}
```

**Solutions**:

<AccordionGroup>
  <Accordion title="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>

  <Accordion title="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>

  <Accordion title="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'
      });
    }
    ```
  </Accordion>
</AccordionGroup>

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

<AccordionGroup>
  <Accordion title="Check Supported Models">
    Verify the model name is correct:

    ```bash theme={"system"}
    # List available models
    curl https://api.promptguard.co/api/v1/models \
      -H "X-API-Key: $PROMPTGUARD_API_KEY"
    ```

    For complete model list, see [Supported LLM Providers](/guides/llm-providers).

    Supported providers:

    * **OpenAI**: GPT-5.x, GPT-4.x, GPT-3.5 series
    * **Anthropic**: Claude 4.x, 3.7, 3.5, 3.x series
    * **Google**: Gemini 3.x, 2.5, 2.0, 1.5 series
    * **Mistral**: Mistral Large, Small, Tiny, Medium, Pixtral
    * **DeepSeek**: deepseek-chat, deepseek-reasoner
    * **Cohere**: Command R+, Command R, Command A, Aya
    * **Groq**: Llama, Qwen, Whisper models
    * **Azure OpenAI**: All OpenAI models via Azure
  </Accordion>

  <Accordion title="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
  </Accordion>
</AccordionGroup>

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

<AccordionGroup>
  <Accordion title="Increase Function Timeouts">
    For serverless deployments:

    ```json theme={"system"}
    // vercel.json
    {
      "functions": {
        "api/chat/stream.js": {
          "maxDuration": 300
        }
      }
    }
    ```
  </Accordion>

  <Accordion title="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
      }
    }
    ```
  </Accordion>
</AccordionGroup>

## Integration-Specific Issues

### Next.js API Routes

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

**Common Solutions**:

<AccordionGroup>
  <Accordion title="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>

  <Accordion title="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
    }
    ```
  </Accordion>
</AccordionGroup>

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

<CardGroup cols={2}>
  <Card title="Email Support" icon="envelope" href="mailto:support@promptguard.co">
    Technical support for integration issues
  </Card>

  <Card title="System Health" icon="activity" href="https://api.promptguard.co/health">
    Check API status in real-time
  </Card>

  <Card title="Integration Guides" icon="book" href="/guides/node-sdk">
    Complete integration guides and examples
  </Card>

  <Card title="Examples" icon="code" href="/cookbooks/chatbot-protection">
    See working code examples
  </Card>
</CardGroup>

### 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.PROMPTGUARD_API_KEY,
  baseURL: 'https://api.promptguard.co/api/v1',
  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.
