Skip to content
shenald-devPublic

About

⚡ One API for 20+ LLM providers. OpenAI-compatible, single binary edge gateway, streaming & rate-limiting.

Topics

Resources

Stars

35 stars

Watchers

0 watching

Forks

Repository files navigation

one-api

one-api

Zero-bloat Edge LLM Gateway & Distributed Agent Runtime

Route OpenAI, Anthropic, Gemini, DeepSeek, Groq, Mistral, xAI, Perplexity, Together, and Ollama behind one OpenAI-compatible API with adaptive bandit routing, SimHash LSH caching, virtual keys, MCP, and A2A.

NPM Version NPM Downloads Node 18+ MCP 2025-11-25 A2A 0.2.5 156 Tests Passing License GPLv3

Quick Start · Features · Architecture · Benchmarks · Protocols · Configuration


Quick Start

Run one-api immediately with zero mandatory keys (built-in local fallback included) or supply provider keys via environment variables.

npx @shenald/one-api

Send an adaptive completion request:

curl -X POST http://localhost:3000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "X-Routing-Strategy: fastest" \
  -d '{"model":"auto","messages":[{"role":"user","content":"Explain consistent hashing in 2 sentences."}]}'

Drop into any OpenAI SDK:

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: process.env.ONE_API_KEY || 'local-dev',
  baseURL: 'http://localhost:3000/v1'
});

const res = await client.chat.completions.create({
  model: 'auto',
  messages: [{ role: 'user', content: 'Hello from one-api' }]
});

Features

