מאמרים הנדסיים
ניהול עלויות טוקנים ואסטרטגיות מטמון ב-Next.js
מאת Muhammad Shahid · · 28 דקות קריאה
תשובה קצרה
כדי להוזיל עלויות API של LLM ב-Next.js, בדקו קודם את האפשרויות הזולות: מטמון מדויק ב-Redis לפי המודל, גיבוב של הפרומפט והשאלה המנורמלת; אחר כך מטמון סמנטי שמשתמש שוב בתשובה לשאלה בניסוח אחר, עם סף דמיון שנבדק ושומר על מילים כמו on/off; אחר כך תקרת הוצאה לכל משתמש ונעילה כך ששאלות זהות יגרמו לקריאה אחת. הפעילו את ה-prompt caching של הספק על פרומפט המערכת הארוך והגבילו את max_tokens. בסימולציה של 1,000 שאלות תמיכה זה הוריד את החשבון ב-Claude Sonnet 5.5 מ-7.55$ ל-0.17$.
| סטאק | Route handler ב-Next.js App Router, Redis 8, @anthropic-ai/sdk, הטמעות transformers.js |
|---|---|
| חיסכון | מ-7.55$ ל-0.17$ ל-1,000 שאלות מדומות ב-Claude Sonnet 5.5; מ-0.377$ ל-0.010$ ב-Haiku 5.5 |
| סף | דמיון 0.80 ושומר מילים מנוגדות: 11 מתוך 30 ניסוחים חוזרים שימשו שוב, 0 תשובות שגויות |
| מלכודת שנמצאה | "Turn off 2FA" קיבל 0.90 מול "turn on 2FA" עם all-MiniLM-L6-v2 |
| נבדק | מול Redis 8 ב-Docker עם הטמעות מקומיות אמיתיות ולקוח Claude מתוסרט |
רוב תכונות ה-AI עונות על אותן שאלות שוב ושוב, ומשלמות על כל תשובה. המדריך הזה מראה איך לשמור תשובות LLM במטמון Redis ב-Next.js כדי להוזיל עלויות API של AI: מטמון מדויק, מטמון סמנטי לשאלות בניסוח אחר, ה-prompt caching של הספק עצמו, תקרת הוצאה לכל משתמש ונעילה שמונעת מגל של שאלות זהות להפוך לגל של חשבונות זהים. הכל הורץ מול Redis 8 ב-Docker, עם הטמעות מקומיות אמיתיות ולקוח Claude מתוסרט שמחייב כמו ה-API האמיתי, והבדיקה מצאה בדרך שתי בעיות אמיתיות: אחת בפענוח של Redis אצלי ואחת ברעיון של מטמון סמנטי עצמו. שתיהן מוסברות למטה.
מאיפה מגיע החשבון של LLM?
כל בקשה משלמת על טוקני הקלט (פרומפט המערכת, מסמכים והשאלה) ועל טוקני הפלט (התשובה, וגם חשיבה אם יש). הפלט הוא החלק היקר לכל טוקן: ב-Claude Sonnet 5.5 הוא 10$ למיליון טוקנים מול 2$ לקלט. אבל בבוט תמיכה או בעוזר תיעוד, הקלט הוא בדרך כלל המספר הגדול יותר בסך הכל, כי פרומפט מערכת ארוך עם עובדות על המוצר נשלח עם כל שאלה. אז יש שני מנופים: לשלוח פחות בקשות, ולהוזיל את החלק החוזר בכל בקשה. ספרו את הפרומפט שלכם עם מונה הטוקנים של LLM ותמחרו אותו עם מחשבון עלויות ה-API של AI.
חמש דרכים להוריד את החשבון
| טכניקה | מה היא חוסכת | סיכון |
|---|---|---|
| מטמון תשובות מדויק | את כל הקריאה, לשאלה שחוזרת | תשובות ישנות אם הפרומפט משתנה (פתרון: גרסה במפתח) |
| מטמון תשובות סמנטי | את כל הקריאה, לשאלה בניסוח אחר | תשובות שגויות לשאלות דומות למראה (פתרון: סף ושומר) |
| prompt caching של הספק | כ-90% ויותר מעלות התחילית החוזרת של הפרומפט | החטאות שקטות אם התחילית משתנה ולו בבייט |
| תקרות הוצאה ו-max_tokens | משתמשים חריגים ותשובות ארוכות מדי | תשובות קטועות אם max_tokens נמוך מדי |
| איחוד בקשות (נעילה) | קריאות כפולות כשהרבה משתמשים שואלים בבת אחת | בקשות שממתינות אם הקריאה הראשונה איטית |
העיצוב
הסדר הוא העיקר. בדיקה מדויקת עולה סבב אחד ל-Redis. בדיקה סמנטית עולה הטמעה מקומית אחת (כ-2 ms על CPU של מחשב נייד) וחיפוש וקטורי. רק כששתיהן מחטיאות הבקשה נוגעת בתקציב, לוקחת נעילה וקוראת למודל, והתשובה נשמרת לאדם הבא. כל מפתח במטמון כולל את המודל וגיבוב של פרומפט המערכת, כך ששינוי באחד מהם מתחיל מטמון חדש במקום להגיש תשובות שנכתבו לפי הוראות ישנות.
מה צריך?
| כלי | גרסה | למה |
|---|---|---|
| Next.js | 15 (App Router) | ה-route handler |
| Redis | 8 (Docker) | מטמון מדויק, חיפוש וקטורי, נעילות, מוני הוצאה |
| redis (npm) | 6.3 | לקוח עם עזרי Query Engine (ft.create, ft.search) |
| @huggingface/transformers | 4 | הטמעות מקומיות עם all-MiniLM-L6-v2 |
| @anthropic-ai/sdk | 1.8 | Claude עם prompt caching |
| zod | 4 | בדיקת בקשות |
שלב 1: הקמה
npm install @anthropic-ai/sdk redis @huggingface/transformers zod
docker run -d --name redis -p 6379:6379 redis:8 # Redis 8 includes the Query Engine (vector search)
echo "REDIS_URL=redis://localhost:6379" >> .env.local
echo "ANTHROPIC_API_KEY=sk-ant-..." >> .env.local
Redis 8 כולל את Redis Query Engine, כך שחיפוש וקטורי עובד בתמונה הרגילה בלי מודולים נוספים. בפרודקשן מתאים כל שירות תואם Redis שתומך ב-FT.SEARCH עם שדות וקטור.
שלב 2: המטמון המדויק, המטמון הסמנטי והנעילה
import { createHash } from "node:crypto";
import { SCHEMA_FIELD_TYPE, SCHEMA_VECTOR_FIELD_ALGORITHM, type RedisClientType } from "redis";
// ---- 1. Exact cache: same model, same prompt version, same (normalised) question -> same answer
export function normalise(question: string) {
return question
.normalize("NFKC")
.toLowerCase()
.replace(/\s+/g, " ")
.replace(/[\s?!.。?!]+$/u, "")
.trim();
}
export function exactKey(model: string, promptVersion: string, question: string) {
const hash = createHash("sha256").update(JSON.stringify([model, promptVersion, normalise(question)])).digest("hex");
return "llm:exact:" + hash;
}
export interface CachedAnswer {
text: string;
model: string;
createdAt: string;
}
export async function getExact(redis: RedisClientType, key: string): Promise<CachedAnswer | null> {
const raw = await redis.get(key);
return raw ? (JSON.parse(raw) as CachedAnswer) : null;
}
export async function setExact(redis: RedisClientType, key: string, value: CachedAnswer, ttlSeconds: number) {
await redis.set(key, JSON.stringify(value), { EX: ttlSeconds });
}
// ---- 2. Semantic cache: a different wording of a question already answered
// Redis 8 includes the Query Engine, so vectors are stored in hashes and searched with FT.SEARCH KNN.
export const SEM_INDEX = "llm:sem:idx";
const SEM_PREFIX = "llm:sem:";
export async function ensureSemanticIndex(redis: RedisClientType, dims: number) {
try {
await redis.ft.create(
SEM_INDEX,
{
scope: { type: SCHEMA_FIELD_TYPE.TAG },
vec: {
type: SCHEMA_FIELD_TYPE.VECTOR,
ALGORITHM: SCHEMA_VECTOR_FIELD_ALGORITHM.HNSW,
TYPE: "FLOAT32",
DIM: dims,
DISTANCE_METRIC: "COSINE",
},
},
{ ON: "HASH", PREFIX: SEM_PREFIX },
);
} catch (err) {
if (!String(err).includes("Index already exists")) throw err;
}
}
const toBytes = (v: Float32Array) => Buffer.from(v.buffer, v.byteOffset, v.byteLength);
// Words that flip the meaning of an otherwise similar question ("turn ON 2FA" vs "turn OFF 2FA" scored 0.90).
// If both questions use a word from the same group and the words differ, the cached answer is not reused.
// Build these groups from your own product: plans, platforms, on/off actions.
const CONTRASTS: Map<string, string>[] = [
new Map([["on", "on"], ["enable", "on"], ["off", "off"], ["disable", "off"], ["reset", "reset"]]),
new Map([["free", "free"], ["plus", "plus"], ["pro", "pro"]]),
new Map([["windows", "windows"], ["mac", "mac"], ["macos", "mac"], ["macbook", "mac"], ["ios", "ios"], ["iphone", "ios"], ["android", "android"]]),
];
export function conflicts(a: string, b: string) {
const terms = (s: string, group: Map<string, string>) =>
[...new Set(normalise(s).split(/[^\p{L}\p{N}]+/u).flatMap((w) => (group.has(w) ? [group.get(w)!] : [])))].sort().join();
return CONTRASTS.some((group) => {
const ta = terms(a, group);
const tb = terms(b, group);
return ta !== "" && tb !== "" && ta !== tb;
});
}
// scope = model + prompt version: an answer is only reused under the same model and instructions
export async function findSimilar(redis: RedisClientType, scope: string, question: string, vec: Float32Array, minSimilarity: number) {
const { documents } = await redis.ft.search(
SEM_INDEX,
"(@scope:{" + scope.replace(/[^a-zA-Z0-9]/g, "\\$&") + "})=>[KNN 3 @vec $v AS dist]",
{ PARAMS: { v: toBytes(vec) }, SORTBY: "dist", RETURN: ["dist", "answer", "question"], DIALECT: 2 },
);
for (const doc of documents) {
const similarity = 1 - Number(doc.value.dist); // cosine distance -> similarity
if (similarity < minSimilarity) break; // sorted: the rest are further away
if (conflicts(question, String(doc.value.question))) continue;
return { answer: String(doc.value.answer), question: String(doc.value.question), similarity };
}
return null;
}
export async function storeSimilar(
redis: RedisClientType, scope: string, question: string, vec: Float32Array, answer: string, ttlSeconds: number,
) {
const key = SEM_PREFIX + createHash("sha256").update(scope + "|" + normalise(question)).digest("hex");
await redis.hSet(key, { scope, question, answer, vec: toBytes(vec) });
await redis.expire(key, ttlSeconds);
}
// ---- 3. Stampede protection: when 50 users ask the same new question at once, only one pays
export async function withLock<T>(
redis: RedisClientType, key: string, compute: () => Promise<T>, waitForOther: () => Promise<T | null>,
): Promise<T> {
const lockKey = key + ":lock";
const gotLock = await redis.set(lockKey, "1", { NX: true, PX: 30_000 });
if (!gotLock) {
for (let i = 0; i < 100; i++) {
await new Promise((r) => setTimeout(r, 100));
const done = await waitForOther();
if (done) return done;
}
// the other request took too long or failed: compute anyway
}
try {
return await compute();
} finally {
if (gotLock) await redis.del(lockKey);
}
}
המטמון המדויק מגבב את המודל, גרסת הפרומפט והשאלה המנורמלת (אותיות קטנות, רווח יחיד, בלי סימני פיסוק בסוף), כך ש-"How do I cancel my subscription?" ו-" how do I cancel my subscription " חולקים רשומה אחת. זו השכבה הזולה ביותר, ובסימולציה למטה היא זו שחוסכת הכי הרבה.
המטמון הסמנטי שומר כל שאלה שנענתה יחד עם ההטמעה שלה ב-hash של Redis ומחפש את שלושת השכנים הקרובים עם KNN, מוגבל לאותו מודל ואותה גרסת פרומפט עם מסנן TAG. שכן משמש שוב רק אם הדמיון שלו מעל הסף והוא עובר את conflicts, שומר המילים המנוגדות שמוסבר מיד.
הנעילה משתמשת ב-SET NX עם תפוגה של 30 שניות. הבקשה הראשונה לשאלה חדשה מחשבת את התשובה; האחרות בודקות את המטמון המדויק עד 10 שניות במקום לשלם על אותה קריאה. בבדיקה, 20 שאלות זהות שנשלחו באותו רגע יצרו קריאה אחת בדיוק למודל.
הגרסה הראשונה של findSimilar שלחה FT.SEARCH גולמי ופענחה את התשובה כמערך שטוח קלאסי. הבדיקה תפסה שהיא אף פעם לא מצאה כלום: לקוח redis 6 מדבר RESP3 כברירת מחדל ומחזיר תוצאות חיפוש כ-map. העזר ft.search שמשמש עכשיו מחזיר { total, documents } בכל פרוטוקול.
כמה דומה זה מספיק דומה?
מטמון סמנטי נשמע כמו כסף חינם עד שבודקים אותו. עם המודל הקטן all-MiniLM-L6-v2, "How do I turn off two-factor authentication?" קיבל 0.90 מול השאלה השמורה "How do I turn on two-factor authentication?", יותר מרוב הניסוחים החוזרים האמיתיים. "How much storage does the Pro plan have?" קיבל 0.80 מול השאלה על התוכנית החינמית. דמיון לבדו הגיש תשובה שגויה בכל סף מתחת ל-0.95, וב-0.95 הוא השתמש שוב רק בניסוח אחד מתוך 30.
הפתרון הוא שומר מילים מנוגדות: קבוצות קטנות של מילים שהופכות את המשמעות של שאלה דומה (on/off/enable/disable/reset, שמות תוכניות, פלטפורמות). אם שתי השאלות משתמשות במילה מאותה קבוצה והמילים שונות, התשובה השמורה לא משמשת שוב. עם השומר לא היו תשובות שגויות מסף 0.75 ומעלה. המאמר משתמש ב-0.80, שהשתמש שוב ב-11 מתוך 30 ניסוחים בלי תשובות שגויות על הסט הזה. ארבעים שאלות הן מדגם קטן: בנו סט מתויג משלכם מתנועה אמיתית, כללו שאלות דומות-למראה משלכם, ומדדו לפני שאתם מפעילים מטמון סמנטי. מודל הטמעות חזק יותר גם יפריד בין שאלות טוב יותר מהמודל הקטן הזה.
שלב 3: הטמעות מקומיות
// Local sentence embeddings with transformers.js: no API call, no per-request cost.
// all-MiniLM-L6-v2 gives 384-dimension vectors; the model (about 23 MB) downloads once and is cached.
import { pipeline, type FeatureExtractionPipeline } from "@huggingface/transformers";
export const EMBED_DIMS = 384;
let extractor: Promise<FeatureExtractionPipeline> | null = null;
export async function embed(text: string): Promise<Float32Array> {
extractor ??= pipeline("feature-extraction", "Xenova/all-MiniLM-L6-v2", { dtype: "fp32" });
const out = await (await extractor)(text, { pooling: "mean", normalize: true });
return out.data as Float32Array;
}
הרצת מודל ההטמעות בתוך תהליך ה-Node.js אומרת שבדיקה סמנטית לא עולה קריאת API ולא סבב רשת: כ-1.9 ms לשאלה על CPU של מחשב נייד בבדיקה. המודל יורד פעם אחת (כ-23 MB) ומשמש שוב. כיוון שה-route handler צריך ממשקי Node.js ומודל שחי לאורך זמן, הוא רץ ב-runtime של Node.js ולא ב-Edge.
שלב 4: prompt caching והקריאה למודל
import { createHash } from "node:crypto";
import type Anthropic from "@anthropic-ai/sdk";
import type { RedisClientType } from "redis";
import { exactKey, findSimilar, getExact, setExact, storeSimilar, withLock } from "./cache";
// USD per million tokens (Claude pricing, November 2026). Cache writes cost 1.25x input, reads about 0.1x.
export const PRICES = {
"claude-haiku-5-5": { input: 0.1, output: 0.5, cacheWrite: 0.125, cacheRead: 0.01 },
"claude-sonnet-5-5": { input: 2, output: 10, cacheWrite: 2.5, cacheRead: 0.1 },
} as const;
export type Model = keyof typeof PRICES;
// The long, fixed part of every request: instructions plus product facts. Never put a date or user name here,
// or the provider's prompt cache misses on every request.
export const SYSTEM_PROMPT = [
"You are the support assistant for Acme Cloud Storage. Answer in at most 120 words.",
"Use only the product facts below. If they do not answer the question, say so and suggest contacting support.",
"PRODUCT FACTS:",
"- Plans: Free (5 GB), Plus (200 GB, $4/month), Pro (2 TB, $10/month). Annual billing saves 20%.",
"- Cancel any time in Settings > Billing; files stay readable for 30 days after cancelling.",
"- Password reset: Sign-in page > Forgot password. Links expire after 1 hour.",
"- Shared links can have a password and an expiry date (Plus and Pro).",
"- Deleted files stay in Trash for 30 days (Free) or 180 days (Plus, Pro).",
"- Two-factor authentication: Settings > Security, with an authenticator app or a passkey.",
"- Desktop apps for Windows and macOS; mobile apps for iOS and Android.",
].join("\n");
// Change this whenever the prompt or facts change: it is part of every cache key, so old answers stop matching.
export const PROMPT_VERSION = createHash("sha256").update(SYSTEM_PROMPT).digest("hex").slice(0, 12);
export const EXACT_TTL = 24 * 3600;
export const SEMANTIC_TTL = 7 * 24 * 3600;
export const MIN_SIMILARITY = 0.8; // chosen from labelled questions with the contrast-word guard on, see the test
export function costOf(model: Model, u: Anthropic.Usage) {
const p = PRICES[model];
return (
(u.input_tokens * p.input +
(u.cache_creation_input_tokens ?? 0) * p.cacheWrite +
(u.cache_read_input_tokens ?? 0) * p.cacheRead +
u.output_tokens * p.output) / 1_000_000
);
}
export interface Deps {
redis: RedisClientType;
claude: Anthropic;
embed: (text: string) => Promise<Float32Array>;
dailyBudgetUsd: number;
}
export type Source = "exact" | "semantic" | "model";
export async function answer(
deps: Deps, userId: string, question: string,
opts: { model?: Model; semantic?: boolean } = {}, // semantic: false for questions about private data
) {
const model = opts.model ?? "claude-haiku-5-5";
const useSemantic = opts.semantic ?? true;
const key = exactKey(model, PROMPT_VERSION, question);
const scope = model + "-" + PROMPT_VERSION;
// 1. Exact cache: free and instant
const exact = await getExact(deps.redis, key);
if (exact) return { text: exact.text, source: "exact" as Source, costUsd: 0 };
// 2. Semantic cache: one local embedding, no API call
const vec = useSemantic ? await deps.embed(question) : null;
const similar = vec ? await findSimilar(deps.redis, scope, question, vec, MIN_SIMILARITY) : null;
if (similar) {
await setExact(deps.redis, key, { text: similar.answer, model, createdAt: new Date().toISOString() }, EXACT_TTL);
return { text: similar.answer, source: "semantic" as Source, costUsd: 0 };
}
// 3. Spend cap per user per day, checked before paying for a call
const spendKey = "llm:spend:" + userId + ":" + new Date().toISOString().slice(0, 10);
const spent = Number((await deps.redis.get(spendKey)) ?? 0);
if (spent >= deps.dailyBudgetUsd) throw Object.assign(new Error("Daily AI budget used up"), { status: 429 });
// 4. Model call, once per new question even when many users ask it at the same moment
return withLock(
deps.redis,
key,
async () => {
const msg = await deps.claude.messages.create({
model,
max_tokens: 400, // caps the most expensive part of the bill: output tokens
output_config: { effort: "low" }, // short support answers do not need long thinking
system: [{ type: "text", text: SYSTEM_PROMPT, cache_control: { type: "ephemeral" } }],
messages: [{ role: "user", content: question }],
});
const text = msg.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
const costUsd = costOf(model, msg.usage);
await deps.redis.incrByFloat(spendKey, costUsd);
await deps.redis.expire(spendKey, 2 * 24 * 3600);
// Only cache complete, normal answers: never a refusal or an answer cut off by max_tokens
if (msg.stop_reason === "end_turn" && text) {
await setExact(deps.redis, key, { text, model, createdAt: new Date().toISOString() }, EXACT_TTL);
if (vec) await storeSimilar(deps.redis, scope, question, vec, text, SEMANTIC_TTL);
}
return { text, source: "model" as Source, costUsd, usage: msg.usage };
},
async () => {
const done = await getExact(deps.redis, key);
return done ? { text: done.text, source: "exact" as Source, costUsd: 0 } : null;
},
);
}
כמה שורות עושות את רוב החיסכון בהחטאה. cache_control על פרומפט המערכת מפעיל את ה-prompt caching של Claude: הבקשה הראשונה כותבת את הפרומפט למטמון ב-1.25 ממחיר הקלט, ובקשות מאוחרות יותר בתוך חמש הדקות של המטמון, שכל קריאה מחדשת, משלמות חלק קטן ממנו (ב-Sonnet 5.5, 0.10$ למיליון טוקנים שמורים מול 2$). הפרומפט חייב להיות זהה בייט אחר בייט, ולכן אין בו תאריכים או שמות משתמשים, והוא חייב להיות ארוך מהאורך המינימלי של המודל למטמון (512 טוקנים במודלים הנוכחיים): פרומפט קצר פשוט לא נשמר, בשקט. max_tokens מגביל את הטוקנים היקרים ביותר, ו-effort: "low" שומר על חשיבה קצרה לתשובות תמיכה פשוטות. תשובות שנדחו או נקטעו בגלל max_tokens לעולם לא נשמרות, כך שתשובה גרועה לא מוגשת שוב במשך יום.
תקרת ההוצאה סופרת דולרים אמיתיים לכל משתמש ליום משדות ה-usage של ה-API עצמו, ונבדקת רק אחרי ששני המטמונים מחטיאים: תשובות שמורות נשארות חינמיות גם למשתמש שהגיע לתקרה. לשאלות על נתונים פרטיים, קראו ל-answer עם semantic: false והוסיפו את מזהה המשתמש למפתח המדויק, כך שתשובה של משתמש אחד לעולם לא מוגשת לאחר.
שלב 5: ה-route handler של Next.js
// app/api/ask/route.ts - Next.js App Router route handler
import Anthropic from "@anthropic-ai/sdk";
import { createClient, type RedisClientType } from "redis";
import { z } from "zod";
import { answer } from "@/lib/answer";
import { embed } from "@/lib/embed";
import { ensureSemanticIndex } from "@/lib/cache";
export const runtime = "nodejs"; // Redis TCP and local embeddings need Node.js, not the Edge runtime
export const dynamic = "force-dynamic"; // never let Next.js cache this route itself
// One Redis connection and one SDK client per server process, reused across requests
const g = globalThis as unknown as { redis?: Promise<RedisClientType> };
g.redis ??= (async () => {
const client = createClient({ url: process.env.REDIS_URL }) as RedisClientType;
await client.connect();
await ensureSemanticIndex(client, 384);
return client;
})();
const claude = new Anthropic();
const Body = z.object({ question: z.string().trim().min(3).max(1000) });
export async function POST(req: Request) {
const userId = req.headers.get("x-user-id"); // set by your auth middleware, never trusted from the browser
if (!userId) return Response.json({ error: "Sign in first" }, { status: 401 });
const parsed = Body.safeParse(await req.json().catch(() => null));
if (!parsed.success) return Response.json({ error: "Ask a question of 3 to 1000 characters" }, { status: 400 });
try {
const result = await answer({ redis: await g.redis!, claude, embed, dailyBudgetUsd: 0.5 }, userId, parsed.data.question);
return Response.json(
{ answer: result.text, source: result.source },
{ headers: { "Cache-Control": "private, no-store", "X-Answer-Source": result.source } },
);
} catch (err) {
const status = (err as { status?: number }).status === 429 ? 429 : 502;
return Response.json({ error: status === 429 ? "Daily AI budget used up" : "Try again in a moment" }, { status });
}
}
ה-handler שומר חיבור Redis אחד לכל תהליך שרת על globalThis, כך שטעינות מחדש בפיתוח וקריאות חוזרות בפרודקשן לא פותחות חיבור חדש לכל בקשה. dynamic = "force-dynamic" מונע מ-Next.js לשמור את הנתיב עצמו במטמון, ו-Cache-Control: private, no-store מרחיק תשובות ממטמוני HTTP משותפים. הכותרת X-Answer-Source מספרת לכם, בקשה אחר בקשה, איזו שכבה ענתה: רשמו אותה ויש לכם את שיעור הפגיעה. כדי להזרים תשובות לדף, אספו את הטקסט בזמן ההזרמה ושמרו אותו כשהזרם מסתיים; המדריך להזרמת תשובות LLM ב-React מראה את חלק ההזרמה.
בדיקה
// Labelled test questions: each intent has the first wording that reaches the cache, then three rewordings.
// "traps" look similar to a cached question but need a different answer.
export const intents: Record<string, string[]> = {
cancel: ["How do I cancel my subscription?", "how can i cancel my plan", "I want to stop my subscription, how?", "Cancel my Acme plan please"],
reset: ["How do I reset my password?", "forgot my password, what do I do", "Password reset steps?", "I can't remember my password"],
price: ["How much does the Pro plan cost?", "What is the price of Pro?", "Pro plan pricing", "how much is acme pro per month"],
trash: ["How long are deleted files kept?", "How long do files stay in the trash?", "Can I recover a file I deleted last week?", "trash retention period"],
share: ["Can I password-protect a shared link?", "How do I add a password to a share link?", "Is it possible to protect shared links with a password?", "share link password"],
twofa: ["How do I turn on two-factor authentication?", "Enable 2FA", "How can I set up two-step verification?", "Can I use a passkey to secure my account?"],
apps: ["Is there a desktop app for Mac?", "Do you have a macOS app?", "Can I install Acme on my MacBook?", "Mac desktop client"],
annual: ["Is there a discount for paying yearly?", "Do annual plans cost less?", "How much do I save with annual billing?", "yearly billing discount"],
free: ["How much storage does the free plan have?", "What is the free plan storage limit?", "How many GB do I get for free?", "free tier storage"],
after: ["What happens to my files after I cancel?", "Can I still access my files if I cancel?", "Do my files get deleted when I cancel?", "files after cancelling"],
};
export const traps: [string, string][] = [
["How do I cancel a shared link?", "cancel"],
["How do I reset my two-factor authentication?", "reset"],
["How much does the Plus plan cost?", "price"],
["How long do shared links stay valid?", "trash"],
["Can I password-protect a folder on my desktop?", "share"],
["How do I turn off two-factor authentication?", "twofa"],
["Is there a desktop app for Windows?", "apps"],
["Is there a discount for students?", "annual"],
["How much storage does the Pro plan have?", "free"],
["What happens to my files after I delete my account?", "after"],
];
// ...plus 60 less common, distinct questions (longTail) used in the cost simulation
import assert from "node:assert/strict";
import { createClient, type RedisClientType } from "redis";
import type Anthropic from "@anthropic-ai/sdk";
import { answer, costOf, MIN_SIMILARITY, PROMPT_VERSION, type Model } from "../lib/answer";
import { conflicts, ensureSemanticIndex, exactKey } from "../lib/cache";
import { embed, EMBED_DIMS } from "../lib/embed";
import { intents, longTail, traps } from "./questions";
const redis = createClient({ url: "redis://localhost:56380" }) as RedisClientType;
await redis.connect();
await redis.flushAll();
await ensureSemanticIndex(redis, EMBED_DIMS);
// A scripted Claude client that bills like the real API for a support bot with a 3,000-token system
// prompt: about 25 tokens per question and 150 per answer. The prompt cache is written on the first call
// and read on later calls (all of them start within its 5-minute life here).
const SYSTEM_TOKENS = 3000;
function fakeClaude(stop = "end_turn") {
let calls = 0;
let written = false;
const client = {
messages: {
create: async (p: { system: { cache_control?: unknown }[]; messages: { content: string }[] }) => {
calls++;
await new Promise((r) => setTimeout(r, 30));
const cached = Boolean(p.system[0]?.cache_control);
const usage = {
input_tokens: 25 + (cached ? 0 : SYSTEM_TOKENS),
cache_creation_input_tokens: cached && !written ? SYSTEM_TOKENS : 0,
cache_read_input_tokens: cached && written ? SYSTEM_TOKENS : 0,
output_tokens: 150,
};
if (cached) written = true;
return { stop_reason: stop, content: [{ type: "text", text: "Answer: " + p.messages[0].content }], usage };
},
},
};
return { client: client as unknown as Anthropic, calls: () => calls };
}
// ---- 1) Where should the similarity threshold be?
const firsts = Object.entries(intents).map(([intent, qs]) => ({ intent, q: qs[0] }));
const firstVecs = await Promise.all(firsts.map((f) => embed(f.q)));
const dot = (a: Float32Array, b: Float32Array) => a.reduce((s, x, i) => s + x * b[i], 0);
async function closest(q: string) {
const v = await embed(q);
let similarity = -1, intent = "";
firstVecs.forEach((b, i) => {
const s = dot(v, b);
if (s > similarity) { similarity = s; intent = firsts[i].intent; }
});
return { similarity, intent, guarded: conflicts(q, intents[intent][0]) };
}
const rewordings = [];
for (const [intent, qs] of Object.entries(intents)) for (const q of qs.slice(1)) rewordings.push({ want: intent, ...(await closest(q)) });
const trapResults = [];
for (const [q] of traps) trapResults.push(await closest(q));
console.log("threshold | similarity only: right of 30, wrong of 40 | with contrast-word guard: right, wrong");
for (const t of [0.7, 0.75, 0.8, 0.85, 0.9, 0.95]) {
const hit = (r: { similarity: number }) => r.similarity >= t;
const all = [...rewordings, ...trapResults.map((r) => ({ ...r, want: "" }))];
const right = rewordings.filter((r) => hit(r) && r.intent === r.want).length;
const wrong = all.filter((r) => hit(r) && r.intent !== r.want).length;
const gRight = rewordings.filter((r) => hit(r) && !r.guarded && r.intent === r.want).length;
const gWrong = all.filter((r) => hit(r) && !r.guarded && r.intent !== r.want).length;
console.log(" " + t.toFixed(2) + " | " + String(right).padStart(2) + " right, " + wrong + " wrong" + " | " + String(gRight).padStart(2) + " right, " + gWrong + " wrong");
}
// ---- 2) The cache layers, end to end against Redis 8
const fake = fakeClaude();
const deps = { redis, claude: fake.client, embed, dailyBudgetUsd: 100 };
const q0 = intents.cancel[0];
assert.equal((await answer(deps, "u1", q0)).source, "model");
assert.equal((await answer(deps, "u2", q0)).source, "exact");
assert.equal((await answer(deps, "u3", " HOW do I cancel my subscription ")).source, "exact"); // normalised
const reworded = rewordings.find((r) => r.want === "cancel" && r.similarity >= MIN_SIMILARITY);
if (reworded) assert.equal((await answer(deps, "u4", intents.cancel[rewordings.indexOf(reworded) + 1])).source, "semantic");
assert.equal((await answer(deps, "u5", traps[0][0])).source, "model"); // "cancel a shared link" is a different question
await answer(deps, "u6", intents.twofa[0]); // "turn on 2FA" is now cached
assert.equal((await answer(deps, "u7", "How do I turn off two-factor authentication?")).source, "model"); // 0.90 similar, opposite meaning
assert.notEqual(exactKey("claude-haiku-5-5", PROMPT_VERSION, q0), exactKey("claude-haiku-5-5", "new-prompt", q0));
console.log("layers: model, then exact, normalised exact" + (reworded ? ", semantic" : "") + "; a look-alike question still goes to the model; a new prompt version misses");
// Stampede: 20 users ask the same new question at the same moment
const before = fake.calls();
const burst = await Promise.all(Array.from({ length: 20 }, (_, i) => answer(deps, "s" + i, "Does Acme support WebDAV?")));
assert.equal(fake.calls() - before, 1);
console.log("stampede: 20 simultaneous identical questions -> " + (fake.calls() - before) + " model call, sources " + [...new Set(burst.map((b) => b.source))].join("/"));
// Truncated answers are never cached
const cut = fakeClaude("max_tokens");
const cutDeps = { ...deps, claude: cut.client };
await answer(cutDeps, "t1", "Explain every setting in detail");
await answer(cutDeps, "t1", "Explain every setting in detail");
assert.equal(cut.calls(), 2);
// Spend cap per user per day
const capped = { ...deps, claude: fakeClaude().client, dailyBudgetUsd: 0.0004 };
await answer(capped, "heavy", "First question about quotas?");
await assert.rejects(answer(capped, "heavy", "Can I change the email address on my account?"), /budget/); // cached answers stay free
console.log("safety: answers cut by max_tokens are not cached; the daily spend cap returns 429");
// ---- 3) What does each layer save? 1,000 requests: 70% from the 40 common wordings, 30% from 60 less common questions
let seed = 7;
const rand = () => ((seed = (seed * 48271) % 2147483647) / 2147483647);
const common = Object.values(intents).flat();
const traffic = Array.from({ length: 1000 }, (_, i) =>
rand() < 0.7 ? common[Math.floor(rand() * common.length)] : longTail[Math.floor(rand() * longTail.length)],
);
const intentOf = new Map<string, string>();
for (const [id, qs] of Object.entries(intents)) for (const q of qs) intentOf.set(q, id);
async function run(label: string, model: Model, mode: "none" | "prompt" | "exact" | "all") {
await redis.flushAll();
await ensureSemanticIndex(redis, EMBED_DIMS);
const f = fakeClaude();
let cost = 0;
let suspect = 0;
const answered = new Set<string>();
if (mode === "none" || mode === "prompt") {
for (const q of traffic) {
const msg = await (f.client.messages.create as unknown as (p: object) => Promise<{ usage: Anthropic.Usage }>)({
system: [mode === "prompt" ? { cache_control: { type: "ephemeral" } } : {}], messages: [{ content: q }],
});
cost += costOf(model, msg.usage);
}
} else {
const d = { redis, claude: f.client, embed, dailyBudgetUsd: 1000 };
for (const q of traffic) {
const r = await answer(d, "sim", q, { model, semantic: mode === "all" });
cost += r.costUsd;
// a long-tail question answered from the semantic cache borrowed another question's answer
if (r.source === "semantic" && !intentOf.has(q)) suspect++;
answered.add(q);
}
}
return { label, calls: f.calls(), cost, suspect };
}
for (const model of ["claude-haiku-5-5", "claude-sonnet-5-5"] as Model[]) {
const results = [
await run("no caching", model, "none"),
await run("+ prompt caching", model, "prompt"),
await run("+ exact cache", model, "exact"),
await run("+ semantic cache", model, "all"),
];
console.log(model + " per 1,000 requests: " + results.map((r) => r.label + " " + r.calls + " calls $" + r.cost.toFixed(3)).join(" | "));
console.log(" semantic answers given to a long-tail question (probably wrong): " + results[3].suspect);
}
// Embedding cost: local, but not free in time
const t0 = performance.now();
for (const q of common) await embed(q);
console.log("embedding: " + ((performance.now() - t0) / common.length).toFixed(1) + " ms per question on this laptop's CPU");
await redis.quit();
console.log("ALL CACHE TESTS PASS");
docker run -d --name cache-redis -p 56380:6379 redis:8
npx tsx test/cache.test.ts # no API key: the Claude client is scripted
הפלט:
threshold | similarity only: right of 30, wrong of 40 | with contrast-word guard: right, wrong
0.70 | 16 right, 6 wrong | 16 right, 1 wrong
0.75 | 14 right, 3 wrong | 14 right, 0 wrong
0.80 | 11 right, 1 wrong | 11 right, 0 wrong
0.85 | 8 right, 1 wrong | 8 right, 0 wrong
0.90 | 3 right, 1 wrong | 3 right, 0 wrong
0.95 | 1 right, 0 wrong | 1 right, 0 wrong
layers: model, then exact, normalised exact, semantic; a look-alike question still goes to the model; a new prompt version misses
stampede: 20 simultaneous identical questions -> 1 model call, sources model/exact
safety: answers cut by max_tokens are not cached; the daily spend cap returns 429
claude-haiku-5-5 per 1,000 requests: no caching 1000 calls $0.377 | + prompt caching 1000 calls $0.108 | + exact cache 100 calls $0.011 | + semantic cache 89 calls $0.010
semantic answers given to a long-tail question (probably wrong): 0
claude-sonnet-5-5 per 1,000 requests: no caching 1000 calls $7.550 | + prompt caching 1000 calls $1.857 | + exact cache 100 calls $0.192 | + semantic cache 89 calls $0.172
semantic answers given to a long-tail question (probably wrong): 0
embedding: 1.9 ms per question on this laptop's CPU
ALL CACHE TESTS PASS
הלקוח המתוסרט מחייב כמו בוט תמיכה עם פרומפט מערכת של 3,000 טוקנים, שאלות של 25 טוקנים ותשובות של 150 טוקנים, לפי המחירים ב-PRICES. הבדיקה מריצה את הפונקציה answer האמיתית מול Redis 8 והטמעות אמיתיות, כך שמפתחות המטמון, החיפוש הווקטורי, השומר, הנעילה, תקרת ההוצאה והכלל נגד שמירת תשובות קטועות כולם נבדקים.
כמה חוסכת כל שכבה?
בסימולציה, 70% מ-1,000 הבקשות הגיעו מ-40 ניסוחים נפוצים ו-30% מ-60 שאלות פחות נפוצות, כך ש-100 שאלות שונות הרכיבו את התנועה. prompt caching לבדו הוריד את החשבון ב-Sonnet בכ-75%, כי הפרומפט של 3,000 טוקנים נקרא מהמטמון. המטמון המדויק הוריד אחר כך 900 מתוך 1,000 הקריאות. המטמון הסמנטי הוריד עוד 11, בלי שאף תשובה נשאלה לשאלה לא קשורה. כמה תחסכו תלוי כמעט רק בכמה התנועה שלכם חוזרת על עצמה, אז רשמו את מקור התשובה ומדדו את שיעור הפגיעה האמיתי לפני שאתם מבטיחים מספר.
גרסה מוקדמת של הסימולציה השתמשה בשאלות חד-פעמיות מומצאות שנבדלו רק במספר ("question 5 about folder sync", "question 6..."). המטמון הסמנטי ענה בשמחה על 290 מהן בתשובה אחת. שאלות אמיתיות מגוונות יותר, אבל הלקח נשאר: שאלות שנבדלות רק במספר, בשם או במזהה נראות זהות למודל הטמעות.
ביטול תוקף: לשמור על תשובות עדכניות
- גרסה במפתח:
PROMPT_VERSIONהוא גיבוב של פרומפט המערכת והעובדות שלו, כך שעריכה שלהם הופכת כל תשובה ישנה ללא נגישה בבת אחת, בלי לרוקן את המטמון. - השתמשו ב-TTL: 24 שעות לתשובות מדויקות ו-7 ימים לאינדקס הסמנטי כאן. קצר יותר לעובדות שמשתנות הרבה, כמו מחירים או מלאי.
- מחקו לפי אירועים: כשעובדה על המוצר משתנה, העלו את גרסת הפרומפט; לתוכן שקשור למסמך אחד, כללו את גרסת המסמך במפתח.
- הפרידו שדרוגי מודל: שם המודל הוא חלק מכל מפתח, כך שמעבר מ-Haiku ל-Sonnet לעולם לא מגיש תשובה שנכתבה על ידי המודל השני.
מה לעולם לא לשמור במטמון
אל תשתפו תשובות שמורות בין משתמשים כשהשאלה נוגעת בנתונים שלהם (הזמנות, חשבוניות, הודעות); או שתוותרו על המטמון הסמנטי ותוסיפו את מזהה המשתמש למפתח, או שלא תשמרו בכלל. אל תשמרו תשובות שתלויות בזמן, במלאי חי או במחירים, אלא אם ה-TTL קצר. אל תשמרו סירובים, שגיאות או תשובות קטועות. והיזהרו עם מידע אישי בשאלות שמורות: המטמון הוא עותק של מה שמשתמשים הקלידו, אז תנו לו TTL וכללו אותו בתהליך מחיקת הנתונים שלכם.
טעויות נפוצות ואיך לתקן אותן
| טעות | מה קורה | תיקון |
|---|---|---|
| חותמת זמן או שם משתמש בפרומפט המערכת | ה-prompt cache לא פוגע אף פעם; מפתחות המטמון לא חוזרים | השאירו את הפרומפט קבוע; שימו נתונים לכל בקשה בהודעה |
| מפתח מטמון בלי מודל או גרסת פרומפט | תשובות ישנות מוגשות אחרי שינוי פרומפט | גבבו את המודל והפרומפט לתוך המפתח |
| סף סמנטי שנבחר לפי תחושה | שאלות הפוכות מקבלות אותה תשובה | מדדו על שאלות מתויגות; הוסיפו שומר מילים מנוגדות |
| שמירת תשובות קטועות או סירובים | תשובה גרועה מוגשת כל היום | שמרו רק stop_reason "end_turn" |
| אין נעילה על שאלות חדשות | קפיצה בתנועה משלמת על אותה תשובה פעמים רבות | נעילת SET NX; האחרים מחכים לתשובה השמורה |
| פענוח ידני של תשובות FT.SEARCH גולמיות | תוצאות נעלמות בשקט ב-RESP3 | השתמשו בעזר ft.search של הלקוח |
| מטמון משותף לשאלות אישיות | משתמש אחד רואה תשובה של אחר | מפתחות לכל משתמש, בלי מטמון סמנטי לנתונים פרטיים |
מגבלות
העלויות כאן מגיעות מסימולציה עם לקוח מתוסרט, לא מחשבון אמיתי: ספירות הטוקנים, שיעורי הפגיעה וההתנהגות של ה-prompt cache בתנועה שלכם יהיו שונים, אז מדדו עם שדות ה-usage וכותרת מקור התשובה. הסף נבחר על 40 שאלות מתויגות, מספיק כדי להראות את הסיכון אבל לא כדי להוכיח ערך למוצר שלכם. שומר המילים המנוגדות מכיר רק את המילים שנתתם לו. ומטמון לא יכול לעזור למוצר שכל השאלות בו שונות, כמו עוזר קוד שעובד על קוד פרטי; שם prompt caching ובחירת מודל חשובים יותר.
מדידה בפרודקשן
רשמו ארבעה מספרים לכל בקשה: מקור התשובה (מדויק, סמנטי או מודל), טוקני קלט ופלט, טוקני קלט שמורים מ-cache_read_input_tokens, והעלות. מהם מקבלים את שיעור הפגיעה של כל שכבה, את שיעור הפגיעה של ה-prompt cache ואת העלות לשאלה שנענתה. עברו על מדגם של פגיעות סמנטיות כל שבוע והוסיפו כל זוג שגוי לסט המתויג, ואם מתאים, לקבוצות המילים המנוגדות. לצד האבטחה של אותו endpoint, הגבלות קצב ו-prompt injection, ראו את המדריך לאבטחת APIs של AI; לתשובות שמבוססות על המסמכים שלכם, ראו את צנרת ה-RAG ב-Next.js.
שאלות נפוצות
איך שומרים תשובות LLM במטמון ב-Next.js?
ב-route handler על runtime של Node.js, גבבו את המודל, גרסת הפרומפט והשאלה המנורמלת למפתח Redis, החזירו את התשובה השמורה אם קיימת, ואחרת קראו למודל ושמרו את התשובה השלמה עם TTL.
מה זה מטמון סמנטי?
מטמון שמשתמש שוב בתשובה כששאלה חדשה אומרת את אותו הדבר כמו שאלה שכבר נענתה, ומוצא אותה בהשוואת הטמעות בחיפוש וקטורי במקום התאמה מדויקת של הטקסט.
באיזה סף דמיון צריך מטמון סמנטי להשתמש?
מדדו אותו על השאלות המתויגות שלכם. בבדיקה של המאמר, 0.80 עם שומר מילים מנוגדות השתמש שוב ב-11 מתוך 30 ניסוחים בלי תשובות שגויות; דמיון לבדו נתן תשובות שגויות מתחת ל-0.95.
האם מטמון סמנטי יכול לתת תשובות שגויות?
כן. "Turn off 2FA" קיבל 0.90 מול "turn on 2FA" בבדיקה. הוסיפו שומר למילים שהופכות משמעות ובדקו על שאלות דומות למראה.
מה ההבדל בין prompt caching למטמון תשובות?
prompt caching נעשה אצל ספק המודל ומוזיל את התחילית החוזרת של הפרומפט בכל קריאה. מטמון תשובות נעשה אצלכם ומדלג על הקריאה כולה כשהתשובה כבר ידועה.
כמה חוסך ה-prompt caching של Claude?
כתיבה למטמון עולה 1.25 ממחיר הקלט וקריאה חלק קטן ממנו; ב-Claude Sonnet 5.5 קריאות עולות 0.10$ למיליון טוקנים מול 2$. בסימולציה זה הוריד את החשבון בכ-75%.
למה ה-prompt cache שלי לא פוגע?
התחילית חייבת להיות זהה בייט אחר בייט וארוכה מהמינימום של המודל (512 טוקנים במודלי Claude הנוכחיים). תאריך, שם משתמש או סדר כלים שונה בפרומפט שוברים אותו.
מה זה cache stampede ואיך מונעים אותו?
הרבה בקשות לאותו פריט שלא במטמון שמגיעות בבת אחת, וכל אחת עושה את העבודה היקרה. נעילת SET NX ב-Redis נותנת לבקשה אחת לקרוא למודל בזמן שהאחרות מחכות לתשובה השמורה.
האם לשמור תשובות על הנתונים של המשתמש עצמו?
לא במטמון משותף. הוסיפו את מזהה המשתמש למפתח וכבו את המטמון הסמנטי לשאלות האלה, או אל תשמרו אותן.
איך מבטלים תשובות LLM שמורות כשהפרומפט משתנה?
שימו גיבוב של הפרומפט בכל מפתח מטמון. פרומפט שהשתנה יוצר מפתחות חדשים, כך שתשובות ישנות לא מוגשות, וה-TTL מנקה אותן.
אפשר להשתמש ב-Redis לחיפוש וקטורי?
כן. Redis 8 כולל את Query Engine, שתומך בשדות וקטור עם אינדקסי HNSW ובשאילתות KNN דרך FT.SEARCH.
האם מטמון עובד עם תשובות מוזרמות?
כן. הזרימו את התשובה למשתמש, אספו את הטקסט כשהוא מגיע, ושמרו אותו במטמון כשהזרם מסתיים כרגיל.