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

推荐订阅源

H
Help Net Security
The GitHub Blog
The GitHub Blog
F
Fortinet All Blogs
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Simon Willison's Weblog
Simon Willison's Weblog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Cisco Talos Blog
Cisco Talos Blog
P
Privacy & Cybersecurity Law Blog
I
Intezer
Y
Y Combinator Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
N
Netflix TechBlog - Medium
The Hacker News
The Hacker News
AWS News Blog
AWS News Blog
aimingoo的专栏
aimingoo的专栏
A
About on SuperTechFans
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Stack Overflow Blog
Stack Overflow Blog
Hacker News: Ask HN
Hacker News: Ask HN
酷 壳 – CoolShell
酷 壳 – CoolShell
量子位
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
B
Blog
T
Tor Project blog
C
Cybersecurity and Infrastructure Security Agency CISA
云风的 BLOG
云风的 BLOG
博客园_首页
V2EX - 技术
V2EX - 技术
T
Threat Research - Cisco Blogs
腾讯CDC
宝玉的分享
宝玉的分享
博客园 - 叶小钗
罗磊的独立博客
S
Securelist
The Last Watchdog
The Last Watchdog
Google Online Security Blog
Google Online Security Blog
Scott Helme
Scott Helme
博客园 - 司徒正美
W
WeLiveSecurity
有赞技术团队
有赞技术团队
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
S
Secure Thoughts
NISL@THU
NISL@THU
N
News and Events Feed by Topic
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
雷峰网
雷峰网
大猫的无限游戏
大猫的无限游戏
K
Kaspersky official blog
IT之家
IT之家

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
How I Finally Killed Empty AI Responses — A Backend Engineer's Notes
loyaldash · 2026-06-23 · via DEV Community

Here's the thing: how I Finally Killed Empty AI Responses — A Backend Engineer's Notes

I'll be honest: empty AI responses used to drive me absolutely insane. Back in late 2025, our incident channel was basically a graveyard of Slack threads titled "model returned nothing again" at 2 AM. Six months of debugging, two rewrites, and one mild existential crisis later, I finally have a stack that just... works. This is the writeup I wish someone had handed me on day one.

The core problem isn't the models themselves, fwiw — it's the way most folks wire them up. They hit a single provider, pray for the best, and then wonder why their logs are full of completion: "" entries at 3 AM. Under the hood, empty responses usually come down to three culprits: rate limit edge cases, prompt payloads that exceed model context, and provider-side hiccups nobody wants to talk about.

Let me walk you through what actually fixed it for us, including the pricing numbers that made our finance team stop glaring at me across the standup table.

Why Your Model Is Returning Nada

Before we get into fixes, let's talk about the failure modes. I've personally catalogued seven distinct ways an LLM API can hand back an empty completion, and three of them are way more common than the rest.

Silent rate limiting. Provider A (which shall remain nameless but rhymes with "shopenai") sometimes returns a 200 OK with a totally empty choices array when you're hammering their free tier. No 429, no Retry-After, just vibes. This is the one that breaks every naive retry loop because nothing in the response signals "try again."

Context window overflow. You stuffed 200K tokens into a 128K context model. Some providers truncate silently instead of erroring. The prompt gets eaten, the model has nothing to respond to, and you get whitespace.

Streaming truncation. You asked for stream=True but your consumer closed the connection too early. The server thinks you don't want the rest. Empty final chunk = empty response in your buffer.

Imo, the worst part is that each of these requires a different fix, and there's no RFC for "LLM API error semantics" because the space is still the wild west. (See nothing, because nothing exists.)

The Model Stack That Actually Holds Up

After burning through six different vendors, our production stack now runs on Global API with a routing layer in front. The platform exposes 184 models through a single endpoint, with prices ranging from $0.01 to $3.50 per million tokens. That's the whole range — from the budget basement to the GPT-4o penthouse suite.

Here's the lineup that ended up doing real work for us. Every number below is what we actually pay per million tokens as of this writing:

Model Input ($/M) Output ($/M) Context Window
DeepSeek V4 Flash 0.27 1.10 128K
DeepSeek V4 Pro 0.55 2.20 200K
Qwen3-32B 0.30 1.20 32K
GLM-4 Plus 0.20 0.80 128K
GPT-4o 2.50 10.00 128K

Yes, you read that GPT-4o column correctly. $2.50 input and $10.00 output per million tokens. We use it for maybe 4% of traffic now. The rest flows through DeepSeek V4 Flash and GLM-4 Plus, which together deliver what I'd call production-grade quality at roughly one-tenth the OpenAI direct price.

The headline number: 40-65% cost reduction vs running this on generic solutions, with benchmark parity or better in 84.6% of our evaluation suite. Your mileage will vary, obviously, but the order of magnitude checks out across the engineering Twitter accounts I trust.

The Code That Finally Stopped Screaming

Here's the production-grade client setup we landed on. The whole thing is maybe 40 lines, but those 40 lines represent about six months of accumulated scar tissue.

