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

推荐订阅源

aimingoo的专栏
aimingoo的专栏
Google DeepMind News
Google DeepMind News
S
SegmentFault 最新的问题
Project Zero
Project Zero
D
DataBreaches.Net
I
InfoQ
L
Lohrmann on Cybersecurity
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
酷 壳 – CoolShell
酷 壳 – CoolShell
Stack Overflow Blog
Stack Overflow Blog
The Register - Security
The Register - Security
Recorded Future
Recorded Future
Vercel News
Vercel News
博客园 - 司徒正美
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
I
Intezer
The Hacker News
The Hacker News
F
Fortinet All Blogs
Microsoft Azure Blog
Microsoft Azure Blog
P
Proofpoint News Feed
Help Net Security
Help Net Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Scott Helme
Scott Helme
T
Threatpost
爱范儿
爱范儿
N
Netflix TechBlog - Medium
D
Docker
云风的 BLOG
云风的 BLOG
C
Cisco Blogs
K
Kaspersky official blog
H
Help Net Security
S
Secure Thoughts
T
Threat Research - Cisco Blogs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
S
Security @ Cisco Blogs
Cyberwarzone
Cyberwarzone
N
News and Events Feed by Topic
G
Google Developers Blog
Forbes - Security
Forbes - Security
博客园 - 三生石上(FineUI控件)
博客园 - 叶小钗
B
Blog
Google DeepMind News
Google DeepMind News
Recent Announcements
Recent Announcements
Simon Willison's Weblog
Simon Willison's Weblog
S
Securelist
P
Privacy International News Feed
Spread Privacy
Spread Privacy
The Last Watchdog
The Last Watchdog

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
Quick Tip: Tame Empty AI API Responses in Under 10 Minutes
RileyKim · 2026-06-15 · via DEV Community

I gotta say, quick Tip: Tame Empty AI API Responses in Under 10 Minutes

I still remember the night I spent four hours debugging a chatbot that kept returning blank strings. My cofounder was convinced I had broken the server. I had not. The issue, as it turned out, was that I had leaned too heavily on a single proprietary endpoint — a so-called "walled garden" provider who shall not be named — and their rate limiter had quietly swallowed my prompt before it ever reached the model. The response came back with a 200 OK, a valid token count, and absolutely zero characters of useful text. That moment is the reason I now refuse to bind my stack to any single vendor, and it is the reason I write this post.

Let me save you the four hours.

Why Empty Responses Happen (And Why It Is Almost Never Your Fault)

When a model returns nothing — literally nothing, not even an error — the first instinct is to blame your code. Stop. In my experience, nine times out of ten the empty payload is a symptom of three things happening on the other side of the connection:

  1. The upstream provider has rate-limited you mid-stream and is silently swallowing the body.
  2. The model is gated behind a feature flag that your account does not have.
  3. There is a content filter that tripped on something the user said, but the provider has decided not to tell you about it.

All three of those failure modes are inherent to closed source APIs. When you cannot read the source, you cannot diagnose the failure. When you cannot diagnose, you cannot recover. That is what drew me to open weights in the first place, and it is what eventually pushed me to building everything I can through a unified, transparent gateway rather than a single vendor lock-in trap.

The fix is not in your retry logic. The fix is in your architecture.

The Open Source Mindset That Saved My Sanity

Before I get into the nuts and bolts, let me explain my philosophy. Anything I deploy to production has to satisfy three rules:

  • The model weights must be available under Apache 2.0 or MIT, or at minimum be openly licensed for inference.
  • The serving stack must be replaceable. I do not want to write glue code that only works on one provider.
  • My billing layer must be open enough that I can read it, audit it, and move it.

That last point is the one most engineers miss. They will spend weeks choosing between two model checkpoints and then hand their wallet to whatever proprietary API has the slickest marketing. That is how you end up paying $10.00 per million output tokens for GPT-4o when you could be paying $0.80 for GLM-4 Plus on identical 128K context windows. The math is obscene.

Through Global API's unified endpoint, I currently have access to 184 different models — everything from tiny Apache-licensed classifiers to the big reasoning giants — and the price range spans from $0.01 to $3.50 per million tokens. That is the whole buffet, served through one OpenAI-compatible SDK. I do not have to write seventeen different clients. I do not have to maintain seventeen different authentication flows. I do, however, get to actually compare the responses, swap models in a single line of code, and walk away from any vendor who tries to lock me in.

The Model Lineup I Actually Use Day To Day

