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

推荐订阅源

L
LangChain Blog
Martin Fowler
Martin Fowler
P
Palo Alto Networks Blog
MongoDB | Blog
MongoDB | Blog
A
About on SuperTechFans
Google DeepMind News
Google DeepMind News
博客园_首页
量子位
小众软件
小众软件
F
Full Disclosure
Vercel News
Vercel News
爱范儿
爱范儿
Engineering at Meta
Engineering at Meta
F
Fortinet All Blogs
博客园 - 聂微东
V
V2EX
Blog — PlanetScale
Blog — PlanetScale
罗磊的独立博客
WordPress大学
WordPress大学
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Tor Project blog
Google DeepMind News
Google DeepMind News
M
MIT News - Artificial intelligence
L
Lohrmann on Cybersecurity
H
Hacker News: Front Page
Spread Privacy
Spread Privacy
AI
AI
C
Cyber Attacks, Cyber Crime and Cyber Security
C
CERT Recently Published Vulnerability Notes
D
Docker
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Recorded Future
Recorded Future
L
LINUX DO - 热门话题
Microsoft Azure Blog
Microsoft Azure Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Latest news
Latest news
W
WeLiveSecurity
Application and Cybersecurity Blog
Application and Cybersecurity Blog
博客园 - 司徒正美
博客园 - 叶小钗
T
Threat Research - Cisco Blogs
P
Privacy International News Feed
O
OpenAI News
Help Net Security
Help Net Security
aimingoo的专栏
aimingoo的专栏
宝玉的分享
宝玉的分享
博客园 - Franky

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
One API Key for GPT, Claude, Gemini, and Qwen: A Practical Guide to OpenAI-Compatible Model Routing
plasma · 2026-06-24 · via DEV Community

If you've built anything serious with LLM APIs, you've probably hit this pattern:

  • GPT is great for one task, but too expensive for another.
  • Claude is better at long-context reasoning, but you don't want to rewrite your whole client.
  • Gemini or Qwen may be good enough for cheaper background jobs.
  • Your app slowly turns into a pile of provider-specific SDKs, env vars, retry logic, and billing dashboards.

Not fun.

The cleanest version of this setup is simple: keep your app speaking the OpenAI API format, but route requests to different models behind the scenes.

That's the idea behind an OpenAI-compatible AI gateway.

Disclosure: I work on TokenBay, an AI model API gateway. This post is based on the setup I usually recommend when developers want access to multiple model families without rewriting their app every time they test a new provider.

The Problem

Most AI apps start with one model provider.

That works fine until you need to optimize for cost, latency, quality, availability, or task type.

For example:

  • Use a strong reasoning model for complex user-facing answers.
  • Use a cheaper model for summarization, tagging, extraction, or internal jobs.
  • Fall back to another provider when one API is slow or unavailable.
  • Test new models without refactoring half your codebase.

The painful part is not calling one API.

The painful part is maintaining five slightly different API integrations.

The Practical Pattern

Instead of wiring every provider directly into your app, you can use an OpenAI-compatible gateway.

Your application keeps using the familiar chat.completions.create() interface.

The only things you usually change are:

  • baseURL
  • apiKey
  • model

That means your app can switch between GPT, Claude, Gemini, Qwen, and other models while keeping most of your code unchanged.

Quickstart with Node.js

Install the OpenAI SDK:

npm install openai

Create a file called index.js:

import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOKENBAY_API_KEY,
  baseURL: "https://api.tokenbay.com/v1"
});

async function main() {
  const response = await client.chat.completions.create({
    model: "gpt-4o-mini",
    messages: [
      {
        role: "system",
        content: "You are a concise technical assistant."
      },
      {
        role: "user",
        content: "Explain model routing in one paragraph."
      }
    ]
  });

  console.log(response.choices[0].message.content);
}

main().catch(console.error);

Run it:

TOKENBAY_API_KEY=your_api_key_here node index.js

If your app already uses the OpenAI SDK, the main migration is usually just the client config:

const client = new OpenAI({
  apiKey: process.env.TOKENBAY_API_KEY,
  baseURL: "https://api.tokenbay.com/v1"
});

