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

推荐订阅源

宝玉的分享
宝玉的分享
Know Your Adversary
Know Your Adversary
T
The Exploit Database - CXSecurity.com
P
Palo Alto Networks Blog
Cloudbric
Cloudbric
Scott Helme
Scott Helme
C
CERT Recently Published Vulnerability Notes
Latest news
Latest news
P
Privacy International News Feed
S
Schneier on Security
Simon Willison's Weblog
Simon Willison's Weblog
S
Security @ Cisco Blogs
N
News | PayPal Newsroom
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
AI
AI
MyScale Blog
MyScale Blog
T
Threat Research - Cisco Blogs
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Cisco Talos Blog
Cisco Talos Blog
AWS News Blog
AWS News Blog
Webroot Blog
Webroot Blog
C
Cisco Blogs
博客园 - 聂微东
S
Security Affairs
Hacker News - Newest:
Hacker News - Newest: "LLM"
C
CXSECURITY Database RSS Feed - CXSecurity.com
The Cloudflare Blog
Hugging Face - Blog
Hugging Face - Blog
P
Privacy & Cybersecurity Law Blog
D
DataBreaches.Net
博客园_首页
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Project Zero
Project Zero
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
The Blog of Author Tim Ferriss
雷峰网
雷峰网
V2EX - 技术
V2EX - 技术
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
I
InfoQ
Engineering at Meta
Engineering at Meta
Y
Y Combinator Blog
V
V2EX
I
Intezer
美团技术团队
TaoSecurity Blog
TaoSecurity Blog
Hacker News: Ask HN
Hacker News: Ask HN
Cyberwarzone
Cyberwarzone
Google DeepMind News
Google DeepMind News
Microsoft Security Blog
Microsoft Security Blog
G
GRAHAM CLULEY

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
The JSON-Mode Prompt Pattern That Survives Claude Version Bumps
Gabriel Anha · 2026-04-27 · via DEV Community

Picture a classification pipeline that has run cleanly for nine months. A new Sonnet release lands, and suddenly a noticeable slice of rows comes back empty. Same prompt, same inputs, same temperature. The diff: the model now likes to preface its JSON with Sure, here's the JSON you asked for:. The downstream regex peels off the first { it finds, hits the first stray brace inside a string value, and quietly returns {} for every row that contains a colon in free text.

The fix is not a better regex. The fix is deleting the regex.

Anthropic now documents native Structured Outputs on the Claude Developer Platform, joining the tool-use-with-strict-schema pattern that has been the durable answer for two years. If your prompts still ask the model to "respond with JSON only please," you are one model version away from a 3 a.m. page. Here's the anti-pattern, why it breaks, and the pattern that survives every version bump.

What brittle JSON prompting actually looks like

This is the pattern that ships in tutorials and bites in production:

import json
import re
import anthropic

client = anthropic.Anthropic()

PROMPT = """You are a support-ticket classifier.
Return ONLY valid JSON in this exact format:
{"category": "...", "priority": "...", "needs_escalation": true|false}
Do not include any other text. Do not wrap in markdown.
The category must be one of: billing, bug, feature, other.
The priority must be one of: low, medium, high.

Ticket: {ticket_text}
"""

