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

推荐订阅源

Recent Announcements
Recent Announcements
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
量子位
博客园 - 司徒正美
Security Archives - TechRepublic
Security Archives - TechRepublic
P
Palo Alto Networks Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Cyberwarzone
Cyberwarzone
小众软件
小众软件
T
Threatpost
Latest news
Latest news
J
Java Code Geeks
博客园 - Franky
博客园 - 三生石上(FineUI控件)
Project Zero
Project Zero
P
Privacy & Cybersecurity Law Blog
T
Tenable Blog
L
Lohrmann on Cybersecurity
大猫的无限游戏
大猫的无限游戏
WordPress大学
WordPress大学
Apple Machine Learning Research
Apple Machine Learning Research
Scott Helme
Scott Helme
Simon Willison's Weblog
Simon Willison's Weblog
C
CXSECURITY Database RSS Feed - CXSecurity.com
P
Privacy International News Feed
人人都是产品经理
人人都是产品经理
S
Schneier on Security
T
The Blog of Author Tim Ferriss
V
V2EX
有赞技术团队
有赞技术团队
Y
Y Combinator Blog
罗磊的独立博客
IT之家
IT之家
雷峰网
雷峰网
H
Help Net Security
C
Cyber Attacks, Cyber Crime and Cyber Security
T
Tor Project blog
C
Cybersecurity and Infrastructure Security Agency CISA
I
InfoQ
GbyAI
GbyAI
博客园 - 叶小钗
PCI Perspectives
PCI Perspectives
The GitHub Blog
The GitHub Blog
Martin Fowler
Martin Fowler
H
Heimdal Security Blog
Spread Privacy
Spread Privacy
博客园_首页
A
About on SuperTechFans
T
Tailwind CSS Blog
The Register - Security
The Register - Security

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
Building AI Explain for 260+ calculators (without going broke)
Vlad Mihalac · 2026-05-19 · via DEV Community

Users abandon calculator pages because raw numbers don't tell them what to do.

A debt-to-income ratio of 0.42 means nothing without context. Neither does a body fat percentage of 22%, a TDEE of 2,180 calories, or a sous vide time of 4 hours at 56°C. The user gets the number. Then they wonder "ok, but what now?"

We built AI Explain to fix that. Click a button, get a 100-word breakdown in plain English of what your number means and what to do with it. Available on every tool, in all 7 languages.

The problem: doing this for 260+ tools, with growing volume, on a free tier, without burning thousands in API costs.

This article covers how the system actually works, including the caching layer that kept it economically viable.

Why WordPress (yes, really)

First, the unconventional stack choice. Most devs would default to Next.js for something this app-like. We picked WordPress + custom theme + custom REST endpoints. Here's why, and the honest tradeoffs.

What WordPress gave us for free:

  • Polylang handles 7 languages without rewriting i18n from scratch
  • Custom post types fit "tool" as a first-class object
  • Theme + plugin model maps cleanly to "tool registry"
  • Editing pages with non-tool content (about, blog, legal) is trivial for non-devs
  • Hosting on Hostico is €5/month, no Vercel-level surprises at scale

What it cost us:

  • No streaming server-side rendering (each tool is a JS island)
  • Custom REST endpoints for everything dynamic
  • Polylang quirks with shortcodes
  • Slower DX than Next.js with hot reload

Net assessment: for a content-heavy multilingual site where each tool is mostly a self-contained widget, WordPress was the right call. If Toolita were 5 complex apps instead of 260 small ones, Next.js would have won.

Architecture overview

When a user clicks "Explain my result," this happens:

[Tool page]
    ↓
Calculate locally (JS, instant)
    ↓
User clicks "Explain"
    ↓
Frontend: hash tool_id + bucketed inputs + result
    ↓
Frontend: check local LRU cache (sessionStorage)
    ↓ miss
POST /wp-json/toolita/v1/explain
    ↓
WordPress: check transient cache (24-72hr TTL)
    ↓ miss
Build prompt with tool context + language
    ↓
