100% Codebase Verified Last Synchronized: 2026-11-16

RRC Gateway Developer API

A high-throughput, drop-in OpenAI-compatible API proxy that cuts LLM inference costs by up to 90% across OpenAI, Google Gemini, Anthropic Claude, and Groq using Semantic Caching, Virtual Memory Context Optimization, and Autonomous Model Routing.

1. Overview & Architecture

RRC Gateway acts as a transparent, high-speed reverse proxy between your application code and upstream inference providers. It eliminates redundant GPU execution and token bloat before requests ever hit expensive upstream models.

Request Lifecycle & The 3 Optimization Pillars
Pillar 1: Context Trimming
Compresses historical conversation turns and strips boilerplate. Latest user turn preserved 100% untouched.
Pillar 2: Smart Routing
Classifies query complexity in <1ms. Simple queries downscale to high-speed tier models (e.g. GPT-4o-mini, Flash).
Pillar 3: Semantic Cache
Instant sub-15ms return for identical or topical matches (Jaccard similarity ≥ 0.65) in Universal Common DB at $0.00.

2. 60-Second Quickstart

Migrating to RRC Gateway requires changing exactly one line of code in any OpenAI SDK client by pointing base_url to the gateway:

# Before: client = openai.OpenAI()
# After: Point base_url to RRC Gateway!
from openai import OpenAI

client = OpenAI(
    api_key="demo",  # Or your Groq (gsk_*), Gemini (AIza*), or OpenAI (sk-*) key
    base_url="https://gateway.rrcsolutions.me/v1"
)

response = client.chat.completions.create(
    model="openai/gpt-oss-20b",
    messages=[
        {"role": "user", "content": "Explain semantic caching in 2 sentences."}
    ]
)

print(response.choices[0].message.content)

# Access RRC Cost & Token Telemetry directly on the response:
print(f"Cache Status: {response.rrc['cache']}")
print(f"Tokens Saved: {response.rrc['tokens_saved']}")
print(f"Cost Saved:   ${response.rrc['cost_saved_usd']:.6f}")

3. Base URLs & Environments

Environment Base URL Notes
Production Edge https://gateway.rrcsolutions.me/v1 Global Vercel Edge Serverless functions. Sub-15ms edge caching.
Legacy / Preview https://rrc-two.vercel.app/v1 Permanently 308-redirects to gateway.rrcsolutions.me.
Local Runtime http://localhost:8000/v1 FastAPI / Uvicorn server (main.py). Includes benchmark suite.

4. Authentication & Dynamic Provider Routing

RRC Gateway requires standard HTTP Bearer token authentication:

Authorization: Bearer <API_KEY>
Automatic Key Signature Detection

The gateway inspects the prefix of the provided key and automatically routes the request to the corresponding upstream inference engine:

Key Prefix Signature Routed Provider Default Upstream Model
AQ.*, AIzaSy*, AIza* Google Gemini gemini-2.5-flash
gsk_* Groq Cloud openai/gpt-oss-20b
sk-or-v1-* OpenRouter meta-llama/llama-3.1-8b-instruct
sk-ant-* Anthropic (via OpenRouter) anthropic/claude-3.5-sonnet
sk-proj-*, sk-admin-*, sk-* OpenAI gpt-4o-mini
demo, community, public Free Community Pool (Groq) openai/gpt-oss-20b
Zero Secret Exposure Guarantee: Upstream provider keys are utilized in-memory solely for upstream invocation and are never returned in responses, logged in plain text, or shared.
POST Verified Live

/v1/chat/completions

Primary inference proxy endpoint. OpenAI-compatible request payload with automatic 3-pillar cost reduction and enriched rrc telemetry.

Request Headers

Header Type Requirement Description
Authorization string Required Bearer <API_KEY> or Bearer demo
Content-Type string Required application/json
X-RRC-Consent string Optional "true" or "false" (Defaults to "true")

Request Body Schema

Field Type Default Description
messages array<object> Required Array of conversation messages: [{ role: "user"|"system"|"assistant", content: string }]
model string provider default Target model. Frontier models are evaluated by Autonomous Routing.
temperature float 1.0 Sampling temperature (0.0 to 2.0). Forwarded upstream.
max_tokens integer null Maximum completion tokens to generate.
stream boolean false Note: SSE streaming is not supported in current MVP. Must be false.
consent boolean true Set false to opt-out of Common DB caching and persistence.

