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

推荐订阅源

T
Tenable Blog
月光博客
月光博客
雷峰网
雷峰网
WordPress大学
WordPress大学
博客园 - 司徒正美
Last Week in AI
Last Week in AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
Visual Studio Blog
H
Help Net Security
Engineering at Meta
Engineering at Meta
Google DeepMind News
Google DeepMind News
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
S
Security @ Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
爱范儿
爱范儿
W
WeLiveSecurity
J
Java Code Geeks
Forbes - Security
Forbes - Security
H
Hacker News: Front Page
T
Threatpost
The Cloudflare Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
N
Netflix TechBlog - Medium
Latest news
Latest news
V2EX - 技术
V2EX - 技术
小众软件
小众软件
T
The Blog of Author Tim Ferriss
A
Arctic Wolf
B
Blog RSS Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
I
InfoQ
C
Check Point Blog
N
News | PayPal Newsroom
Cyberwarzone
Cyberwarzone
V
V2EX
TaoSecurity Blog
TaoSecurity Blog
P
Privacy & Cybersecurity Law Blog
Microsoft Security Blog
Microsoft Security Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
D
DataBreaches.Net
F
Fortinet All Blogs
阮一峰的网络日志
阮一峰的网络日志
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
IT之家
IT之家
K
Kaspersky official blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Google DeepMind News
Google DeepMind News
C
CXSECURITY Database RSS Feed - CXSecurity.com
www.infosecurity-magazine.com
www.infosecurity-magazine.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 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
My LLM API Calls Were Failing Silently. Here's the Logging Setup I Wish I Had Earlier
plasma · 2026-06-26 · via DEV Community

The first few LLM API bugs I hit in production were easy to notice.

The request failed. The user saw an error. I opened the logs, found the stack trace, fixed the obvious thing, and moved on.

The harder bugs were quieter.

The API still returned a response, but it was slower than usual. A fallback model kicked in without anyone noticing. Token usage crept up over a few days. A retry made the request succeed, but doubled the latency. Streaming worked most of the time, except when it didn't.

Nothing looked "down." The app just started feeling worse.

That was when I realized my LLM logging was too thin.

I was logging errors, but not enough context to understand behavior.

The problem with normal API logs

For a typical REST API call, I might log:

  • request path
  • status code
  • latency
  • error message
  • user ID or request ID

That is useful, but LLM calls have a few extra dimensions.

A successful LLM request can still be a problem if:

  • it used the wrong model
  • it silently retried
  • it fell back to another model
  • it returned fewer tokens than expected
  • it took 18 seconds instead of 2
  • it streamed partially, then stopped
  • it cost more than the normal path
  • it failed only for long prompts
  • it failed only for tool calling or JSON mode

If all I log is status: 200, I miss almost everything that matters.

What I log for every LLM call

This is the basic shape I try to capture now:

{
  "event": "llm_request",
  "request_id": "req_123",
  "provider": "tokenbay",
  "model": "gpt-4.1-mini",
  "operation": "chat_completion",
  "status": "success",
  "latency_ms": 1842,
  "input_tokens": 812,
  "output_tokens": 244,
  "estimated_cost_usd": 0.0019,
  "retry_count": 0,
  "fallback_from": null,
  "fallback_to": null,
  "streaming": false,
  "error_type": null,
  "error_message": null
}

For failed requests:

{
  "event": "llm_request",
  "request_id": "req_124",
  "provider": "tokenbay",
  "model": "some-model",
  "operation": "chat_completion",
  "status": "error",
  "latency_ms": 5000,
  "input_tokens": null,
  "output_tokens": null,
  "estimated_cost_usd": null,
  "retry_count": 2,
  "fallback_from": "some-model",
  "fallback_to": "backup-model",
  "streaming": false,
  "error_type": "rate_limit",
  "error_message": "Rate limit exceeded"
}

The exact fields depend on your app, but the categories matter more than the names.

I want to know:

  • what model I asked for
  • what provider handled it
  • how long it took
  • whether retries happened
  • whether fallback happened
  • how many tokens were used
  • whether the request streamed
  • what kind of failure happened
  • roughly how much the request cost

That is the difference between "the AI feature feels slow today" and "requests to model X are retrying twice after 429s, then falling back to model Y."

A small Node.js wrapper

Here is a simple version using the OpenAI SDK.

It works with OpenAI directly, or with any OpenAI-compatible endpoint by changing baseURL.

Install:

npm install openai

Create llm-client.js:

import OpenAI from "openai";
import crypto from "node:crypto";

const client = new OpenAI({
  apiKey: process.env.LLM_API_KEY,
  baseURL: process.env.LLM_BASE_URL || "https://api.openai.com/v1"
});

function nowMs() {
  return Number(process.hrtime.bigint() / 1000000n);
}