Anthropic API call (Claude Haiku for free tier)
    ↓
Store in transient
    ↓
Return markdown
    ↓
Frontend renders + optionally streams follow-up

Enter fullscreen mode Exit fullscreen mode

The two-layer cache (browser + server) is what keeps the system economical. More on that in a moment.

The REST endpoint

WordPress makes this part clean. Register a custom REST route, validate inputs, handle the call.

// includes/explain/register.php

add_action('rest_api_init', function () {
    register_rest_route('toolita/v1', '/explain', [
        'methods' => 'POST',
        'callback' => 'toolita_handle_explain',
        'permission_callback' => 'toolita_check_rate_limit',
        'args' => [
            'tool_id' => [
                'required' => true,
                'sanitize_callback' => 'sanitize_text_field',
            ],
            'inputs' => [
                'required' => true,
                'validate_callback' => 'is_array',
            ],
            'result' => [
                'required' => true,
            ],
            'lang' => [
                'default' => 'en',
                'sanitize_callback' => 'sanitize_text_field',
                'validate_callback' => function ($value) {
                    return in_array($value, ['en', 'ro', 'es', 'it', 'pt', 'pl', 'de']);
                },
            ],
        ],
    ]);
});

function toolita_handle_explain(WP_REST_Request $request) {
    $tool_id = $request['tool_id'];
    $inputs  = $request['inputs'];
    $result  = $request['result'];
    $lang    = $request['lang'];

    $tool_context = toolita_get_tool_context($tool_id);
    if (!$tool_context) {
        return new WP_Error('unknown_tool', 'Tool not registered', ['status' => 404]);
    }

    $bucketed_inputs = toolita_bucket_inputs($tool_id, $inputs);
    $cache_key = 'explain_' . md5(
        $tool_id . '_' .
        wp_json_encode($bucketed_inputs) . '_' .
        wp_json_encode($result) . '_' .
        $lang
    );

    $cached = get_transient($cache_key);
    if ($cached !== false) {
        return [
            'explanation' => $cached,
            'cached'      => true,
        ];
    }

    $prompt = toolita_build_prompt($tool_context, $inputs, $result, $lang);

    try {
        $response = toolita_call_anthropic($prompt);
        $explanation = $response['content'][0]['text'];

        $ttl = $tool_context['rate_dependent']
            ? 6 * HOUR_IN_SECONDS
            : 48 * HOUR_IN_SECONDS;

        set_transient($cache_key, $explanation, $ttl);

        return [
            'explanation' => $explanation,
            'cached'      => false,
        ];
    } catch (Exception $e) {
        error_log('Toolita explain failed: ' . $e->getMessage());
        return new WP_Error('explain_failed', 'Could not generate explanation', ['status' => 500]);
    }
}

Enter fullscreen mode Exit fullscreen mode

The caching layer that saved us thousands

First version had no caching. We burned through $400 in the first week of beta. The Mortgage Calculator alone was eating $80/day because every user had similar inputs that produced near-identical explanations.

The insight: most users with similar financial profiles get explanations that should be essentially the same. A 30-year-old paying off $5,234 in credit card debt at 22% APR doesn't need a different explanation than a 30-year-old paying off $5,108 at 21.5%. Both get "this is high-interest debt, prioritize it, here's the math on snowball vs avalanche."

So we bucket the inputs before hashing for the cache key.

// includes/explain/bucketing.php

function toolita_bucket_inputs($tool_id, $inputs) {
    $config = toolita_get_bucketing_config($tool_id);
    if (!$config) {
        return $inputs;
    }

    $bucketed = [];

    foreach ($inputs as $key => $value) {
        if (!isset($config[$key])) {
            $bucketed[$key] = $value;
            continue;
        }

        $rule = $config[$key];

        switch ($rule['type']) {
            case 'numeric_range':
                $bucketed[$key] = floor($value / $rule['bucket_size']) * $rule['bucket_size'];
                break;

            case 'numeric_log':
                if ($value <= 0) {
                    $bucketed[$key] = 0;
                } else {
                    $magnitude = pow(10, floor(log10($value)));
                    $bucketed[$key] = floor($value / $magnitude) * $magnitude;
                }
                break;

            case 'categorical':
                $bucketed[$key] = $value;
                break;

            default:
                $bucketed[$key] = $value;
        }
    }

    return $bucketed;
}