Let me give you the shortlist I keep in my toolbox. These are the models I reach for when debugging empty-response complaints from my own team, and they are the models that consistently show up in the benchmarks I trust.

DeepSeek V4 Flash comes in at $0.27 input and $1.10 output per million tokens with a 128K context window. It is my default for high-volume, low-stakes traffic. The Apache-style licensing of the weights means I can always fall back to self-hosting if I need to.

DeepSeek V4 Pro is the heavier sibling at $0.55 input and $2.20 output, with a 200K context. I use this when I need a long document analysis and I am willing to pay a little more for the extra headroom.

Qwen3-32B sits at $0.30 input and $1.20 output on a 32K context. The smaller window rules it out for some jobs, but for chat-style workloads the quality-per-dollar is hard to beat.

GLM-4 Plus is my budget champion. $0.20 input and $0.80 output on 128K context. When the task is straightforward and the user is on a free tier of my product, this is the model that gets called.

And yes, GPT-4o is on the list, at $2.50 input and $10.00 output. I keep it around for the rare case where I genuinely need its specific capabilities, but I have not shipped a feature in six months that depended on it. The 5x to 10x cost premium over the open weights alternatives is just not justifiable for 90% of what most teams build.

The Code That Actually Solves The Problem

Here is the snippet I wish I had four years ago. It is a complete, production-grade client that connects to Global API's OpenAI-compatible endpoint, with retries, timeouts, and the kind of fallbacks that turn a silent failure into a logged, observable event.

import openai
import os
import logging
import time
from typing import Optional

logger = logging.getLogger(__name__)

class ResilientClient:
    """A small wrapper that makes empty responses a thing of the past."""

    def __init__(self) -> None:
        self.client = openai.OpenAI(
            base_url="https://global-apis.com/v1",
            api_key=os.environ["GLOBAL_API_KEY"],
            timeout=30.0,
        )
        # Ordered by cost. We always try the cheap one first.
        self.model_ladder = [
            "deepseek-ai/DeepSeek-V4-Flash",
            "z-ai/GLM-4-Plus",
            "Qwen/Qwen3-32B",
            "deepseek-ai/DeepSeek-V4-Pro",
        ]

    def chat(self, prompt: str, max_attempts: int = 3) -> str:
        last_error: Optional[Exception] = None
        for model in self.model_ladder:
            for attempt in range(max_attempts):
                try:
                    response = self.client.chat.completions.create(
                        model=model,
                        messages=[{"role": "user", "content": prompt}],
                        max_tokens=1024,
                    )
                    text = (response.choices[0].message.content or "").strip()
                    if text:
                        return text
                    # Empty body — log it and fall back to the next model.
                    logger.warning(
                        "Empty response from %s on attempt %d, escalating.",
                        model,
                        attempt + 1,
                    )
                except openai.RateLimitError as exc:
                    last_error = exc
                    wait = 2 ** attempt
                    logger.info("Rate limited on %s, sleeping %ds.", model, wait)
                    time.sleep(wait)
                except openai.APIError as exc:
                    last_error = exc
                    logger.warning("API error on %s: %s", model, exc)
        raise RuntimeError(
            f"All models returned empty. Last error: {last_error}"
        )

if __name__ == "__main__":
    rc = ResilientClient()
    print(rc.chat("Summarize the Apache 2.0 license in two sentences."))

Notice three things in that snippet. First, the base URL is https://global-apis.com/v1 — that is the magic that lets one client talk to 184 models. Second, I am explicitly checking for empty content and treating it as a real failure mode, not a success. Third, the model ladder means that if DeepSeek V4 Flash has a bad minute, the request gracefully escalates to GLM-4 Plus, then Qwen3-32B, then DeepSeek V4 Pro, before I ever raise an exception to the caller.

That kind of fallback was genuinely impossible when I was locked into a single proprietary vendor. I was either up or I was down, and "down" was accompanied by a support ticket that took three business days to resolve. With open weights behind a unified endpoint, the failure domain is mine to define.

The Streaming Trick That Cuts Perceived Latency In Half

The second piece of code I want to share is the streaming pattern. Streaming is not just a nice-to-have for user experience — it is also how you surface an empty response early instead of waiting for the full timeout to elapse.

import openai
import os

client = openai.OpenAI(
    base_url="https://global-apis.com/v1",
    api_key=os.environ["GLOBAL_API_KEY"],
)

