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

推荐订阅源

Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
WordPress大学
WordPress大学
云风的 BLOG
云风的 BLOG
Stack Overflow Blog
Stack Overflow Blog
MongoDB | Blog
MongoDB | Blog
腾讯CDC
V
V2EX
Martin Fowler
Martin Fowler
A
About on SuperTechFans
大猫的无限游戏
大猫的无限游戏
Blog — PlanetScale
Blog — PlanetScale
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
酷 壳 – CoolShell
酷 壳 – CoolShell
C
Check Point Blog
博客园 - 【当耐特】
Cisco Talos Blog
Cisco Talos Blog
The Hacker News
The Hacker News
K
Kaspersky official blog
Security Latest
Security Latest
H
Help Net Security
博客园_首页
美团技术团队
Spread Privacy
Spread Privacy
博客园 - 司徒正美
Hugging Face - Blog
Hugging Face - Blog
S
SegmentFault 最新的问题
G
Google Developers Blog
NISL@THU
NISL@THU
爱范儿
爱范儿
I
Intezer
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
阮一峰的网络日志
阮一峰的网络日志
N
News and Events Feed by Topic
P
Privacy International News Feed
Application and Cybersecurity Blog
Application and Cybersecurity Blog
S
Security @ Cisco Blogs
Schneier on Security
Schneier on Security
雷峰网
雷峰网
人人都是产品经理
人人都是产品经理
V
Vulnerabilities – Threatpost
W
WeLiveSecurity
P
Palo Alto Networks Blog
G
GRAHAM CLULEY
Hacker News: Ask HN
Hacker News: Ask HN
I
InfoQ
The Cloudflare Blog
F
Full Disclosure
SecWiki News
SecWiki News
宝玉的分享
宝玉的分享
N
Netflix TechBlog - Medium

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
Don't Let Claude Haiku Do the Math — A Two-Stage Read-Aloud Coach Design, and the Prompt Swamp
Uya · 2026-06-18 · via DEV Community

Uya

Uya

Posted on • Originally published at zenn.dev

📝 Originally published in Japanese on Zenn. This is the English version.
Canonical: https://zenn.dev/uya0526_design/articles/satellite2_haiku-coaching

📚 This is satellite article #2 in my "Read-Aloud Speed Meter dev log" series. For the whole picture, see the main article; for the AmiVoice integration, see satellite #1.

Where This Sits

This article covers the part of the read-aloud speed meter that hands the measured numbers to Claude Haiku to generate coaching as "one compliment + one improvement."

Many articles that use generative AI just dump it on the model: "here's the recognized text, evaluate it nicely." This article is the opposite. Don't let the LLM do the math. All computation and rule-based decisions are settled in code, and Haiku only does the wording. I'll go through how I designed this "two-stage" split, and which swamps I sank into during implementation.

Four things:

  • Why "code does the math, Haiku only does the wording" (the role-split design)
  • The finalized prompt, and the messages / system / cache_control implementation
  • First-hand findings: the prompt cache that didn't work
  • The moment real data slapped me with "written in the prompt ≠ obeyed"

💡 I'm an ex-Java engineer learning TypeScript in public, so I drop in Java comparisons.


Why Not Let Haiku Do the "Math"?

Up front: Haiku is more than enough for feedback generation — in fact, you can shape the task into something Haiku is good at. The key is the role split.

I settle all the metric computation (speaking speed, stagnation rate, threshold decisions) entirely in code. So by the time it reaches Haiku, it's already settled facts like this (below is from running labelMetrics on a real measurement — reading the Heike sample during development; stagnationRate is a number for percentage display):

{
  "pureSpeakingSpeed": 322,
  "pureSpeakingSpeedEvaluation": "slightly fast",
  "stagnationRate": 0,
  "stagnationRateEvaluation": "few"
}

Haiku's only job is to translate these numbers and labels into warm, concrete words. That's exactly what small models are best at — wording, summarizing, tone — and it demands no numeric precision.

Conversely, I clearly decided what not to let Haiku do:

  • Precise numeric computation (deriving speed or scores) → done in code
  • Multi-step threshold branching (judging "is 322 chars/min fast?") → code interprets it as "slightly fast" before passing it on

Java comparison: This is exactly the separation of the Service layer (computation = code) from the presentation layer (wording = Haiku). Just as you don't write business logic in a template engine, I draw the line at "don't make the LLM write the decisions."

This split has a practical benefit beyond cost: pushing threshold decisions into code makes the output stable. Asking Haiku to judge "is this fast?" every time wavers with its mood, but passing it the label "slightly fast" leaves only the wording free to vary.