Enter fullscreen mode Exit fullscreen mode

Bucketing config per tool category:

$mortgage_bucketing = [
    'home_price'    => ['type' => 'numeric_log'],        // $5234 → $5000, $52340 → $50000
    'down_payment'  => ['type' => 'numeric_log'],
    'interest_rate' => ['type' => 'numeric_range', 'bucket_size' => 0.25],   // 6.74% → 6.50%
    'term_years'    => ['type' => 'categorical'],         // 15, 20, 30 stay as-is
];

$bmi_bucketing = [
    'weight_kg' => ['type' => 'numeric_range', 'bucket_size' => 2],  // 73 → 72
    'height_cm' => ['type' => 'numeric_range', 'bucket_size' => 2],
    'age'       => ['type' => 'numeric_range', 'bucket_size' => 5],
    'gender'    => ['type' => 'categorical'],
];

Enter fullscreen mode Exit fullscreen mode

After two weeks of running with bucketing, our cache hit rate stabilized at 68%. That cut Anthropic API costs by about 3x.

Multilingual prompts (direct translation is wrong)

We learned this the hard way. A direct translation of an English explanation reads awkward in Romanian. The framing, the call-to-action, the level of formality all shift.

So each tool registers a prompt template per language, not one English template that we translate output from.

// tools/finance/mortgage/prompts.php

return [
    'en' => "You are explaining a mortgage calculation to a first-time homebuyer.\n\n" .
            "Inputs: {INPUTS}\n" .
            "Result: {RESULT}\n\n" .
            "Write a friendly 100-120 word explanation. Include one specific actionable tip. " .
            "Use plain English, no jargon. Amounts in USD.",

    'ro' => "Explici un calcul de ipoteca cuiva care vrea sa cumpere prima locuinta.\n\n" .
            "Date introduse: {INPUTS}\n" .
            "Rezultat: {RESULT}\n\n" .
            "Scrie o explicatie prietenoasa de 100-120 cuvinte. Include un sfat practic concret. " .
            "Limbaj clar, fara jargon. Sumele in RON.",

    'es' => "Explicas el cálculo de una hipoteca a alguien que compra su primera vivienda.\n\n" .
            "Datos introducidos: {INPUTS}\n" .
            "Resultado: {RESULT}\n\n" .
            "Escribe una explicación amigable de 100-120 palabras. Incluye un consejo concreto " .
            "y accionable. Lenguaje sencillo, sin jerga. Importes en EUR.",

    'it' => "Spieghi il calcolo di un mutuo a chi sta comprando la prima casa.\n\n" .
            "Dati inseriti: {INPUTS}\n" .
            "Risultato: {RESULT}\n\n" .
            "Scrivi una spiegazione amichevole di 100-120 parole. Includi un consiglio pratico " .
            "concreto. Linguaggio semplice, senza gergo. Importi in EUR.",

    // ... pt, pl, de follow same pattern
];

Enter fullscreen mode Exit fullscreen mode

For tools that are jurisdiction-specific (salary calculators, tax tools), the prompt also includes the relevant legal references for that country.

Rate limiting (because cheap users will hammer you)

Free tier gets 5 explanations per IP per day. Pretty obvious why.

// includes/explain/rate-limit.php

function toolita_check_rate_limit() {
    if (current_user_can('toolita_pro')) {
        return true;
    }

    $ip = toolita_get_client_ip();
    $key = 'rate_explain_' . md5($ip);
    $count = (int) get_transient($key);

    if ($count >= 5) {
        return new WP_Error('rate_limit', 'Daily limit reached. Upgrade to Pro for unlimited.', [
            'status' => 429,
        ]);
    }

    set_transient($key, $count + 1, DAY_IN_SECONDS);
    return true;
}

