惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 司徒正美
M
MIT News - Artificial intelligence
博客园_首页
IT之家
IT之家
L
LangChain Blog
D
DataBreaches.Net
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Google DeepMind News
Google DeepMind News
Blog — PlanetScale
Blog — PlanetScale
人人都是产品经理
人人都是产品经理
博客园 - Franky
云风的 BLOG
云风的 BLOG
罗磊的独立博客
量子位
G
Google Developers Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 【当耐特】
博客园 - 叶小钗
S
SegmentFault 最新的问题
Stack Overflow Blog
Stack Overflow Blog
B
Blog
T
Tailwind CSS Blog
A
About on SuperTechFans
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How I added LLM fallback to my OpenAI app in 10 minutes
Jay · 2026-05-03 · via DEV Community

Jay

How I added LLM fallback to my OpenAI app in 10 minutes

You're running a production app on OpenAI. One Tuesday morning it goes down. Your app returns 500s. You spend an hour refreshing status.openai.com.

There's a better setup. Here's how to add provider fallback to any OpenAI-SDK app without rewriting anything.


The problem with single-provider setups

When you call OpenAI directly, you have one point of failure:

from openai import OpenAI

client = OpenAI(api_key="sk-...")

resp = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Summarise this text..."}],
)

Enter fullscreen mode Exit fullscreen mode

If OpenAI returns a 500 or a 429, your user sees an error. You have no fallback, no visibility into what failed, and no easy way to route to a cheaper provider when you don't need GPT-4 quality.


The fix: two lines and a gateway

InferBridge is an OpenAI-compatible API gateway. You point the OpenAI SDK at it instead of OpenAI directly. It handles routing, fallback, and per-request observability — without touching your application logic.

Step 1: Get an InferBridge key (run once)

# Create an account — returns your InferBridge key exactly once, save it.
curl -X POST https://api.inferbridge.dev/v1/users \
  -H 'Content-Type: application/json' \
  -d '{"email":"you@example.com"}'

# {"api_key": "ib_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", ...}

Enter fullscreen mode Exit fullscreen mode

Step 2: Register your existing OpenAI key

curl -X POST https://api.inferbridge.dev/v1/keys \
  -H 'Authorization: Bearer ib_xxx...' \
  -H 'Content-Type: application/json' \
  -d '{"provider":"openai","api_key":"sk-..."}'

Enter fullscreen mode Exit fullscreen mode

Your key is Fernet-encrypted at rest. InferBridge never logs request content and never marks up inference — your key goes directly to the provider.

Step 3: Change two lines in your app

from openai import OpenAI

client = OpenAI(
    api_key="ib_xxx...",                          # ← was sk-...
    base_url="https://api.inferbridge.dev/v1",    # ← new
)

resp = client.chat.completions.create(
    model="ib/balanced",                          # ← was "gpt-4o-mini"
    messages=[{"role": "user", "content": "Summarise this text..."}],
)

Enter fullscreen mode Exit fullscreen mode

That's it. Your app now has fallback.


What the routing tiers actually do

InferBridge uses explicit routing tiers instead of magic auto-classification:

Tier Chain Use when
ib/cheap Groq → DeepSeek → Together → Sarvam → OpenAI High volume, cost-sensitive, quality flexible
ib/balanced OpenAI → Sarvam → Anthropic Default for most production apps
ib/premium Anthropic → OpenAI Complex reasoning, quality-critical

The router intersects the tier with the provider keys you've registered. So if you only have an OpenAI key, ib/cheap routes to OpenAI. Register a Groq key (free tier available) and the same request code now hits Groq first — no code change.


What fallback looks like in practice

A 500 from OpenAI on ib/balanced is invisible to your app. You get a clean 200 with a normal OpenAI-shaped response. The only signal is in the inferbridge block appended to the response body:

{
  "id": "chatcmpl-...",
  "choices": [...],
  "usage": {...},
  "inferbridge": {
    "provider": "anthropic",
    "model": "claude-3-5-haiku-20241022",
    "mode": "ib/balanced",
    "cache_hit": false,
    "latency_ms": 834,
    "cost_usd": "0.000041",
    "residency_actual": "global",
    "request_id": "abc123"
  }
}

Enter fullscreen mode Exit fullscreen mode

provider: "anthropic" tells you OpenAI failed and Anthropic served it. Your application code didn't change. Your user saw nothing.

If every candidate in the chain fails, you get a clean error:

  • All 429s → 429 rate_limit_error with a Retry-After header
  • Mixed 5xx/timeouts → 502 provider_error or 504 gateway_timeout

Observability you get for free

Every request is logged. Two endpoints give you visibility without a dashboard:

# Aggregated stats
GET /v1/stats
# → totals, cache_hit_rate, breakdown by provider/mode/status

# Paginated request log
GET /v1/logs
# → per-request: provider, model, cost_usd, latency_ms, status, request_id

Enter fullscreen mode Exit fullscreen mode

status can be success, fallback_success, cache_hit, or error. Filter for fallback_success to see exactly when and how often your primary provider is failing.


Optional: add caching for repeated prompts

For deterministic prompts (classification, extraction, templated queries) you can opt into exact-match caching with one header:

resp = client.chat.completions.create(
    model="ib/balanced",
    messages=[...],
    extra_headers={
        "X-InferBridge-Cache": "true",
        "X-InferBridge-Cache-TTL": "3600",  # seconds
    }
)

Enter fullscreen mode Exit fullscreen mode

Cache key is a SHA-256 over provider + model + messages + determinism params. A cache hit returns cache_hit: true in the inferbridge block and costs zero tokens.


What's not built yet (be honest with yourself)

InferBridge is early. Before you adopt it, know the gaps:

  • No dashboard UI — observability is JSON endpoints only
  • Streaming requests bypass the cache
  • No embeddings endpoint
  • No vision inputs
  • No streaming tool use / function calling

If those are blockers for your use case, it's not the right fit yet.


Try it

Free tier is unlimited BYOK. No credit card.

If you run into anything broken or confusing, hello@inferbridge.dev goes to a real inbox.