redis-semantic-cache

작성자: redis

Redis LangCache를 사용하여 Redis Cloud에서 LLM 응답의 시맨틱 캐싱을 수행하는 방법 — SDK 또는 REST API를 통한 검색/설정 호출, 유사도 임계값 조정,…

npx skills add https://github.com/redis/agent-skills --skill redis-semantic-cache

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.
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 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.

ThresholdBehaviorUse when
0.95+Near-exact match requiredCustomer-facing answers where wrong responses are costly
0.9Balanced defaultMost workloads — start here
0.8Loose semantic matchInternal tools, exploratory queries, FAQ deduplication
# 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.

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.

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

redis의 다른 스킬

docs-sync
redis
마스터 브랜치의 구현 및 구성을 분석하여 docs/, README.md, 패키지별 README에서 누락되거나, 부정확하거나, 오래된 문서를 찾습니다.
official
implement-command
redis
Add a new Redis command (or command variant) to node-redis end-to-end — the `<NAME>.ts` Command file, its registration with JSDoc in the package…
official
maintainer-review
redis
GitHub 이슈 또는 풀 리퀘스트 URL을 node-redis 관리자로서 검토하고, 해당 주장이 실제인지, 실질적으로 중요한지, 이미 처리되었는지에 대한 단계적 평가를 수행합니다.
official
pr-draft-summary
redis
node-redis에 필요한 PR 준비 요약 블록, 브랜치 제안, 제목 및 초안 설명을 생성합니다. 최종 응답 전에 항상 사용해야 합니다...
official
runtime-behavior-probe
redis
임시 TypeScript 프로브 스크립트, 검증 매트릭스, 상태 제어, 결과 우선 보고서를 사용하여 runtime-behavior-probe 조사를 계획하고 실행합니다. 사용…
official
backend
redis
NestJS 백엔드 개발 패턴: RedisInsight API를 위한 모듈 구조, 서비스, 컨트롤러, DTO, 의존성 주입 및 오류 처리. 다음 경우에 사용…
official
branches
redis
소문자 케밥 케이스에 유형 접두사와 이슈/티켓 식별자를 사용하세요. 브랜치 이름은 GitHub Actions 워크플로우 규칙(.github/workflows/enforce-branch-name-rules.yml 참조)과 일치해야 합니다.
official
code-quality
redis
Code-quality standards for RedisInsight: TypeScript strictness, naming conventions (camelCase, PascalCase, UPPER_SNAKE_CASE), linting rules, no `any` without…
official