Example Response (HTTP 200 OK)

{
  "id": "chatcmpl-8a19f0e1c",
  "object": "chat.completion",
  "created": 1731776100,
  "model": "openai/gpt-oss-20b",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Semantic caching eliminates redundant LLM execution by storing and retrieving answers based on conceptual meaning rather than exact string matches."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 28,
    "completion_tokens": 32,
    "total_tokens": 60
  },
  "rrc": {
    "cache": "exact",
    "routed": false,
    "requested_model": "openai/gpt-oss-20b",
    "served_model": "openai/gpt-oss-20b",
    "tokens_prompt": 28,
    "tokens_completion": 32,
    "tokens_total": 60,
    "tokens_compressed": 0,
    "tokens_saved": 60,
    "cost_standard_usd": 0.000023,
    "cost_gateway_usd": 0.0,
    "cost_saved_usd": 0.000023,
    "savings_pct": 100,
    "savings_breakdown": {
      "cache_saved_usd": 0.000023,
      "routing_saved_usd": 0.0,
      "compression_saved_usd": 0.0
    },
    "latency_ms": 11,
    "speed_multiplier": "50x faster (Exact KV Hit)",
    "provider": "groq",
    "model": "openai/gpt-oss-20b",
    "common_db_hit": true,
    "common_db_saved": true,
    "private_mode": false,
    "consent_granted": true
  }
}
GET Verified Live

/v1/models

Universal model auto-discovery endpoint. Dynamically queries the upstream provider matching your API key and returns an OpenAI-compatible catalog with tier ratings and pricing metadata.

curl -X GET https://gateway.rrcsolutions.me/v1/models \
  -H "Authorization: Bearer demo"

Verified Models & Reference Pricing

Model ID Provider Tier Prompt ($/1M) Completion ($/1M)
gemini-2.5-flash Google Gemini Fast & Optimized $0.075 $0.30
gemini-2.5-pro Google Gemini Frontier Reasoning $1.250 $5.00
gpt-4o OpenAI Frontier $2.500 $10.00
gpt-4o-mini OpenAI Tier Downscale $0.150 $0.60
openai/gpt-oss-20b Groq Ultra-Fast Tier $0.100 $0.40
llama-3.3-70b-versatile Groq Frontier Speed $0.590 $0.79
claude-3-5-sonnet Anthropic Frontier $3.000 $15.00
GET Verified Live

/api/auth/config

Provides client applications with verified Supabase credentials for user session authentication and telemetry tracking.

{
  "supabaseUrl": "https://wqayntphckoyjsviuksv.supabase.co",
  "supabaseAnonKey": "sb_publishable_4UugcdV7UkGRVGmpki_0rA_xwxbir0R",
  "hasSupabase": true
}
GET Verified Live

/health

Liveness check reporting gateway operational status.

{
  "status": "ok",
  "custom_backend": null
}
Pillar 1

Pillar 1: Safe Hybrid Context & Prompt Compression

Implemented in compressContext(). Eliminates 20% to 60% of input prompt overhead without modifying user intent:

  • Untouched User Prompt: The user's active, latest turn is left 100% byte-for-byte intact to preserve exact prompt semantics and instructions.
  • Whitespace & Divider Deduplication: Normalizes consecutive newlines (3+ collapsed to 2) and removes repetitive horizontal markdown dividers.
  • Boilerplate Filler Stripping: Strips conversational filler prefixes in past assistant turns (e.g. "Certainly! I'd be glad to help..." or "As an AI language model...").
Pillar 2

Pillar 2: Autonomous Model Routing (Tier Downscaling)

Implemented in classifyComplexity(). Whenever a user requests an expensive frontier model (gpt-4o, claude-3-5-sonnet, gemini-2.5-pro), the classifier evaluates complexity in <1ms:

1. Length Check: ≥ 250 words indicates heavy context → Remains on Frontier model.
2. Systems & Architecture Regex: Matches terms like refactor, concurrency, deadlock, microservice, kubernetes, memory leak → Remains on Frontier model.
3. Multi-block Code Debugging: ≥ 2 code blocks with explicit debugging directives → Remains on Frontier model.
4. Formal Logic & Reasoning: Matches mathematical proof, formal verification, calculus → Remains on Frontier model.
5. Simple Queries: Automatically routed to high-speed tier target (e.g. GPT-4o-mini or Gemini 2.5 Flash), slashing cost by 90%+ at 3.5x faster turnaround.
Pillar 3