def classify(ticket: str) -> dict:
    r = client.messages.create(
        model="claude-sonnet-4-7",
        max_tokens=200,
        messages=[
            {
                "role": "user",
                "content": PROMPT.replace("{ticket_text}", ticket),
            }
        ],
    )
    text = r.content[0].text
    # Strip markdown fences if the model added them.
    text = re.sub(r"^```

(?:json)?\s*|\s*

```$", "", text.strip())
    # Find the first {...} block. The model sometimes wraps in prose.
    m = re.search(r"\{.*\}", text, re.DOTALL)
    return json.loads(m.group(0)) if m else {}

Enter fullscreen mode Exit fullscreen mode

It works. It works on most inputs. It works until one of these happens:

  1. A model upgrade adjusts the assistant's preface style and your prefix-strip misses a new pattern.
  2. A user types a } in a ticket body and your "first {...}" regex closes early.
  3. The model emits priority: "Medium" (capitalized) and your downstream code doesn't normalize.
  4. The model decides one ticket is ambiguous and emits two JSON objects separated by \n\n.
  5. The model truncates at max_tokens=200 mid-string and your json.loads raises.

Every one of these is a real production incident. The common cause: you're asking a probabilistic system to behave like a parser, and patching the cracks in the wrapper code. The wrapper is the bug.

Why "respond with JSON only" gets weaker over time

Each model version adjusts its instruction-following distribution. A subtle behavior, should I put a one-line preamble before the JSON when the user asks for explanation-free output, is noise across versions. Anthropic doesn't promise stability on it, because the broader instruction-following is what they tune.

The Pydantic AI team, which has dealt with every output mode under the sun, documents five output modes precisely because "ask the model nicely" is the weakest one. Their prompted mode (inject the schema in the prompt and hope) is the fallback for models with no better option. Their tool mode (the default) uses the model's tool-calling pathway because it's grammar-constrained on the API side.

Anthropic's structured outputs docs are even more direct: with output_format and a JSON schema, the platform constrains generation at the token level so the response validates against the schema in the normal path. No regex. No preamble-stripping. No "the model added a trailing comma again" Slack thread.

The durable pattern: tool use with a JSON schema

Two equivalent ways to anchor your output in 2026: native structured outputs (newer, simpler API) and tool use with tool_choice forcing a specific tool (older, broadly supported, works on every Claude version that ships tools).

Tool use is what I reach for first because it works across providers. The same shape ports to OpenAI's tool-calling and to Pydantic AI's tool mode without rewriting application code. Here's the same classifier, rewritten:

import anthropic
from pydantic import BaseModel, Field, ValidationError
from typing import Literal

client = anthropic.Anthropic()


class Classification(BaseModel):
    category: Literal["billing", "bug", "feature", "other"]
    priority: Literal["low", "medium", "high"]
    needs_escalation: bool
    reason: str = Field(
        description="One sentence explaining the classification."
    )


CLASSIFY_TOOL = {
    "name": "record_classification",
    "description": (
        "Record the classification for a single support ticket. "
        "Call this exactly once per ticket."
    ),
    "input_schema": Classification.model_json_schema(),
}

SYSTEM = (
    "You classify support tickets. For every ticket, call "
    "`record_classification` exactly once with the structured fields."
)


def classify(ticket: str) -> Classification:
    r = client.messages.create(
        model="claude-sonnet-4-7",
        max_tokens=400,
        system=SYSTEM,
        tools=[CLASSIFY_TOOL],
        tool_choice={"type": "tool", "name": "record_classification"},
        messages=[{"role": "user", "content": ticket}],
    )
    for block in r.content:
        if block.type == "tool_use" and block.name == "record_classification":
            try:
                return Classification.model_validate(block.input)
            except ValidationError as e:
                # Validation should not fail; the schema constrains the model.
                # If it does, log and re-raise. Your schema is the contract.
                raise RuntimeError(
                    f"Schema drift on classify: {e}"
                ) from e
    raise RuntimeError("No tool call in response.")

Enter fullscreen mode Exit fullscreen mode

What changed and why each change matters:

tool_choice={"type": "tool", "name": "record_classification"}. This is the lynchpin. Anthropic's API guarantees the model will call this specific tool. No assistant-text preamble path. No "I'll think about this first" detour. The output is a structured tool_use block, not free text.

Classification.model_json_schema() is the source of truth. The Pydantic model defines the schema and the runtime validator. The schema goes to the API; the validator runs on the response. They cannot drift because they're generated from the same class. Adding a field is one edit, not three.

Literal[...] for enums. The schema produced by Pydantic includes enum: ["billing", "bug", ...]. The model will not return "Billing" or "bugs". The constrained generation path emits a token sequence in the enum. You don't need a normalization step.

max_tokens=400, not 200. Tool inputs include a small structural overhead. Budgeting tightly here was where the original brittle version sometimes truncated and produced parser-incompatible JSON. With tool use, truncation surfaces as a clean API error you can catch and retry, not a malformed string.

No regex anywhere. The wrapper code is six lines: call the model, find the tool block, validate. There is nothing to update on a model bump.

What survives a version bump and what doesn't

Run the brittle version and the durable version against the last several Claude releases on the same eval set, and the error shape is the part that matters.

The brittle version's failure rate tends to drift across versions, sometimes single-digit, sometimes well into double digits. Every version, the failures take a different shape: sometimes empty objects, sometimes capitalization mismatches, sometimes truncation. Each shape needs its own monkey-patch in the wrapper. The wrapper accretes over time and nobody on the team is confident about deleting any of it.

The durable version's shape failure rate stays effectively flat across the same versions. Not because the model is perfect. Because the failure mode is now the API rejecting an invalid schema, which is a 400 you can see in your error budget, not a silent {} that bleeds into your warehouse.

The lesson is not "tool use is more accurate." The lesson is tool use moves the failure mode from silent to loud. A regression in classification quality still happens. That's a different problem you address with evals. But you can no longer be wrong about whether the data shape was valid, and you no longer need a wrapper that pretends to parse arbitrary text.

The migration path for an existing prompt

You probably have a few hundred prompts asking for JSON. You don't need to migrate all of them. Start with the ones that match any of these:

  • It's a classifier or extractor (single-shot structured task).
  • The downstream consumer is code, not a human.
  • The data lands in a database, queue, or another API.
  • The current implementation has a regex, a try/except json.JSONDecodeError, or a "strip markdown fences" helper.

For each one:

  1. Define a Pydantic model (or a JSON schema directly) with Literal enums and Field descriptions. The descriptions are part of the prompt the model sees. Write them as instructions.
  2. Wrap it as a tool with a clear description ("Call this exactly once per ...").
  3. Force the call with tool_choice.
  4. Delete the regex, the markdown stripper, the JSON repair library, and the "I'll just retry on parse error" loop.

Code review the diff for what you removed, not just what you added. The wrapper code disappearing is the actual win.

When you still need free-text output

Not every output is structured. Drafting an email, summarizing a meeting, writing a code review: these are inherently free-text, and forcing them into a JSON shape is an anti-pattern in the other direction. The right move there is a hybrid response: a tool call that records structured metadata (sentiment, topics, recommended action), and a free-text field inside the tool input that holds the body. The structured envelope still gives you parseability; the body still reads like prose.

class EmailDraft(BaseModel):
    subject: str
    body: str = Field(description="Plain text, no markdown.")
    tone: Literal["formal", "neutral", "warm"]
    follow_up_in_days: int | None = None

Enter fullscreen mode Exit fullscreen mode

One tool call, one validated object, one durable contract. The only thing the next model bump can do is improve it.

If this was useful

The Prompt Engineering Pocket Guide has a chapter on durable structured outputs that covers the version-bump failure modes, the tool-use pattern across Anthropic and OpenAI, and the eval setup that tells you when prompt drift is a quality regression versus a shape regression. If your prompts are starting to feel load-bearing, it's the short read.