Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/MatthewSabia1/SubPirate-Pro/llms.txt

Use this file to discover all available pages before exploring further.

Overview

SubPirate uses OpenRouter to analyze subreddits for marketing potential. OpenRouter provides unified access to multiple LLM providers, and SubPirate uses Google’s Gemini 3 Flash model for fast, cost-effective analysis.

Why OpenRouter?

OpenRouter offers several advantages:
  • Unified API: Access multiple LLM providers through a single API
  • Automatic failover: If one provider is down, OpenRouter routes to alternatives
  • Cost tracking: Built-in usage monitoring and spend limits
  • Model flexibility: Easy to switch models without code changes

Getting Started

1

Create OpenRouter Account

2

Generate API Key

Navigate to SettingsAPI Keys and create a new key.
Store your API key securely. It will only be shown once at creation time.
3

Add Credits

Add credits to your OpenRouter account. Start with $5-10 for testing.Typical costs:
  • Analysis per subreddit: ~$0.01-0.05 depending on data volume
  • 100 analyses: ~$2-5
4

Configure Environment Variable

Add your API key to .env:
.env
OPENROUTER_API_KEY=sk-or-v1-...
This is a server-only variable. Never prefix it with VITE_ or expose it to the browser.

Model Configuration

SubPirate uses Google Gemini 3 Flash Preview as the default model:
const OPENROUTER_MODEL = 'google/gemini-3-flash-preview';
This model is defined in api/_lib/openrouter.js:7.

Why Gemini 3 Flash?

  • Fast: Low latency responses (typically 2-5 seconds)
  • Cost-effective: ~$0.01 per analysis
  • JSON output: Native support for structured JSON responses
  • Context window: 1M+ tokens for analyzing large subreddit data

Switching Models

To use a different model, update the constant in api/_lib/openrouter.js:
// Alternative options:
const OPENROUTER_MODEL = 'anthropic/claude-3.5-sonnet'; // Higher quality, more expensive
const OPENROUTER_MODEL = 'openai/gpt-4o-mini'; // Balanced option
const OPENROUTER_MODEL = 'meta-llama/llama-3.1-70b-instruct'; // Open source
View available models at https://openrouter.ai/models.

API Implementation

The OpenRouter integration is implemented in api/_lib/openrouter.js:

Request Configuration

const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${apiKey}`,
    'Content-Type': 'application/json',
    'HTTP-Referer': referer || 'http://localhost',
    'X-Title': 'SubPirate - Reddit Marketing Analysis',
  },
  body: JSON.stringify({
    model: OPENROUTER_MODEL,
    messages: [
      { role: 'system', content: systemPrompt },
      { role: 'user', content: prompt }
    ],
    temperature: 0.6,
    max_tokens: 35000,
    response_format: { type: 'json_object' }
  })
});
Key parameters:
  • temperature: 0.6 - Balanced creativity/consistency
  • max_tokens: 35000 - Allows comprehensive analysis output
  • response_format: json_object - Ensures structured JSON responses

Analysis Prompt

The system prompt guides the AI analysis:
const systemPrompt = 'You are an expert Reddit marketing analyst. ' +
  'Follow subreddit rules and Reddit policies; ' +
  'do not suggest rule circumvention.';
The user prompt is built from subreddit data in api/_lib/analyze.js (imported as buildAnalysisPrompt).

Quota Management

SubPirate enforces analysis quotas per subscription tier to control OpenRouter costs:

Quota Check

Before each analysis, the system verifies the user hasn’t exceeded their limit:
const quotaCheck = await checkAnalysisQuota(auth.user.id);
if (!quotaCheck.allowed) {
  return {
    error: 'quota_exceeded',
    feature: 'analysis',
    used: quotaCheck.used,
    limit: quotaCheck.limit,
    upgrade_required: true
  };
}
Implementation in api/_lib/subscriptionGate.js:4.

Usage Tracking

After successful analysis, usage is incremented (non-admin users only):
if (!(await isAdminUser(auth.user.id))) {
  const serviceDb = getServiceSupabaseClient();
  await serviceDb.rpc('increment_analysis_usage', { p_user_id: auth.user.id });
}
This updates the subscription_usage table via a database function.

Rate Limits

OpenRouter Rate Limits

OpenRouter applies rate limits based on your account tier:
  • Free tier: ~10 requests/minute
  • Paid tier: ~60 requests/minute
  • Enterprise: Custom limits
Check current limits at https://openrouter.ai/settings/limits.

SubPirate Batch Analysis

When analyzing multiple subreddits, SubPirate:
  1. Uses Web Workers for parallel processing (analysisWorker.ts)
  2. Queues requests to avoid overwhelming OpenRouter
  3. Caches results in IndexedDB to prevent duplicate analyses
Running 50+ concurrent analyses may hit OpenRouter rate limits. The frontend automatically retries with exponential backoff.

Error Handling

The OpenRouter client handles various error scenarios:
if (!result.ok) {
  return {
    statusCode: result.status,
    error: `OpenRouter API error: ${result.status}`,
    details: result.errorText
  };
}
Common errors:
StatusCauseSolution
401Invalid API keyCheck OPENROUTER_API_KEY in .env
402Insufficient creditsAdd credits to OpenRouter account
429Rate limit exceededReduce concurrent requests or upgrade OpenRouter tier
500OpenRouter internal errorRetry request, check OpenRouter status page

Cost Optimization

1. Enable Result Caching

SubPirate caches analysis results in:
  • Client: IndexedDB (analysisIdb.ts)
  • Server: subreddit_analyses table
This prevents re-analyzing the same subreddit multiple times.

2. Set OpenRouter Spend Limits

In OpenRouter settings, configure:
  • Daily spend limit: e.g., $10/day
  • Monthly budget: e.g., $100/month
  • Low balance alerts: Email when credits drop below threshold

3. Monitor Usage

Track costs in OpenRouter dashboard:
  • Usage by model: Identify expensive models
  • Usage by endpoint: See which features consume most credits
  • Anomaly detection: Spot unexpected spikes

Security Considerations

API Key Protection: Never expose OPENROUTER_API_KEY in client-side code. All OpenRouter calls must originate from your server.
Request Origin: SubPirate includes HTTP-Referer and X-Title headers for OpenRouter’s analytics. These help OpenRouter attribute usage to your app.
User Input Validation: The analysis prompt is built server-side. Never pass unsanitized user input directly to OpenRouter.

Testing

Test OpenRouter Connection

Create a test endpoint to verify your API key:
// In server.js or api/ directory
app.post('/api/test/openrouter', async (req, res) => {
  const result = await callOpenRouterChatCompletions({
    apiKey: process.env.OPENROUTER_API_KEY,
    referer: 'http://localhost',
    title: 'SubPirate Test',
    body: {
      model: 'google/gemini-3-flash-preview',
      messages: [{ role: 'user', content: 'Hello, world!' }],
      max_tokens: 100
    }
  });
  
  res.json(result);
});
Expected response:
{
  "ok": true,
  "status": 200,
  "json": {
    "choices": [{
      "message": { "content": "Hello! How can I help you today?" }
    }]
  }
}

Monitor Test Costs

Small test requests typically cost less than $0.001. Check OpenRouter dashboard after testing.

Environment Variables Reference

.env
# OpenRouter API key (server-only)
OPENROUTER_API_KEY=sk-or-v1-...

# Supabase (for quota management)
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_SERVICE_ROLE_KEY=your_service_role_key

Next Steps