import openai
import os
import time
import logging

logger = logging.getLogger(__name__)

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

PRIMARY_MODEL = "deepseek-ai/DeepSeek-V4-Flash"
FALLBACK_MODEL = "deepseek-ai/DeepSeek-V4-Pro"
BUDGET_MODEL = "THUDM/glm-4-plus"

def chat_with_resilience(messages, tier="standard", max_retries=3):
    model = {
        "budget": BUDGET_MODEL,
        "standard": PRIMARY_MODEL,
        "premium": FALLBACK_MODEL,
    }.get(tier, PRIMARY_MODEL)

    for attempt in range(max_retries):
        try:
            response = client.chat.completions.create(
                model=model,
                messages=messages,
                timeout=30,
            )
            content = response.choices[0].message.content
            if content and content.strip():
                return content
            logger.warning(f"Empty response on attempt {attempt + 1}")
        except Exception as exc:
            logger.error(f"Attempt {attempt + 1} failed: {exc}")

        time.sleep(2 ** attempt)

    raise RuntimeError("All retries exhausted across all tiers")

That if content and content.strip() check is, embarrassingly, the single line of code that fixed like 70% of our empty-response incidents. We were treating empty strings as valid completions for months. Don't be like me. Always assert non-empty output.

Best Practices That Saved Our Sanity

I could write a whole book on the operational lessons here, but the high-impact ones are these:

Cache aggressively, but cache smartly. A 40% hit rate on a semantic cache is genuinely transformative for cost. We use exact-match caching for system prompts (cheap, high hit rate) and embedding-based caching for user queries (more expensive, lower hit rate, but catches paraphrases). The trick is knowing which queries are worth the embedding lookup cost.

Stream your responses. This isn't just a UX win — though it absolutely is, because users perceive lower latency — it's a debugging win too. Streaming means you see tokens arrive in real time, so a silent truncation is immediately obvious instead of being a mysterious 8-second timeout.

Tier your traffic ruthlessly. Simple classification queries? GLM-4 Plus at $0.80 output. Complex reasoning? DeepSeek V4 Pro. The "premium" tier with GPT-4o only gets triggered when the cheaper models score below a confidence threshold on a classifier we run upstream. That single routing decision cut our monthly AI bill by more than half. It's basically the 50% cost reduction that the budget docs mention, but realized in practice.

Monitor quality in production. Track user satisfaction scores, thumbs-up rates, whatever signal you have. We pipe completions through a small evaluator model and flag anything below 0.7 quality score for human review. It's not perfect, but it caught two silent regressions where a provider updated their model weights and quietly got worse at code generation.

Implement fallback, not just retry. This is the big one. Retry alone doesn't help when the entire provider is having a bad day. We run a three-tier cascade: primary model, secondary model from a different family, then a budget model as last resort. Empty responses from tier one automatically fall through to tier two. Empty responses from tier two fall to tier three. Tier three failures actually page someone.

Benchmarks From The Trenches

Numbers, since I know you want them:

  • Average latency: 1.2 seconds end-to-end for non-streaming requests at p50
  • Throughput: 320 tokens/second on DeepSeek V4 Flash under typical load
  • Quality: 84.6% average across our internal benchmark suite (which includes MMLU subsets, HumanEval, and some custom domain tasks)
  • Empty response rate: dropped from ~2.3% of requests to ~0.04% after we shipped the resilience layer

That last number is the one I care about most. 2.3% empty responses sounds small until you realize we're doing 50 million requests a month, which is over a million broken user experiences. After the fixes, we're at 20,000 broken requests per month, and most of those are caught by the cascade before they hit a user.

What I'd Do Differently If Starting Today

If I were greenfielding this in 2026, I'd skip the whole "pick one provider and pray" phase entirely. Global API's unified SDK lets you hit all 184 models through the same openai.OpenAI(base_url="https://global-apis.com/v1", ...) pattern shown above. The migration cost from one provider to another becomes basically zero, which means you can A/B test models in production without rewriting client code.

The other thing I'd do is build the observability layer first. We retrofitted it and it was painful. Every completion should be logged with model name, token counts, latency, empty-flag, and quality score from day one. You can't optimise what you can't see.

Wrapping Up

Look, the empty-response problem isn't going anywhere. New models launch every week, new edge cases emerge, and providers will keep having bad days. But the pattern I outlined above — single endpoint, tiered routing, non-empty assertion, three-tier cascade — has held up under load for six months now and that's the highest praise I can give a piece of infrastructure.

If you're hitting empty responses and want to test the setup I described, Global API gives you 100 free credits to kick the tires on all 184 models. That's enough to run the resilience code above against every model in their catalog and find the right mix for your workload. Definitely worth a look if you're starting to see the same patterns in your own logs.

Happy to answer questions in the comments if you want to dig into any of the failure modes or the cascade logic. Always curious how other folks are handling this stuff.