Pillar 3: Semantic Caching & Universal Common DB

Powered by an in-memory LRU map bounded at 1,000 entries and globally synchronized with Vercel Blob store (common_db_store.json):

  • Tier 1 (Exact Match): Evaluates SHA-256 and normalized conversation string role:content||... and single-query key.
  • Tier 2 (Semantic Topical Match): Extracts non-stopword keywords and computes combined subset and Jaccard similarity. Matches with score ≥ 0.65 return instantly from cache.
  • Cost & Latency: Cache hits yield 100% token savings ($0.00 cost) and sub-15ms response latency (50x speed multiplier).

6. The `rrc` Telemetry Object Specification

Every chat completion response returns an rrc object detailing economic and performance analytics:

Field Type Example Description
cache string "exact" | "semantic" | "miss" Cache evaluation outcome.
routed boolean true | false True if query was downscaled by Pillar 2 routing.
tokens_saved integer 60 Tokens eliminated via cache hit or context compression.
cost_standard_usd float 0.000450 Baseline cost at standard upstream provider rates.
cost_gateway_usd float 0.000045 Actual net cost billed through RRC Gateway.
cost_saved_usd float 0.000405 Net USD savings achieved on this invocation.
savings_pct integer 90 Percentage savings compared to standard pricing.
latency_ms integer 14 Round-trip execution latency in milliseconds.
common_db_hit boolean true | false True if served from the shared Common DB.
private_mode boolean true | false True if Zero-Trust Private Mode was activated.

7. Response Headers Specification

Header Example Description
X-RRC-Cache EXACT | SEMANTIC | MISS Indicates cache hit type or miss.
X-RRC-Routing DIRECT | DOWNSCALED Indicates whether model was downscaled by Smart Routing.
X-RRC-Tokens-Compressed 18 Input context tokens trimmed by Virtual Memory.
X-RRC-Tokens-Saved 45 Total tokens saved on this request.
X-RRC-Cost-Saved 0.000350 Net dollar savings in USD.
X-RRC-Latency-Ms 12 Total gateway turnaround time in milliseconds.
X-RRC-Common-DB-Hit true | false Shared Common DB cache match indicator.

8. Streaming Support Status

Verified Implementation Status: Streaming Unsupported in Current MVP

In the current production release, Server-Sent Events (SSE) streaming (stream: true) is not supported:

  • In local runtime (main.py), sending stream: true raises HTTP 400 with detail "Streaming not supported in this MVP version".
  • In serverless edge (completions.js), responses are evaluated and cached as atomic JSON documents.
  • Action required: All client requests must omit stream or pass "stream": false. Full SSE streaming chunking is scheduled for the upcoming v1.1 release.

9. Error Codes & Auto-Recovery

HTTP Status Error Code / Type Cause & Resolution
400 Bad Request invalid_request_error Missing or invalid messages array, or streaming requested when unsupported.
401 Unauthorized missing_api_key Missing Authorization header. Pass Authorization: Bearer <key> or Bearer demo.
405 Method Not Allowed method_not_allowed Invoked an unsupported HTTP method (e.g. GET on chat completions). Use POST.
500 / 502 Bad Gateway upstream_error Upstream provider returned an error or timed out.
Automatic Upstream Model Recovery:

If an upstream inference provider returns an unsupported model error (e.g. decommissioned model ID), RRC Gateway automatically catches the error, re-routes the query to openai/gpt-oss-20b, and retries the upstream request so your application code never breaks.

10. Code Examples

cURL

curl -X POST https://gateway.rrcsolutions.me/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer demo" \
  -H "X-RRC-Consent: true" \
  -d '{
    "model": "openai/gpt-oss-20b",
    "messages": [
      {"role": "system", "content": "You are a concise engineering assistant."},
      {"role": "user", "content": "What is the difference between TCP and UDP?"}
    ],
    "temperature": 0.7,
    "max_tokens": 256
  }'

Python (Official OpenAI SDK)

import os
from openai import OpenAI

