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

推荐订阅源

P
Privacy & Cybersecurity Law Blog
SecWiki News
SecWiki News
T
Troy Hunt's Blog
Y
Y Combinator Blog
V
V2EX
美团技术团队
Last Week in AI
Last Week in AI
S
Security @ Cisco Blogs
IT之家
IT之家
博客园_首页
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
阮一峰的网络日志
阮一峰的网络日志
AI
AI
罗磊的独立博客
人人都是产品经理
人人都是产品经理
H
Hacker News: Front Page
N
News and Events Feed by Topic
P
Privacy International News Feed
V2EX - 技术
V2EX - 技术
Recent Commits to openclaw:main
Recent Commits to openclaw:main
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
GbyAI
GbyAI
L
LINUX DO - 热门话题
C
Cybersecurity and Infrastructure Security Agency CISA
Microsoft Azure Blog
Microsoft Azure Blog
Martin Fowler
Martin Fowler
月光博客
月光博客
WordPress大学
WordPress大学
Latest news
Latest news
Google DeepMind News
Google DeepMind News
S
Schneier on Security
N
Netflix TechBlog - Medium
腾讯CDC
T
Tailwind CSS Blog
TaoSecurity Blog
TaoSecurity Blog
S
Secure Thoughts
L
LINUX DO - 最新话题
Project Zero
Project Zero
Cyberwarzone
Cyberwarzone
D
DataBreaches.Net
Webroot Blog
Webroot Blog
B
Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
S
SegmentFault 最新的问题
The GitHub Blog
The GitHub Blog
H
Help Net Security
L
LangChain Blog
A
Arctic Wolf
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻

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
OpenAI-Compatible APIs Are Great Until Streaming Breaks: What I Check Before Switching Providers
plasma · 2026-06-25 · via DEV Community

Swapping an AI provider looks easy on paper.

Change the baseURL, keep the OpenAI SDK, point your app at a different model, and you're done.

And honestly, for basic non-streaming chat completions, that often works.

But the first place I usually see things break is streaming.

Not because OpenAI-compatible APIs are bad. They're incredibly useful. But "compatible" can mean different things once you move beyond a simple request/response call:

  • chunks arrive in a slightly different shape
  • the first token takes longer than expected
  • proxies buffer the stream
  • usage data is missing from the final response
  • tool calls stream differently
  • errors happen halfway through a stream instead of before it starts

I work on TokenBay, so I spend a lot of time testing OpenAI-compatible model routing across providers. This is the checklist I use before moving a production app from one provider to another.

The part everyone tests

Most people test provider compatibility with something like this:

import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.API_KEY,
  baseURL: process.env.BASE_URL,
});

const response = await client.chat.completions.create({
  model: process.env.MODEL,
  messages: [
    { role: "user", content: "Say hello in one sentence." }
  ],
});

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

If that works, great.

But it doesn't tell you whether streaming works in your actual app.

For a lot of AI products, streaming is not a nice-to-have. It's the difference between "this feels responsive" and "did the app freeze?"

So I test streaming separately.

A minimal streaming test

Here's the smallest script I usually start with.

Create a file called test-streaming.mjs:

import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.API_KEY,
  baseURL: process.env.BASE_URL,
  timeout: 30_000,
});

const model = process.env.MODEL;

if (!model) {
  throw new Error("Missing MODEL env var");
}

const startedAt = Date.now();
let firstTokenAt = null;
let chunkCount = 0;
let contentChunks = 0;
let emptyChunks = 0;
let finalText = "";

const stream = await client.chat.completions.create({
  model,
  stream: true,
  temperature: 0,
  messages: [
    {
      role: "user",
      content:
        "Write a short explanation of why streaming matters in AI apps. Keep it under 80 words.",
    },
  ],
});

for await (const chunk of stream) {
  chunkCount += 1;

  const delta = chunk.choices?.[0]?.delta;
  const content = delta?.content ?? "";

  if (content) {
    if (firstTokenAt === null) {
      firstTokenAt = Date.now();
    }

    contentChunks += 1;
    finalText += content;
    process.stdout.write(content);
  } else {
    emptyChunks += 1;
  }
}

const finishedAt = Date.now();

console.log("\n\n--- streaming diagnostics ---");
console.log({
  model,
  chunkCount,
  contentChunks,
  emptyChunks,
  firstTokenMs: firstTokenAt ? firstTokenAt - startedAt : null,
  totalMs: finishedAt - startedAt,
  chars: finalText.length,
});

Install the SDK:

npm install openai

Then run it against any OpenAI-compatible endpoint:

API_KEY="your_api_key" \
BASE_URL="https://your-provider.example/v1" \
MODEL="your-model-name" \
node test-streaming.mjs

If you're using OpenAI directly, the base URL is usually not needed:

API_KEY="your_openai_key" \
MODEL="gpt-4.1-mini" \
node test-streaming.mjs

If you're testing a gateway such as TokenBay, the idea is the same: keep the OpenAI SDK, change the baseURL, and test the model you actually plan to use.

What I check

I don't just check whether text prints.

That is the first pass, but not enough.

1. Does the first token arrive quickly?

The total response time matters, but streaming UX depends heavily on first-token latency.

If the full response takes 5 seconds but the first token arrives in 600ms, the app feels alive.

If the first token arrives after 5 seconds, streaming is technically working but the UX is basically the same as non-streaming.

In the script above, I look at:

firstTokenMs

For production apps, I usually compare this across:

  • the current provider
  • the new provider
  • the same model through a gateway
  • a fallback model

I don't need perfect lab numbers. I just want to know if the new route is obviously slower before I ship it.