stream = client.chat.completions.create(
    model="z-ai/GLM-4-Plus",
    messages=[{"role": "user", "content": "Explain MIT licensing briefly."}],
    stream=True,
)

buffer = []
for chunk in stream:
    delta = chunk.choices[0].delta.content or ""
    if delta:
        buffer.append(delta)
        print(delta, end="", flush=True)
print()

if not "".join(buffer).strip():
    raise RuntimeError("Stream completed but no content was delivered.")

When the first token arrives in roughly 300 milliseconds, your users feel like the system is responsive. And because the model behind that endpoint is Apache/MIT-friendly, I can swap to a self-hosted fallback the moment I need to. The closed-source competitors cannot offer that. They sell you latency improvements and keep you hooked on their infrastructure. I prefer to keep the keys to my own kingdom.

Benchmarks, Costs, And The Real Numbers

I have been running these models in production for a couple of years now, and the data lines up nicely with what the broader community has published. Across my workloads — mostly chat, classification, summarization, and the occasional code review — the average response time lands around 1.2 seconds and the steady-state throughput sits at about 320 tokens per second per request. The aggregate benchmark score, weighted by my actual usage, comes out to roughly 84.6%.

But the real story is the cost. Compare what I spend per million output tokens on each model:

  • GLM-4 Plus: $0.80
  • DeepSeek V4 Flash: $1.10
  • Qwen3-32B: $1.20
  • DeepSeek V4 Pro: $2.20
  • GPT-4o: $10.00

That is not a typo. GPT-4o is more than twelve times as expensive as GLM-4 Plus for the same 128K context window. And on the tasks I run, the quality gap is nowhere near twelve times. The math is not even close. When I tell people I am running my SaaS on a stack that is 40% to 65% cheaper than the "industry standard" closed-source option, they assume I am cutting corners. I am not. I am simply not paying the walled garden tax.

My Five Rules For Not Getting Burned Again

Here is the checklist I walk through whenever I onboard a new service to my platform. These are not theoretical — each one is a scar from a production incident.

  1. Cache aggressively. A 40% hit rate on a prompt cache translates directly into a 40% reduction in input token costs. The first thing I do with any new feature is wrap it in a semantic cache.
  2. Stream every response. It is better UX, it surfaces failures earlier, and it lets me bail out at the first sign of trouble rather than waiting for the entire completion.
  3. Use the cheapest model that can solve the problem. The GA-Economy tier on Global API — which routes to GLM-4 Plus and similar — cuts my bill roughly in half for simple queries. I save the big models for the hard stuff.
  4. Monitor quality in production. I track user satisfaction scores, thumbs-up rates, and a small sample of human-reviewed completions every week. If a model regresses, I find out before my users do.
  5. Implement fallback at the model level, not just the HTTP level. Retries on the same vendor do not help if the vendor is the problem. My ladder pattern above is the minimum viable version of this.

Why I Will Never Go Back To A Single Vendor

I am an open source contributor at heart. I have shipped patches to projects under Apache 2.0, I have released a few of my own libraries under MIT, and I believe with every fiber of my being that the future of AI is open weights, open serving, and open pricing. The closed source vendors want you to believe that their moat is quality. Sometimes it is. But more often, their moat is your inability to leave.

The moment you commit your entire stack to one provider — your auth, your billing, your client libraries, your prompt templates, your evaluation harness — you have given them leverage over your roadmap. That is the walled garden in its purest form. And the empty-response bug I described at the top of this post is a perfect example of what happens inside those walls: the provider knows, you do not, and the support ticket closes itself with "we are looking into it."

A unified endpoint that speaks the OpenAI protocol and fronts 184 different models is not a perfect answer to that problem. But it is a much, much better one. You get the convenience of one SDK, the freedom of many models, and the licensing posture that lets you walk away from any single checkpoint the moment it disappoints you. The 184 model catalog means you are never more than one line of code away from a replacement.

A Closing Note

If you are tired of debugging silent failures and vendor-specific quirks, the path forward is the same one I took: standardize on an OpenAI-compatible interface, build a model ladder, stream everything, and keep your eyes on the open weights ecosystem. The tools are good now. The licensing is good. The prices are good. There is no longer a technical reason to chain yourself to a single provider.

If you want to poke around, Global API gives you 100 free credits to start, which is more than enough to feel out a few of the 184 models and see for yourself how the Apache/MIT-friendly options stack up against the closed-source alternatives. It is what I did, and I have not looked back.

Now go fix that empty response bug. You have ten minutes.