function promptHash(messages) {
  const text = JSON.stringify(messages);
  return crypto.createHash("sha256").update(text).digest("hex").slice(0, 16);
}

function classifyError(error) {
  const status = error?.status;

  if (status === 400) return "invalid_request";
  if (status === 401 || status === 403) return "auth_or_permission";
  if (status === 413) return "request_too_large";
  if (status === 429) return "rate_limit";
  if (status === 503) return "service_unavailable";
  if (status === 504) return "upstream_timeout";
  if (status >= 500) return "provider_5xx";

  const message = String(error?.message || "").toLowerCase();

  if (message.includes("context length")) return "context_length";
  if (message.includes("timeout")) return "timeout";
  if (message.includes("content filter")) return "content_filter";

  return "unknown";
}

function logLLMEvent(event) {
  console.log(JSON.stringify(event));
}

export async function createLoggedChatCompletion({
  requestId,
  provider = "default",
  model,
  messages,
  temperature = 0.2,
  maxTokens = 500,
  streaming = false
}) {
  const startedAt = nowMs();

  const baseEvent = {
    event: "llm_request",
    request_id: requestId,
    provider,
    model,
    operation: "chat_completion",
    prompt_hash: promptHash(messages),
    streaming,
    retry_count: 0,
    fallback_from: null,
    fallback_to: null
  };

  try {
    const response = await client.chat.completions.create({
      model,
      messages,
      temperature,
      max_tokens: maxTokens,
      stream: streaming
    });

    const latencyMs = nowMs() - startedAt;

    if (streaming) {
      logLLMEvent({
        ...baseEvent,
        status: "success",
        latency_ms: latencyMs,
        input_tokens: null,
        output_tokens: null,
        estimated_cost_usd: null,
        error_type: null,
        error_message: null
      });

      return response;
    }

    logLLMEvent({
      ...baseEvent,
      status: "success",
      latency_ms: latencyMs,
      input_tokens: response.usage?.prompt_tokens ?? null,
      output_tokens: response.usage?.completion_tokens ?? null,
      estimated_cost_usd: null,
      error_type: null,
      error_message: null
    });

    return response;
  } catch (error) {
    const latencyMs = nowMs() - startedAt;

    logLLMEvent({
      ...baseEvent,
      status: "error",
      latency_ms: latencyMs,
      input_tokens: null,
      output_tokens: null,
      estimated_cost_usd: null,
      error_type: classifyError(error),
      error_message: error?.message || "Unknown error"
    });

    throw error;
  }
}

Use it like this:

import crypto from "node:crypto";
import { createLoggedChatCompletion } from "./llm-client.js";

const response = await createLoggedChatCompletion({
  requestId: crypto.randomUUID(),
  provider: "openai-compatible",
  model: "gpt-4.1-mini",
  messages: [
    {
      role: "user",
      content: "Explain retries and exponential backoff in one paragraph."
    }
  ]
});

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

Run it:

LLM_API_KEY="your-api-key" node app.js

If you use TokenBay, the OpenAI-compatible base URL is:

LLM_API_KEY="your-tokenbay-api-key" \
LLM_BASE_URL="https://api.tokenbay.com/v1" \
node app.js

Same SDK shape. Different base URL.

Do not log raw prompts by default

This part matters.

It is tempting to log the full prompt because it makes debugging easier. I try not to do that by default.

Prompts can contain:

  • user messages
  • emails
  • names
  • customer data
  • internal business logic
  • secrets that users accidentally pasted
  • private documents

Instead, I usually log a hash of the prompt and a few safe metadata fields:

{
  "prompt_hash": "a3f9c01de81b7a22",
  "message_count": 4,
  "has_system_prompt": true,
  "input_chars": 3821
}

That lets me group repeated failures without storing the actual content.

For local development, raw prompt logging can be useful. For production, I want it behind a very explicit flag, with retention rules and access control.

Provider logs are not enough

Provider-side usage logs are useful.

For example, TokenBay's Usage Logs page can show request-level details such as time, model, token count, and cost.

That is helpful, especially when you are using multiple models through one OpenAI-compatible API.

But provider logs usually do not know your application context.

They do not know that this request came from your support reply generator, or that the user had already waited through two failed attempts, or that the answer was discarded before being shown.

That is why I still keep app-side logs.

The provider can tell me what happened at the API layer.

My app logs tell me why it mattered.

The fields that helped me most

Some fields looked boring at first, but ended up being the most useful.

model

This sounds obvious until you have multiple models in production.

If your app can use GPT, Claude, Gemini, Qwen, DeepSeek, GLM, or smaller fallback models, you need to know which one actually handled the request.

Not which one the product team thinks is configured.

The actual model.

provider

This matters when using multiple vendors or an OpenAI-compatible API gateway.

The same model name can behave differently depending on the provider, gateway, account limits, or routing setup.

If latency spikes, I want to know whether it is model-specific or provider-specific.