The Finalized Prompt

Here's the system prompt (a static coach persona). After running it against real data several times, it settled into this shape. (Translated here for readability; the production version is in Japanese.)

You are a kind, specific coach who reviews Japanese read-aloud practice.

# Premises (strict)
- The JSON you receive is already-computed, already-evaluated fact.
- Do not recompute numbers. Do not invent new metrics. Do not fill in
  facts that aren't in the JSON by guessing.
- Speak only on the basis of what's written in the JSON.
- Do not mention punctuation (samples can be short and may contain none).

# Output format (strict)
- Polite register. Warm, calm tone.
- No emoji, symbols, line breaks, headings, or preamble. Output exactly two sentences.

# Output format (best-effort)
- About 100 Japanese characters total.

# Output content
Sentence 1: Pick the single best point and praise it concretely.
Sentence 2: Give exactly one improvement, as a concrete action to try next.

# How to pick the improvement (top-down; only the first that matches)
1. "stagnationRateEvaluation" is "somewhat many" or worse → how to use pauses (ma)
2. "pureSpeakingSpeedEvaluation" is "slightly slow"/"slow" → ease the tempo forward
3. "pureSpeakingSpeedEvaluation" is "slightly fast"/"fast" → consciously take a breath and read slower
4. None apply → pick the one most-improvable point and frame it positively as the next goal

Three notes on the intent:

  • I prioritize the improvements and emit only the first match. I also added a fourth branch (a fallback) so the model isn't forced to hunt for flaws when everything is good.
  • Without explicitly saying "exactly two sentences," it tacks on preamble or bullet points. I lock the purity of the output via the prompt.
  • "About 100 chars" is a best-effort goal. I explain why below, but it's because LLMs can't count Japanese characters precisely.

API Implementation: system / messages / cache_control

I call it via messages.create from the Claude Messages API (@anthropic-ai/sdk).

const result = await client.messages.create({
  model: process.env.ANTHROPIC_MODEL!, // e.g. claude-haiku-4-5
  max_tokens: 256,
  system: [
    {
      type: "text",
      text: FEEDBACK_PROMPT,
      cache_control: { type: "ephemeral" }, // goes inside the system block
    },
  ],
  messages: [
    { role: "user", content: JSON.stringify(feedbackFacts) }, // settled facts only
  ],
});