Capability What It Does Key Controls
Adaptive Bandit + Hedging Scores prompt complexity into fast, smart, or reasoning tiers (model: "auto"), samples Thompson-Sampling posteriors, and races a backup provider if TTFT stalls. X-Routing-Strategy, X-Hedge-Enabled, HEDGE_DELAY_MS
SimHash LSH Cache Two-tier cache combining 0.30µs Tier-1 SHA-256 exact LRU with Tier-2 64-bit SimHash + 4-band LSH semantic matching (135.7x faster than linear scan) plus vector caching on /v1/embeddings. CACHE_ENABLED, SEMANTIC_CACHE_ENABLED, X-Allow-Semantic-Cache
Virtual Keys + Loop Breaker Timing-safe (crypto.timingSafeEqual) sk-oa-... scoped keys with model allowlists, sliding RPM/TPM limits, hard/soft USD budgets, and FNV-1a runaway agent loop protection. ONE_API_KEY, ONE_API_VIRTUAL_KEYS, LOOP_BREAKER_THRESHOLD
Rolling Stream DLP + JSON Cascade Tail-overlap rolling buffer redacts secrets (sk-, sk-ant-, ghp_, AIza, hf_, AKIA, eyJ, PEM, SSN, cards) split across SSE chunks; deterministic JSON repair & Schema validator escalate failures from fast to smart. GUARDRAILS_ENABLED, CASCADE_ENABLED, STREAM_TIMEOUT_MS
MCP 2025-11-25 + A2A Dual-transport MCP Streamable HTTP (GET/POST/DELETE /v1/mcp, sessions, async tasks/*, stdio) alongside native Agent2Agent (/.well-known/agent.json, POST /a2a JSON-RPC & SSE). Mcp-Session-Id, MCP-Protocol-Version, ALLOWED_ORIGINS
Flight Recorder + OTel gen_ai.* Zero-allocation circular ring buffer storing redacted request snapshots for live POST /v1/traces/:id/replay diffing and GET /v1/traces/export OpenTelemetry GenAI spans. FLIGHT_RECORDER_CAPACITY, traceparent, X-Trace-Id

Architecture

  OpenAI SDK / Cursor / MCP Client / A2A Agent
                       │
                       ▼
  ┌─────────────────────────────────────────────────────────────────┐
  │ 1. Auth & Governance   timingSafeEqual(ONE_API_KEY | sk-oa-...) │
  │                        Model allowlist · RPM/TPM · USD budget   │
  │                        FNV-1a Runaway-Loop Breaker (429)        │
  └─────────────────────────────────────────────────────────────────┘
                       │
                       ▼
  ┌─────────────────────────────────────────────────────────────────┐
  │ 2. Guardrails & Router Prompt injection + PII/secret scan       │
  │                        Complexity scorer + Thompson Bandit      │
  └─────────────────────────────────────────────────────────────────┘
                       │
                       ▼
  ┌─────────────────────────────────────────────────────────────────┐
  │ 3. Tiered Hybrid Cache Tier 1: SHA-256 Exact LRU (0.30µs)       │
  │                        Tier 2: 64-bit SimHash + 4-Band LSH      │
  └──────────┬─────────────────────────────────────┬────────────────┘
             │ HIT ($0)                            │ MISS
             ▼                                     ▼
  ┌─────────────────────┐             ┌─────────────────────────────┐
  │ Immediate Response  │             │ 4. Provider Mesh & Hedging  │
  │ + OTel Trace        │             │    Retries · Circuit Breaker│
  └─────────────────────┘             │    TTFT Hedge · JSON Cascade│
                                      └──────────────┬──────────────┘
                                                     │
                                                     ▼
  ┌─────────────────────────────────────────────────────────────────┐
  │ 5. Egress & Telemetry  Rolling-window Stream DLP (128B tail)    │
  │                        Token/cost ledger + Flight Recorder      │
  └─────────────────────────────────────────────────────────────────┘

Providers & Aliases

Provider Example Models Notes
OpenAI gpt-4.1, gpt-4.1-mini, gpt-4o, o3, o4-mini Native REST/SSE, tools, response_format, stream usage
Anthropic claude-sonnet-4, claude-3-7-sonnet, claude-haiku-4-5 /v1/messages, tool & json_schema translation, prompt-cache tokens
Google Gemini gemini-2.5-pro, gemini-2.5-flash, gemini-2.0-flash x-goog-api-key header auth, streaming functionCall & responseSchema
DeepSeek deepseek-chat, deepseek-reasoner, deepseek-r1 OpenAI-compatible + cached-token pricing
Groq / Mistral / xAI / Perplexity / Together llama-3.3-70b-versatile, mistral-large-latest, grok-3, sonar-pro OpenAI-compatible upstream routing with key-pool cooldown
Ollama (Local) ollama/llama3, ollama/qwen, ollama/mistral Native /api/chat with tools, format, num_predict, top_p
Zero-Config Fallback Any model when upstream key is omitted Deterministic local completion & JSON Schema mock synthesis

Built-in aliases: auto (adaptive bandit), fast (gpt-4o-mini), fast-next (gpt-4.1-mini), flash (gemini-2.5-flash), smart (claude-3-5-sonnet-20241022), smart-4 (claude-sonnet-4), frontier (gpt-4.1), reasoning (deepseek-reasoner), reasoner-r1 (deepseek-r1), deep-think (o3), code, vision.


Benchmarks

Measured via npm run benchmark (benchmarks/gateway.bench.js) and npm test on Node.js with zero external mocks inflating hot paths:

Subsystem Metric Latency (p50 / p99) Throughput / Result
Test Suite npm test — 156 / 156 passing (0 failed, 0 skipped)
Tier-1 Exact Cache Canonical SHA-256 LRU 0.30 µs / 0.90 µs 2,821,233 ops/s
Tier-2 SimHash + LSH 4-band LSH vs linear scan (N=2,000) 42.60 µs / 145.00 µs 135.7x faster (18,193 vs 134 ops/s, linear 7,254 µs)
Adaptive Bandit Router Complexity + Thompson select + update 6.60 µs / 33.30 µs 110.4k ops/s (110,434 ops/s)
Guardrails & Stream DLP Secret + prompt-injection scan 1.10 µs / 4.50 µs 630k scans/s (47.24 MB/s)
Flight Recorder Circular ring buffer write 0.40 µs / 1.40 µs 1.96M traces/s (1,956,922 traces/s)
OTel gen_ai.* Export 500-span batch serialization 0.152 ms / 1.875 ms 1,916,286 spans/s
Structured Output repairJson + validateJsonSchema 16.50 µs / 73.00 µs 48,907 ops/s
MCP Dispatch JSON-RPC tools/call 4.20 µs / 11.70 µs 190,197 calls/s
Memory Profile 51,000+ gateway operations 11.81 MB → 12.58 MB +0.77 MB heap delta

Protocols & CLI

MCP (2025-11-25 Stdio & Streamable HTTP)

Add one-api as an MCP server in Claude Desktop or Cursor:

{
  "mcpServers": {
    "one-api": {
      "command": "npx",
      "args": ["@shenald/one-api", "mcp"],
      "env": {
        "OPENAI_API_KEY": "sk-...",
        "ANTHROPIC_API_KEY": "sk-ant-...",
        "GOOGLE_API_KEY": "AIza..."
      }
    }
  }
}

Streamable HTTP is available at POST / GET / DELETE /v1/mcp (and /mcp) with Mcp-Session-Id, MCP-Protocol-Version (2025-11-25 or 2024-11-05), Origin validation (403), and async tasks/* execution across 6 tools (oneapi_chat_completion, oneapi_list_models, oneapi_evaluate_guardrails, oneapi_calculate_cost, oneapi_inspect_gateway, oneapi_get_traces), 4 resources, and 2 prompt templates.

Agent2Agent (A2A)

# Public Agent Card discovery
curl http://localhost:3000/.well-known/agent.json

# JSON-RPC 2.0 task execution (supports message/send, message/stream, tasks/get, tasks/cancel)
curl -X POST http://localhost:3000/a2a \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"message/send","params":{"model":"auto","message":{"role":"user","parts":[{"kind":"text","text":"Check gateway status."}]}}}'

Virtual Keys & Trace Replay

# Create a scoped sk-oa-... virtual key (requires master ONE_API_KEY or admin key)
curl -X POST http://localhost:3000/v1/keys \
  -H "Authorization: Bearer $ONE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name":"agent-worker","models":["gpt-4.1-mini","auto"],"rpm":60,"tpm":100000,"budgetUsd":5.0,"softBudgetUsd":4.0}'

# Replay a captured flight trace against another model and inspect latency/cost/output diff
curl -X POST http://localhost:3000/v1/traces/<TRACE_ID>/replay \
  -H "Content-Type: application/json" \
  -d '{"model":"claude-sonnet-4"}'

CLI Commands

npx @shenald/one-api start --port 3000   # Start HTTP / SSE / MCP / A2A gateway + /dashboard
npx @shenald/one-api mcp                 # Run stdio MCP server
npx @shenald/one-api chat auto           # Interactive REPL (/auto, /json, /stats, /model)
npx @shenald/one-api doctor              # Inspect providers, router, governance & protocols
npx @shenald/one-api benchmark           # Run the 9-part performance benchmark suite

Configuration

Copy .env.example to .env or pass variables directly to docker run -p 3000:3000 shenald/one-api.

Environment Variables Reference (Routing, Cache, Governance, Security, Tracing)
Variable Default Description
PORT / HOST 3000 / 0.0.0.0 Gateway listen port and bind address
ONE_API_KEY "" Master Bearer key verified with crypto.timingSafeEqual
ONE_API_VIRTUAL_KEYS "" JSON array/map of pre-seeded scoped virtual keys (sk-oa-...)
LOOP_BREAKER_THRESHOLD 6 Identical prompt+tool repeats in 60s before HTTP 429 agent_runaway_loop
ADAPTIVE_ROUTING_ENABLED true Enable complexity + Thompson-sampling routing for model: "auto"
HEDGE_ENABLED false Enable TTFT-triggered hedged requests globally
HEDGE_DELAY_MS 350 Wait time in ms before launching secondary hedged request
HEDGE_BUDGET_RATIO 0.10 Token-bucket hedge budget refill ratio per call
CASCADE_ENABLED true Escalate unrepairable response_format or refusal results to smart tier
REQUEST_TIMEOUT_MS 60000 Upstream HTTP request timeout in ms
STREAM_TIMEOUT_MS 60000 Mid-stream idle/stall watchdog timeout in ms
CACHE_ENABLED / SEMANTIC_CACHE_ENABLED false / true Toggle Tier-1 Exact LRU and Tier-2 SimHash + LSH semantic cache
CACHE_TTL_SECONDS / CACHE_MAX_ENTRIES 300 / 1000 Cache entry TTL and O(1) LRU capacity
SEMANTIC_CACHE_THRESHOLD 0.80 Minimum Jaccard similarity for Tier-2 semantic cache hits
GUARDRAILS_ENABLED / GUARDRAILS_ACTION false / redact Enable secret/PII scanning (redact or block)
GUARDRAILS_INJECTION_CHECK false Enable heuristic prompt-injection detection
FLIGHT_RECORDER_CAPACITY 1000 Circular trace ring buffer capacity (1–100000)
ALLOWED_ORIGINS "" Comma-separated CORS and MCP Origin allowlist
RATE_LIMIT_RPM 0 Per-IP sliding-window RPM limit (0 = disabled)
Extended HTTP Endpoints & Request/Response Headers
Endpoint Method Purpose
/v1/chat/completions POST OpenAI-compatible completions, SSE, tools, response_format, routing & hedging
/v1/embeddings POST OpenAI/Gemini/local 1536-dim embeddings with X-Cache vector caching
/v1/models & /v1/models/:model GET Unified model, virtual alias, and live adaptive bandit catalog
/v1/keys & /v1/keys/:id GET / POST / DELETE Virtual key creation, masked inspection, and revocation (admin role)
/v1/mcp & /mcp GET / POST / DELETE MCP 2025-11-25 Streamable HTTP & session management
/.well-known/agent.json & /a2a GET / POST A2A Agent Card discovery and JSON-RPC 2.0 task execution
/v1/traces, /v1/traces/stats GET Flight trace search (model, status, errorsOnly) & latency percentiles
/v1/traces/:id/replay & /v1/traces/export POST / GET Live trace replay diffing and OpenTelemetry gen_ai.* JSON export
/v1/metrics, /v1/cache/clear GET / POST Gateway telemetry, bandit posteriors, circuit states, and cache flush
/dashboard, /health, /health/detailed GET Embedded live dashboard and health probes

Per-Request Headers: X-Routing-Strategy (balanced | fastest | cheapest | reliable), X-Adaptive-Routing, X-Hedge-Enabled, X-Allow-Semantic-Cache, X-Cache-Bypass.

Telemetry Headers: X-Served-By-Model, X-Token-Cost-USD, X-Routing-Tier, X-Complexity-Score, X-Cache, X-Cache-Type, X-Cache-Similarity, X-Hedged, X-Hedge-Winner, X-Cascade-Applied, X-Fallback-Applied, X-Budget-Remaining-USD, X-Budget-Warning, X-Guardrails-Violated, traceparent, X-Trace-Id.


License

GNU General Public License v3.0 (GPL-3.0-or-later). See LICENSE.

About

⚡ One API for 20+ LLM providers. OpenAI-compatible, single binary edge gateway, streaming & rate-limiting.

Topics

Resources

Stars

35 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages