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

推荐订阅源

让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
罗磊的独立博客
博客园 - 【当耐特】
M
MIT News - Artificial intelligence
月光博客
月光博客
博客园_首页
博客园 - 叶小钗
T
Tailwind CSS Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
I
InfoQ
量子位
小众软件
小众软件
爱范儿
爱范儿
The GitHub Blog
The GitHub Blog
IT之家
IT之家
Jina AI
Jina AI
阮一峰的网络日志
阮一峰的网络日志
G
Google Developers Blog
WordPress大学
WordPress大学
人人都是产品经理
人人都是产品经理
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
J
Java Code Geeks
云风的 BLOG
云风的 BLOG
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报

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
Caching AI Responses in a Desktop App — Don't Pay Twice f...
hiyoyo · 2026-05-05 · via DEV Community
Cover image for Caching AI Responses in a Desktop App — Don't Pay Twice for the Same Question

hiyoyo

If this is useful, a ❤️ helps others find it.

All tests run on an 8-year-old MacBook Air.

If a user closes the AI diagnosis overlay and reopens it, should you call Gemini again?

No. Cache the result. Same input → same output. No reason to burn rate limit quota.

Here's the caching layer I built into HiyokoLogcat.


The problem

Without caching:

  1. User clicks diagnose on error line 847
  2. Gemini responds in 3 seconds
  3. User closes the overlay
  4. User reopens the overlay
  5. Gemini call again → 3 more seconds, 1 more request

With caching:
Steps 4-5 → instant, zero API calls.


Cache key: hash the input

Same log context → same hash → same cached result.

use std::collections::HashMap;
use sha2::{Sha256, Digest};

pub struct DiagnosisCache {
    entries: HashMap,
    max_size: usize,
}

#[derive(Clone)]
pub struct CacheEntry {
    pub result: String,
    pub created_at: std::time::Instant,
}

impl DiagnosisCache {
    pub fn new(max_size: usize) -> Self {
        Self { entries: HashMap::new(), max_size }
    }

    pub fn key(context: &str) -> String {
        let mut hasher = Sha256::new();
        hasher.update(context.as_bytes());
        format!("{:x}", hasher.finalize())
    }

    pub fn get(&self, key: &str) -> Option<&CacheEntry> {
        self.entries.get(key)
    }

    pub fn insert(&mut self, key: String, result: String) {
        // Evict oldest entries if at capacity
        if self.entries.len() >= self.max_size {
            if let Some(oldest_key) = self.entries
                .iter()
                .min_by_key(|(_, v)| v.created_at)
                .map(|(k, _)| k.clone())
            {
                self.entries.remove(&oldest_key);
            }
        }

        self.entries.insert(key, CacheEntry {
            result,
            created_at: std::time::Instant::now(),
        });
    }
}

Enter fullscreen mode Exit fullscreen mode


Using it in the command

#[tauri::command]
pub async fn diagnose(
    context: String,
    api_key: String,
    cache: tauri::State<'_, Mutex>,
) -> Result {
    let key = DiagnosisCache::key(&context);

    // Check cache first
    {
        let cache = cache.lock().unwrap();
        if let Some(entry) = cache.get(&key) {
            return Ok(entry.result.clone());  // instant
        }
    }

    // Cache miss — call Gemini
    let result = call_gemini(&context, &api_key).await?;

    // Store result
    {
        let mut cache = cache.lock().unwrap();
        cache.insert(key, result.clone());
    }

    Ok(result)
}

Enter fullscreen mode Exit fullscreen mode


Cache size

50 entries is enough for a session. Log lines change constantly — a cache from 2 hours ago is rarely useful. Clear on app restart, or add a TTL if you want.

// Register in main.rs
.manage(Mutex::new(DiagnosisCache::new(50)))

Enter fullscreen mode Exit fullscreen mode


Result

First diagnosis: 3 seconds. Every repeat: instant. Rate limit usage cut significantly for users who re-examine the same errors.


Hiyoko PDF Vault → https://hiyokoko.gumroad.com/l/HiyokoPDFVault
X → @hiyoyok