# Initialize client pointing to RRC Gateway base_url
client = OpenAI(
    api_key=os.environ.get("RRC_API_KEY", "demo"),
    base_url="https://gateway.rrcsolutions.me/v1"
)

response = client.chat.completions.create(
    model="gpt-4o",  # Evaluated by autonomous routing
    messages=[
        {"role": "system", "content": "You are a helpful software engineer."},
        {"role": "user", "content": "How do I optimize database connection pooling?"}
    ],
    extra_headers={"X-RRC-Consent": "true"}
)

# Access generated text
print("Assistant:", response.choices[0].message.content)

# Access rich RRC telemetry
telemetry = response.rrc
print("\n--- RRC Gateway Telemetry ---")
print(f"Cache Result:     {telemetry['cache'].upper()}")
print(f"Model Routed:     {telemetry['routed']} (Served: {telemetry['served_model']})")
print(f"Tokens Saved:     {telemetry['tokens_saved']}")
print(f"Cost Saved:       ${telemetry['cost_saved_usd']:.6f} ({telemetry['savings_pct']}% reduction)")
print(f"Execution Speed:  {telemetry['speed_multiplier']}")

TypeScript / JavaScript (Official OpenAI SDK)

import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.RRC_API_KEY || "demo",
  baseURL: "https://gateway.rrcsolutions.me/v1",
  defaultHeaders: {
    "X-RRC-Consent": "true"
  }
});

async function main() {
  const completion = await client.chat.completions.create({
    model: "openai/gpt-oss-20b",
    messages: [
      { role: "user", content: "Write a high-performance LRU cache in TypeScript." }
    ]
  });

  console.log("Response:", completion.choices[0]?.message?.content);

  // Read RRC Telemetry metadata
  const rrc = (completion as any).rrc;
  if (rrc) {
    console.log(`Cache: ${rrc.cache} | Tokens Saved: ${rrc.tokens_saved} | Savings: ${rrc.savings_pct}%`);
  }
}

main().catch(console.error);

11. Rate Limits & Performance Expectations

RRC Gateway itself is deployed on Vercel's global edge network and imposes no artificial requests-per-minute bottleneck. Rate limits are dictated by the upstream provider associated with your API key:

Community Demo Key ("demo")
Shared rate limit across public playground and benchmarking users (~30 RPM). Suitable for evaluation and testing.
BYOK (Bring Your Own Key)
Inherits your direct tier limits with OpenAI, Groq, Anthropic, or Google Gemini. Semantic cache hits bypass upstream quotas completely!

12. Troubleshooting & FAQ

Q: Why did my request to "gpt-4o" return "gpt-4o-mini" in telemetry?

This is Pillar 2 Autonomous Smart Model Routing in action. The complexity classifier analyzed your query and determined it was a simple Q&A task that does not require expensive frontier weights. It autonomously downscaled to GPT-4o-mini, delivering identical answer quality while saving 94% cost. For complex coding or reasoning prompts, it automatically retains GPT-4o.

Q: How do I completely prevent my prompts from entering the shared cache?

Pass X-RRC-Consent: false as a request header, or include "consent": false in your JSON body. The gateway immediately enables Zero-Trust Private Mode: zero persistence, zero global cache writes, 100% ephemeral.

Q: I received HTTP 401 "missing_api_key". What's wrong?

Ensure your client is transmitting the Authorization: Bearer <API_KEY> header. If you do not have an API key yet, you can pass Bearer demo to test with the free community tier.

13. Verified Changelog

v1.0.0 (Production Release) — 2026-11-16
  • Production migration to gateway.rrcsolutions.me with automated SEO and canonical indexing.
  • Global cache persistence across edge serverless instances via Vercel Blob store.
  • Expanded topical keyword modifiers and standalone query caching.
  • Full OpenAPI 3.1.0 machine-readable specification at /openapi.json for the Codex Benchmark Engine.
  • Comprehensive Developer API Documentation Portal at /docs.
v0.9.0 (Public Beta) — 2026-08-30
  • Initial multi-provider proxy for Groq, Gemini, and OpenAI.
  • Prototype 3-pillar optimization (Virtual Memory, Model Router, Semantic Cache).
  • Supabase usage telemetry logging.
© 2026 RRC Solutions. All rights reserved.