redis-semantic-cache — скилл для Claude Code: кэш ответов LLM
Скилл объясняет, как поставить семантический кэш LangCache перед вызовом модели: похожие промпты получают готовый ответ без нового запроса.
npx skills add redis/agent-skills --skill redis-semantic-cache -a claude-codeЧто делает redis-semantic-cache
Скилл описывает схему cache-aside для ответов LLM. Промпт уходит в search сервиса LangCache, при попадании вы получаете сохранённый ответ сразу, при промахе — вызываете модель и кладёте результат через set. Так работают и с OpenAI, и с Anthropic, и с любым другим провайдером: кэш стоит отдельным слоем перед вызовом.
Внутри — три темы. Порог похожести similarity_threshold решает, насколько близким должен быть промпт к сохранённому: 0.95 и выше для ответов клиентам, 0.9 как сбалансированное начало, 0.8 для внутренних инструментов и дедупликации вопросов. Отдельно разобрано разделение кэшей по типу задачи: вопросы про код и запросы в поддержку не должны жить в одном кэше, иначе на похожий промпт вернётся чужая выдача. Вместо второго кэша можно фильтровать по своим атрибутам, например {"category": "database"}.
Работает это на Redis Cloud, и сервис LangCache там в статусе preview — поведение и функции могут поменяться, так что перед продакшеном стоит перепроверить документацию. Нужны server_url, cache_id и api_key; примеры в скилле берут их из переменных окружения HOST, CACHE_ID и API_KEY. Если SDK не подходит, те же операции доступны по REST.
Какие задачи решает
- поставить кэш перед вызовом LLM, чтобы не платить за повторные запросы
- подобрать порог похожести под свой сценарий
- развести кэши по типам задач, чтобы ответы не смешивались
- отфильтровать записи по своим атрибутам внутри одного кэша
- перейти на REST, когда SDK не подходит
Примеры запросов агенту
- Покажи, как обернуть вызов LLM в LangCache по схеме cache-aside
- Какой similarity_threshold выбрать для ответов клиентам?
- Раздели кэш поддержки и кэш вопросов про код на два cache_id
Как установить redis-semantic-cache
1Через Skills CLI (Vercel)
npx skills add redis/agent-skills --skill redis-semantic-cache -a claude-code2Вручную: положить файлы
~/.claude/skills/redis-semantic-cache/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/redis-semantic-cache/
1Через Skills CLI (Vercel)
npx skills add redis/agent-skills --skill redis-semantic-cache -a codex2Вручную: положить файлы
.agents/skills/redis-semantic-cache/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add redis/agent-skills --skill redis-semantic-cache -a cursor2Вручную: положить файлы
.cursor/skills/redis-semantic-cache/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install redis/agent-skills redis-semantic-cache2Вручную: положить файлы
.github/skills/redis-semantic-cache/SKILL.md1Через Skills CLI (Vercel)
npx skills add redis/agent-skills --skill redis-semantic-cache -a gemini-cli2Командой платформы
gemini skills install https://github.com/redis/agent-skills --path skills/redis-semantic-cacheВручную: положить файлы
.devin/skills/redis-semantic-cache/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add redis/agent-skills --skill redis-semantic-cache -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о redis-semantic-cache
Как установить redis-semantic-cache в Claude?
Выполните npx skills add redis/agent-skills --skill redis-semantic-cache -a claude-code. Скилл окажется в ~/.claude/skills/redis-semantic-cache/SKILL.md.
Что делает redis-semantic-cache?
Описывает семантический кэш LangCache на Redis Cloud: поиск похожего промпта, возврат сохранённого ответа, запись нового и настройку порога похожести.
Что нужно для работы LangCache?
Аккаунт Redis Cloud с сервисом LangCache, а также server_url, cache_id и api_key. Сервис сейчас в статусе preview, поэтому поведение может меняться.
Исходный текст
SKILL.md · MIT
---
name: redis-semantic-cache
description: Redis LangCache guidance for semantic caching of LLM responses on Redis Cloud — calling search/set via the SDK or REST API, tuning the similarity threshold, separating caches per task type, and filtering with custom attributes. Use when caching LLM completions or RAG answers to cut API cost and latency, building a cache-aside layer in front of OpenAI / Anthropic / etc., tuning hit rate vs precision, or splitting one app's LLM workloads into multiple LangCache caches.
license: MIT
metadata:
author: Redis, Inc.
version: "0.1.0"
---
# Redis Semantic Cache
Semantic caching for LLM responses with Redis Cloud's LangCache service. Stores prompts as embeddings; subsequent semantically-similar prompts return the cached response without re-calling the model.
> LangCache is currently in **preview** on Redis Cloud. Features and behavior may change.
## When to apply
- Wrapping an LLM call (OpenAI, Anthropic, etc.) with a cache layer to cut cost and latency.
- Caching RAG answers, classification outputs, or any deterministic LLM workload.
- Tuning the precision/hit-rate trade-off for a semantic cache.
- Splitting one application's LLM workloads across multiple cache instances.
## 1. The cache-aside flow
LangCache fits in front of any LLM call as a standard cache-aside pattern:
1. Send the user's prompt to LangCache's `search`.
2. **Cache hit** — return the stored response directly.
3. **Cache miss** — call the LLM, then `set` the response so future similar prompts hit.
```python
from langcache import LangCache
import os
lang_cache = LangCache(
server_url=f"https://{os.getenv('HOST')}",
cache_id=os.getenv("CACHE_ID"),
api_key=os.getenv("API_KEY"),
)
result = lang_cache.search(prompt="What is Redis?", similarity_threshold=0.9)
if result:
response = result[0]["response"]
else:
response = llm.generate("What is Redis?")
lang_cache.set(prompt="What is Redis?", response=response)
```
The same operations are available via REST (`POST /v1/caches/{cacheId}/entries/search` and `POST /v1/caches/{cacheId}/entries`) when an SDK isn't an option.
See [references/langcache-usage.md](references/langcache-usage.md) for full SDK + REST samples and attribute-based storage.
## 2. Tune the similarity threshold
The threshold controls how close (in embedding cosine distance) a new prompt must be to a cached one to count as a hit. Higher = stricter match, fewer false positives. Lower = more hits, more risk of returning an off-topic answer.
| Threshold | Behavior | Use when |
|---|---|---|
| 0.95+ | Near-exact match required | Customer-facing answers where wrong responses are costly |
| 0.9 | Balanced default | Most workloads — start here |
| 0.8 | Loose semantic match | Internal tools, exploratory queries, FAQ deduplication |
```python
# Stricter — fewer false positives
result = lang_cache.search(prompt="What is Redis?", similarity_threshold=0.95)
# Looser — higher hit rate
result = lang_cache.search(prompt="What is Redis?", similarity_threshold=0.8)
```
Adjust by watching the actual cache-hit rate and spot-checking that returned answers are still relevant.
See [references/best-practices.md](references/best-practices.md).
## 3. Separate caches per task type
Different LLM workloads should not share one cache — a "code question" prompt is semantically close to other code questions but has nothing to do with a password-reset support query, and crossing them returns garbage.
```python
support_cache = LangCache(server_url=..., cache_id="support-cache-id", api_key=...)
code_cache = LangCache(server_url=..., cache_id="code-cache-id", api_key=...)
```
Create distinct cache IDs in Redis Cloud per task, and route each call to the right one. As a finer-grained alternative, store and search with **custom attributes** (e.g. `{"category": "database"}`) to keep tasks in the same cache but isolated by attribute filter — useful when the same prompt format spans subtopics.
## References
- [LangCache documentation](https://redis.io/docs/latest/develop/ai/langcache/)
© Redis, Inc. · MIT · redis/agent-skills