function toolita_get_client_ip() {
    $headers = ['HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'];
    foreach ($headers as $header) {
        if (!empty($_SERVER[$header])) {
            $ip = explode(',', $_SERVER[$header])[0];
            return trim($ip);
        }
    }
    return '0.0.0.0';
}

Enter fullscreen mode Exit fullscreen mode

The Cloudflare header check matters because Hostico sits behind Cloudflare, so REMOTE_ADDR would otherwise return the Cloudflare edge IP, not the user.

The frontend side

Vanilla JS, no framework. The tool result page has a button. Click it, fetch the explanation, render markdown.

// assets/js/explain.js

(function () {
    const CACHE_KEY_PREFIX = 'toolita_explain_';
    const LOCAL_TTL = 60 * 60 * 1000; // 1 hour client cache

    function getLocalCache(key) {
        try {
            const stored = sessionStorage.getItem(CACHE_KEY_PREFIX + key);
            if (!stored) return null;

            const { value, expires } = JSON.parse(stored);
            if (Date.now() > expires) {
                sessionStorage.removeItem(CACHE_KEY_PREFIX + key);
                return null;
            }
            return value;
        } catch (e) {
            return null;
        }
    }

    function setLocalCache(key, value) {
        try {
            sessionStorage.setItem(CACHE_KEY_PREFIX + key, JSON.stringify({
                value,
                expires: Date.now() + LOCAL_TTL,
            }));
        } catch (e) {
            // Quota exceeded, ignore
        }
    }

    async function fetchExplanation(toolId, inputs, result, lang) {
        const cacheKey = toolId + ':' + JSON.stringify(inputs) + ':' + JSON.stringify(result) + ':' + lang;

        const cached = getLocalCache(cacheKey);
        if (cached) return { explanation: cached, cached: true };

        const response = await fetch('/wp-json/toolita/v1/explain', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ tool_id: toolId, inputs, result, lang }),
        });

        if (response.status === 429) {
            throw new Error('rate_limit');
        }

        if (!response.ok) {
            throw new Error('explain_failed');
        }

        const data = await response.json();
        setLocalCache(cacheKey, data.explanation);
        return data;
    }

    window.ToolitaExplain = { fetchExplanation };
})();

Enter fullscreen mode Exit fullscreen mode

The local sessionStorage cache catches users clicking "Explain" multiple times in the same session. Saves a server roundtrip and shows results instantly.

What we got wrong

A few honest admissions for anyone building something similar:

  1. No caching in v1. Burned $400 in week one. Could have saved that with one day of upfront design.
  2. Too-aggressive cache TTL in v2. 30-day cache meant mortgage explanations were referencing rates from a quarter ago. Users noticed. We had to invalidate everything and add the rate_dependent flag per tool.
  3. Single English prompt translated at output. Output read like a robot in Romanian and Italian. Native prompts per language fixed it instantly.
  4. No bucketing. Cache hit rate was 12% before bucketing. With bucketing, 68%.
  5. No tracking of model usage per tool. When Claude API costs spiked one week, we couldn't tell which tools were responsible. Added per-tool token logging in v3.

What's next

  • Streaming responses for instant feel (token-by-token rendering)
  • Premium tier with Claude Sonnet for free-tier-quality + extras
  • Per-user explanation history (logged-in users)
  • Embed widget support so partners get explanations in their iframe
  • Structured outputs for tools that benefit from tables or charts in the explanation

Try it

If you're curious how it feels in practice, Toolita has 260+ tools, 7 languages, and the Explain button on every calculator result. Free, no signup.

Disclosure: I'm the maker. Feedback welcome, especially on the cache hit rate math or the prompt architecture if you've built something similar.


Code snippets in this article are simplified from production for readability. The production codebase has additional error handling, logging, A/B testing for prompts, and observability hooks.

If you found this useful, I write occasionally about Toolita architecture, programmatic SEO at scale, and content automation.