That's the whole point.

You should not need a different SDK for every model family just to run a basic chat completion.

Routing by Task Type

Once your app can talk to multiple models through the same interface, you can make routing decisions in code.

Here's a simple example:

function selectModel(taskType) {
  switch (taskType) {
    case "reasoning":
      return "gpt-4o";

    case "cheap_summary":
      return "qwen-plus";

    case "long_context":
      return "claude-3-5-sonnet";

    default:
      return "gpt-4o-mini";
  }
}

Then call the selected model:

async function runTask(taskType, userInput) {
  const model = selectModel(taskType);

  const response = await client.chat.completions.create({
    model,
    messages: [
      {
        role: "user",
        content: userInput
      }
    ]
  });

  return response.choices[0].message.content;
}

This is intentionally boring code.

Boring is good here.

You want model routing to be understandable, testable, and easy to change.

Adding a Fallback

Provider outages happen. Rate limits happen. Weird transient API failures happen.

A basic fallback wrapper can save you from a lot of production pain:

async function completeWithFallback(messages) {
  const models = [
    "gpt-4o-mini",
    "qwen-plus",
    "gemini-1.5-flash"
  ];

  let lastError;

  for (const model of models) {
    try {
      const response = await client.chat.completions.create({
        model,
        messages
      });

      return {
        model,
        content: response.choices[0].message.content
      };
    } catch (error) {
      lastError = error;
      console.warn(`Model ${model} failed, trying next option...`);
    }
  }

  throw lastError;
}

Example usage:

const result = await completeWithFallback([
  {
    role: "user",
    content: "Summarize this customer support ticket in 3 bullet points."
  }
]);

console.log(`Used model: ${result.model}`);
console.log(result.content);

This is not a full production-grade retry system, but it gives you the shape:

  • Try your preferred model.
  • Fall back to another compatible model.
  • Keep the calling code simple.

Where This Helps Most

An OpenAI-compatible gateway is useful when you have multiple LLM workloads inside the same product.

Some common examples:

  • SaaS apps with user-facing AI features
  • Internal support tools
  • AI agents
  • Document summarization workflows
  • Batch extraction jobs
  • Coding assistants
  • Evaluation pipelines
  • Side projects where API cost actually matters

Not every task needs the most expensive model.

A lot of production AI work is routing the right request to the right model at the right cost.

Cost Control

This is where gateways become more than a convenience layer.

Once all requests pass through one API layer, you can start thinking about:

  • Per-task model selection
  • Usage tracking
  • Budget limits
  • Cheaper models for background jobs
  • Higher-quality models only where they matter
  • Fallbacks when a provider is unavailable

TokenBay is built around this workflow: one API key for major model families, OpenAI-compatible requests, and a usage dashboard so you can see what your app is actually spending.

In many cases, routing routine tasks to lower-cost models can reduce API spend without hurting the user experience.

The exact savings depend on your workload and model choices, so I would treat any blanket savings claim with suspicion. Test it against your own traffic.

A Simple Rule of Thumb

When I look at an AI feature, I usually split calls into three buckets:

Task Model Strategy
User-facing reasoning Use a stronger model
Summarization / tagging / extraction Try cheaper models first
Background automation Optimize heavily for cost and latency

You do not need a complicated ML routing system on day one.

A plain function like selectModel(taskType) is enough to start.

Final Thoughts

The best AI API architecture is usually the one that gives you room to change your mind.

Models change. Prices change. Latency changes. Your product changes.

If your code is tightly coupled to one provider, every model experiment becomes annoying.

If your app talks to one OpenAI-compatible interface, you can test and route across GPT, Claude, Gemini, Qwen, and others with much less friction.

That is the real win: not just saving money, but making model choice a runtime decision instead of a rewrite.

For this post, I used TokenBay as the OpenAI-compatible gateway example, but the same routing pattern applies to any gateway that supports the OpenAI API format.

I'd also be curious how other teams are handling model routing today. Are you using a gateway, building your own abstraction layer, or still calling each provider directly?