LLM Apps in Production (RAG + Vector DB + Caching) · Урок

Семантическое кэширование ответов LLM

Узнайте, как семантическое кэширование повторно использует ответы для похожих запросов, сопоставляя их по смыслу, а не по точному тексту, и значительно сокращает расходы и задержку LLM.

Урок 4 из 413 шагов

«Семантическое кэширование ответов LLM» — бесплатный урок LLM Apps in Production (RAG + Vector DB + Caching) на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения LLM Apps in Production (RAG + Vector DB + Caching), и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс LLM Apps in Production (RAG + Vector DB + Caching) содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Beyond Exact-Match Caching

A normal cache only hits when the key is byte-identical. But 'What is your refund policy?' and 'How do refunds work?' mean the same thing yet miss an exact cache.

Semantic caching matches on meaning, so paraphrases reuse the same answer.

How It Works

The flow:

  • Embed the incoming query into a vector
  • Search the cache for a near-by stored query
  • If similarity exceeds a threshold, return the cached answer
  • Otherwise call the LLM and store the new pair

Embedding the Query

Each query is converted to a vector by an embedding model. Similar meanings produce nearby vectors.

def embed(text):
    return [len(text), text.count('refund'), text.count('?')]

print(embed('How do refunds work?'))

Cosine Similarity

Similarity between query vectors is usually measured with cosine similarity.

import math

def cosine(a, b):
    dot = sum(x*y for x, y in zip(a, b))
    na = math.sqrt(sum(x*x for x in a))
    nb = math.sqrt(sum(y*y for y in b))
    return dot / (na * nb)

print(round(cosine([1,2,1],[1,2,0]), 3))

Choosing the Threshold

The similarity threshold is the key tuning knob:

  • Too low -> false hits, wrong answers served
  • Too high -> few hits, little savings

Tune it on real traffic and err conservative for high-stakes domains.

A Minimal Semantic Cache

Putting embedding, similarity, and a threshold together.

cache = []
THRESH = 0.95

def get(query, qvec):
    for stored_vec, ans in cache:
        if cosine(qvec, stored_vec) >= THRESH:
            return ans
    return None

def cosine(a, b):
    return 1.0 if a == b else 0.0

cache.append(([1,0], 'Refunds take 5 days'))
print(get('q', [1,0]))

When NOT to Cache

Semantic caching is wrong for queries whose answer depends on changing or personal state:

  • 'What is my account balance?'
  • 'What is today's weather?'
  • Anything user-specific or time-sensitive

Cache only stable, general knowledge.

Scoping the Cache

To avoid leaking one user's data to another, scope cache keys by tenant, language, and any relevant context. A global cache for personalized answers is a privacy bug.

Eviction and Freshness

Cached answers go stale when source data changes. Add TTLs and invalidate entries when underlying documents update, so the cache does not serve outdated answers.

Measuring Savings

Track hit rate, cost saved, and latency improvement. A 40 percent semantic hit rate can roughly translate into a 40 percent reduction in LLM spend for cacheable traffic.

Production Stack

In production, store query embeddings in a vector DB or Redis with vector search, set a tuned threshold, scope by tenant, apply TTLs, and monitor hit rate. Combine with exact caching for the best coverage.

Quick Check

Test your understanding of semantic caching.

Recap

You learned that semantic caching reuses answers for paraphrased queries by embedding them and matching via cosine similarity above a tuned threshold. Cache only stable knowledge, scope by tenant for privacy, apply TTLs for freshness, and monitor hit rate to quantify savings.

Можно начать бесплатно

Изучай LLM Apps in Production (RAG + Vector DB + Caching) с ИИ-репетитором — бесплатно

Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.

Курсы
12
Уроки
48

Часто задаваемые вопросы

Урок «Семантическое кэширование ответов LLM» бесплатный?

Да — полный текст урока «Семантическое кэширование ответов LLM» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс LLM Apps in Production (RAG + Vector DB + Caching), подпишись на CoddyKit PRO. Курс LLM Apps in Production (RAG + Vector DB + Caching) содержит 4 уроков всего.

Чему я научусь в уроке «Семантическое кэширование ответов LLM»?

Узнайте, как семантическое кэширование повторно использует ответы для похожих запросов, сопоставляя их по смыслу, а не по точному тексту, и значительно сокращает расходы и задержку LLM. Ты практикуешь LLM Apps in Production (RAG + Vector DB + Caching) с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать LLM Apps in Production (RAG + Vector DB + Caching)?

Предыдущий опыт не требуется. LLM Apps in Production (RAG + Vector DB + Caching) на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Семантическое кэширование ответов LLM»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке LLM Apps in Production (RAG + Vector DB + Caching)?

Да. Каждый урок LLM Apps in Production (RAG + Vector DB + Caching) включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Распределённое кэширование с Redis и Memcached
  2. Управление сеансами и сохранение контекста
  3. Продвинутые стратегии инвалидации кэша
  4. Семантическое кэширование ответов LLM
← Назад к LLM Apps in Production (RAG + Vector DB + Caching)