2. Are chunks actually streaming, or being buffered?

This one is sneaky.

Sometimes the SDK receives a stream, but an intermediate layer buffers the response and releases it all at once.

That can happen because of:

  • reverse proxy settings
  • serverless platform behavior
  • CDN buffering
  • incorrect response headers
  • framework abstractions that collect the body before returning it

A rough smell test:

chunkCount
contentChunks
firstTokenMs
totalMs

If firstTokenMs and totalMs are almost identical, I get suspicious.

It doesn't always mean buffering, but it's worth checking.

3. Are empty chunks expected?

Some streaming APIs send chunks that don't contain text content.

That can happen for role metadata, finish signals, tool call deltas, or provider-specific fields.

So I don't treat this as a failure:

emptyChunks > 0

But I do check whether the final assembled text is correct.

The thing I care about is not "every chunk has content." The thing I care about is:

finalText.length > 0

and whether the text is complete.

4. Does your frontend parser assume too much?

A lot of streaming bugs are not provider bugs. They're parser bugs.

For example, a frontend might assume every chunk has this shape:

chunk.choices[0].delta.content

That works for simple text.

But once you add tool calls, JSON mode, or multimodal responses, the stream can include other delta fields.

A safer frontend parser should tolerate chunks where content is missing.

Bad:

const token = chunk.choices[0].delta.content;
render(token.toUpperCase());

Better:

const token = chunk.choices?.[0]?.delta?.content;

if (token) {
  render(token);
}

This sounds tiny, but it saves you from a lot of random "Cannot read properties of undefined" errors during provider migration.

5. What happens when the stream fails halfway through?

Non-streaming calls usually fail before you render anything.

Streaming can fail after you've already shown partial output.

That means your app needs to decide what to do with incomplete text.

I usually test three cases:

  • invalid model name
  • invalid API key
  • forced timeout during a long response

For the timeout case, ask for a longer answer and lower your client timeout.

Example:

const client = new OpenAI({
  apiKey: process.env.API_KEY,
  baseURL: process.env.BASE_URL,
  timeout: 2_000,
});

Then ask for something long:

{
  role: "user",
  content: "Write a detailed 1500-word explanation of streaming APIs."
}

The exact error shape may differ by provider or network path. Your app should not depend on one extremely specific error message.

In production, I care about:

  • showing a clear retry state
  • preserving partial output if useful
  • logging the provider, model, and request ID if available
  • not charging ahead as if the response completed normally

6. Does usage accounting still work?

This is easy to forget.

For non-streaming calls, usage usually comes back in the response object.

For streaming calls, usage may be missing, delayed, provider-specific, or only available from a dashboard/API after the request finishes.

If your product depends on per-request cost tracking, don't assume streaming usage works the same way.

Before switching providers, I check:

  • do I get prompt tokens?
  • do I get completion tokens?
  • do I get total tokens?
  • are streamed requests visible in the provider dashboard?
  • can I reconcile usage later if the stream response doesn't include it?

For internal tools, this may not matter much.

For SaaS apps where you meter customer usage, it matters a lot.

7. Do tool calls stream the same way?

Plain text streaming is the easy case.

Tool calls are where compatibility claims need more testing.

If your app uses tools/function calling, test that separately.

Things I check:

  • are tool call deltas streamed incrementally?
  • are tool names stable?
  • are arguments valid JSON after reconstruction?
  • does the provider send one tool call or multiple?
  • does the final message match what your agent framework expects?

A basic text streaming test passing does not mean your agent loop is safe.

I learned this the annoying way, which is usually how production lessons arrive.

My migration checklist

Before switching an app to a new OpenAI-compatible provider, I run through this:

  • basic non-streaming completion works
  • basic streaming completion works
  • first-token latency is acceptable
  • chunks are not being buffered by my hosting stack
  • empty chunks don't crash the parser
  • timeout and mid-stream errors are handled
  • usage tracking still works for streamed requests
  • tool calls work if the app uses tools
  • fallback behavior is tested with the real model names
  • logs include provider, model, latency, and error details

The main point: don't test only the happy path.

OpenAI-compatible APIs can make provider switching much easier, but streaming is where the abstraction gets tested for real.

Testing this with TokenBay

If you want to test this kind of provider switch without rewriting your OpenAI SDK code, TokenBay is one option.

The setup is intentionally boring:

import OpenAI from "openai";

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

Then you can run the same streaming test against different models by changing the MODEL env var.

TOKENBAY_API_KEY="your_tokenbay_key" \
MODEL="your-model-name" \
node test-streaming.mjs

That's the main reason I like OpenAI-compatible routing: the migration surface area stays small. You can test GPT, Claude, Gemini, Qwen, GLM, or other supported models without changing the rest of your application code.

TokenBay also gives you one place to manage API usage across providers, which is helpful when you're comparing models or setting up fallbacks.

A good first test is:

  • run your current provider directly
  • run the same prompt through TokenBay
  • compare first-token latency
  • check whether chunks stream correctly
  • verify your app handles timeout and partial output states

If those checks pass, then you can start thinking about routing rules, fallback models, and cost optimization.

Try the boring test before switching

The test script in this post is not fancy.

That's the point.

Before I move a real app to a different provider, I want a repeatable check that answers:

  • does streaming actually work?
  • does it feel fast enough?
  • does my parser survive weird chunks?
  • does failure handling behave sanely?

If you want to try the same checklist with TokenBay, you can start here:

https://www.tokenbay.com

Run the script with your own prompts, models, and frontend stack. The useful result is not just "the API call worked." The useful result is knowing whether your app still feels good when streaming, retries, fallbacks, and real users get involved.