latency_ms

Average latency is not enough.

I usually want p50, p95, and p99 by model and operation.

A chatbot can feel fine at p50 and awful at p95.

retry_count

Retries are sneaky.

They make reliability look better while quietly increasing latency and cost.

If a request succeeds after two retries, the user may not see an error, but the system still degraded.

fallback_from and fallback_to

Fallback is great until it hides the original problem.

If model A fails and model B saves the request, that is useful. But if it happens 30 percent of the time, I need to know.

Otherwise I might think model A is working fine.

input_tokens and output_tokens

Token usage explains a lot of cost surprises.

When a bill jumps, the cause is often not "the provider got expensive." It is more likely:

  • prompts got longer
  • retrieved context got larger
  • output limits were too high
  • retries increased
  • a more expensive model handled more traffic
  • tool calls caused extra rounds

You cannot see that from request count alone.

error_type

Raw error messages are messy.

One provider says rate_limit_exceeded. Another says Too many requests. Another gives you a 429 with a different body.

I normalize errors into categories:

const errorTypes = [
  "auth_or_permission",
  "invalid_request",
  "rate_limit",
  "request_too_large",
  "context_length",
  "content_filter",
  "provider_5xx",
  "service_unavailable",
  "upstream_timeout",
  "stream_interrupted",
  "unknown"
];

This makes dashboards and alerts much easier.

Silent failures I now watch for

The worst failures are not always exceptions.

These are the ones I try to catch with logs and metrics:

1. Retry storms

A provider starts returning intermittent 429s, 503s, or 504s.

Your retry logic hides it.

The app still works, but latency doubles and costs rise.

Watch:

  • retry count by provider
  • retry count by model
  • p95 latency after retries
  • final status after retry

2. Fallback becoming the main path

Fallback should be the backup plan.

If fallback becomes normal, you may have a provider issue, a bad timeout setting, or a model that is no longer suitable.

Watch:

  • fallback rate
  • fallback source model
  • fallback target model
  • quality complaints after fallback

3. Token creep

This is when prompts slowly get larger over time.

Maybe you added more retrieved documents. Maybe the system prompt grew. Maybe conversation history is not being trimmed.

Nothing breaks immediately. The bill just gets heavier.

Watch:

  • average input tokens by feature
  • p95 input tokens by route
  • output tokens by model
  • token usage per customer or workspace

4. Streaming interruptions

Streaming can fail differently from normal responses.

Sometimes the first tokens arrive, then the stream stops. If you only log the initial request success, you miss the failure.

Watch:

  • stream started
  • stream completed
  • stream duration
  • chunks received
  • interruption reason

5. Model mismatch

This happens when config changes, environment variables drift, or a gateway route points somewhere unexpected.

The app asks for one model, but production traffic goes somewhere else.

Watch:

  • requested model
  • resolved model, if available
  • provider
  • deployment environment

A slightly better log event

After a few rounds, my log event usually grows into something like this:

{
  "event": "llm_request",
  "timestamp": "2026-06-26T08:30:00.000Z",
  "request_id": "req_abc",
  "user_id_hash": "user_91ab",
  "environment": "production",
  "feature": "support_reply_generator",
  "provider": "tokenbay",
  "model": "gpt-4.1-mini",
  "operation": "chat_completion",
  "streaming": false,
  "status": "success",
  "latency_ms": 1842,
  "retry_count": 1,
  "fallback_from": null,
  "fallback_to": null,
  "input_tokens": 812,
  "output_tokens": 244,
  "estimated_cost_usd": 0.0019,
  "prompt_hash": "a3f9c01de81b7a22",
  "error_type": null
}

This is not fancy observability.

It is just enough structure to answer practical questions.

Which feature got slower?

Which model is causing errors?

Did fallback save us or hide a bigger issue?

Did the cost increase because of traffic, tokens, retries, or model choice?

Where TokenBay fits into this

Disclosure: I work on TokenBay, so I am biased here.

One reason I care about this logging shape is that TokenBay is built around using multiple AI models through one OpenAI-compatible API.

That makes it convenient to switch between models, but it also makes observability more important.

TokenBay can show usage details at the API layer. I still want my own application logs because my app knows things the API layer cannot always know:

  • which product feature triggered the request
  • whether the answer was shown to the user
  • whether the request was part of a retry chain
  • whether fallback was intentional
  • whether the user abandoned the flow before the model answered

The more flexible your model setup becomes, the more important boring logs become.

My current rule

For every production LLM call, I want enough information to debug four questions:

  • Why did this request fail?
  • Why was this request slow?
  • Why did this request cost more than expected?
  • Which model actually answered?

If my logs cannot answer those, I am probably flying blind.

The annoying part is that you usually do not notice this on day one.

You notice it later, when something is already weird and your only log line says:

LLM request completed

Ask me how I know.