What the structure means:

  • system = Claude's persona and ground rules (outside the conversation). The static coach persona lives here.
  • messages role: "user" = the actual conversational input (the evaluation JSON that changes each time).
  • role is either "user" (your input) or "assistant" (Claude's reply). This is a single round-trip, so one user entry is enough.

Java comparison: A fixed system prompt plus a variable user payload is like passing request/response pairs as an array. For multi-turn conversations, you stack the history in order.

How to think about max_tokens

I initially set 1024, copied from an official example, but this output (two sentences) measured at about 88 tokens. max_tokens is "the maximum you may generate," not "the amount you must generate," so a generous value does almost no harm — generation stops naturally when the output ends. As a safety valve against unintended long output, I tightened it to 256 as in the code above.

Java comparison: It feels close to StringBuilder's initialCapacity. Reserving large doesn't cost anything if you don't use it.


Swamp ① — The Prompt Cache "Didn't Work"

Here's where the first-hand, verify-it-yourself finding begins.

Since the static system prompt is identical every time, I figured I could make it cheaper with prompt caching. I added cache_control: { type: "ephemeral" }, did the break-even math (cache writes cost 1.25× the first time, reads are ~90% off afterward, so "it pays off after two uses"), and concluded "I should use this."

But it wasn't actually working.

The reason is a minimum-token wall. Claude Haiku 4.5's minimum cacheable size is 4,096 tokens. My system prompt was a few hundred tokens — below the threshold. Even with cache_control written, nothing was being cached.

You can check via the response usage:

console.log(result.usage);
// cache_creation_input_tokens: 0
// cache_read_input_tokens: 0   ← if both are 0, nothing was cached

Both were 0. I was so absorbed in the break-even math that the underlying minimum-token condition was my blind spot.

Writing cache_control does no operational harm (it's simply ignored). But writing "I optimized it with caching" in this app would be false. I decided the most honest — and most useful to the reader — thing was to keep it as a verification process: I thought it would help, checked, found it didn't meet the conditions, and it didn't help.

💡 Lesson: "The official feature exists" and "it helps in my use case" are different problems. If you don't check the preconditions — like a minimum token count — you can end up thinking you optimized while doing nothing.


Swamp ② — "Written in the Prompt ≠ Obeyed"

The other swamp. Reading with real data, this happened:

  • Read a short ~10-second sample → the recognized text contains no punctuation
  • Yet Haiku tacked on a concrete tip that wasn't in the input: "take a breath at the punctuation"

The cause was that the finalized prompt's rules had punctuation-dependent wording like "settle at the punctuation." As a fix, I:

  1. Added one line to the premises: "do not mention punctuation"
  2. Changed rule 3 from "settle at the punctuation" → "consciously take a breath and read slower" (punctuation-independent wording)

But there's no guarantee this is obeyed 100%. LLMs can probabilistically break even a "do not ~" prohibition.

In fact, the same run had another wobble. The input was stagnation "somewhat many" + speed "slow," which by the rules should prioritize rule 1 (how to use pauses). But the output leaned toward rule 2 (tempo forward). This surfaced the limit of a design that writes the priority decision into the prompt and lets Haiku choose.

What kicked in here is the same shape as a past lesson: "a passing test ≠ behaving as intended." It's not about whether you instructed it, but whether you verify against real data that it was obeyed. "Written in the prompt" does not equal "obeyed."

Java comparison: It's the same as writing "returns within 100 characters" in a method's Javadoc but still validating on the caller side. Writing a spec and the spec being upheld are separate things. Whether it was upheld is checked on the caller side (in code).

If you want stability, "settle it in code and pass it in"

To make the output fully stable, you can decide which improvement to emit in code and pass it as a single field like { "improvementFocus": "how to use pauses" }. Then Haiku can focus only on wording, and the priority wobble disappears.

Approach Detail Trade-off
A (used this time) Write the priority in the prompt, let Haiku choose Looks smart, but wobbles
B Settle the improvement focus in code, pass as one field Stable output, but rigid

Due to the deadline I left it on approach A this time (watching it after the prompt fix), but I have a clear sense that if the wobble stands out in production, leaning to B is the sure bet. This too was a design-decision point: "looking smart vs. being stable."


How to Handle the Character Limit (Phase 1)

Having Haiku itself count "within 100 chars" isn't trustworthy. LLMs can't count Japanese characters precisely and routinely return over the limit. In Phase 1:

  • Keep the prompt's "about 100 chars" as a best-effort goal
  • Hold the actual ceiling with max_tokens: 256
  • Code-side validation (like truncating on overflow) is not implemented in Phase 1 (a future option)

As with swamp ②, the state here is "the prompt is the spec; the strict guarantee isn't in code yet."


What I Implemented Myself / What I Asked AI For

Area Detail
My decisions / implementation The role split (compute = code / wording = Haiku), the finalized prompt text, the improvement priority order, the max_tokens value, the cache verification, isolating and fixing the punctuation issue, the A/B trade-off judgment
Asked AI for The messages.create skeleton, how to write the system array + cache_control, an example of how to check usage
Fixed on AI's pointer Putting cache_control inside the block rather than on a string system, a sensible max_tokens value, observing the punctuation wobble

The prompt text, the role split, and the verification decisions are all mine. I ran it against real data, sank into the swamps, and isolated and fixed them myself.


Wrapping Up

This was my design for generating read-aloud coaching feedback with Claude Haiku. Three takeaways:

  1. A two-stage design — code does the math, Haiku only does the wording. Keep the LLM on its best skill, translation, and settle the decisions in code.
  2. Prompt caching didn't work in this app (it doesn't reach Haiku's 4,096-token minimum). If you don't check the preconditions, "optimizing" becomes "pretending to."
  3. Written in the prompt ≠ obeyed. Verify the punctuation and priority wobbles against real data, and if you need stability, push the decisions into code.

The thread running through it all is one point: instruction and verification are separate. A prompt is a spec, not a guarantee — on that premise, keeping your verification in code and real data is, I believe, the honest stance when using generative AI in a real product.

The detailed development log is in the repository's LEARNING_LOG_Phase1_Step4.md.

Next time I dig into the rationale behind the metrics — on what basis I set the speed and stagnation-rate thresholds → satellite #3, "The rationale behind the metrics" (https://dev.to/uya0526design/i-went-looking-for-the-basis-of-n-characters-per-minute-is-fast-there-wasnt-one-setting-4967).


This article is part of my public learning journey using AI tools (Claude / Cursor). The design, prompt, and verification decisions are mine, and the output is checked against real data. I collaborate with AI on the article's structure, outline, and draft prose, and I review and revise every line before publishing.