rag-production
БесплатноБез исполняемых скриптовНе проверенOperational concerns for RAG at scale. Incremental indexing (CDC, doc diffing), blue-green re-indexing, index aliases/versioning, embedding-model hot-swap…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
RAG in Production
Incremental Indexing
Never reindex the whole corpus on every change. Three trigger sources:
- Change Data Capture (CDC) from the source database (Debezium, native Postgres logical replication).
- Document diffing on filesystem/S3: store
sha256 + last_modifiedper doc; reprocess when changed. - Event-driven: producer emits
doc.created | doc.updated | doc.deletedon a queue.
# Doc diffing example
import hashlib, json, pathlib
STATE = pathlib.Path(".index_state.json")
state = json.loads(STATE.read_text()) if STATE.exists() else {}
def scan_and_upsert(root: pathlib.Path):
seen = set()
for p in root.rglob("*.md"):
content = p.read_bytes()
h = hashlib.sha256(content).hexdigest()
key = str(p)
seen.add(key)
if state.get(key) != h:
reindex_document(key, content.decode())
state[key] = h
for key in list(state.keys()) - seen:
delete_from_index(key)
state.pop(key, None)
STATE.write_text(json.dumps(state))
At chunk level, store doc_id + chunk_hash; on doc update, delete chunks where chunk_hash is no longer present, insert new ones.
Blue-Green Re-indexing (Full Rebuild)
Required when changing embedding model, chunking strategy, or schema. Never rebuild in place.
# Pinecone: use different index names and swap at the application layer
# Weaviate/Qdrant/Elasticsearch: use index aliases
# Elasticsearch
client.indices.create(index="docs_v42", body=mapping)
# ... reindex into docs_v42 ...
client.indices.update_aliases(actions=[
{"remove": {"index": "docs_v41", "alias": "docs"}},
{"add": {"index": "docs_v42", "alias": "docs"}},
])
# Keep docs_v41 around for fast rollback, delete after N days
Validation gate before switching the alias: run a golden eval set against both indexes, require new index recall@5 >= old - 1%.
Hot-Swap of Embedding Models
Changing embedding model invalidates the entire index. Procedure:
- Build
index_v{new}offline with new embeddings. - Shadow: send 10% of live queries to both indexes, log differences.
- Gate on eval metrics + shadow diff rate.
- Flip alias; keep old index warm for 72h.
- Invalidate semantic caches (they contain old embeddings).
Track embedding_model_version in .dev-suite-manifest.json style metadata alongside the index.
Index Versioning and Aliases
| Pattern | Vector DB | Example |
|---|---|---|
| Alias | Elasticsearch, OpenSearch, Weaviate | alias docs -> docs_v42 |
| Namespace/collection | Pinecone, Qdrant, Chroma | app reads COLLECTION_NAME env |
| Tenant prefix | Pinecone namespace | tenant_{id}_v42 |
Always deploy through the alias/env var. Never hardcode index names in application code.
Cost Optimization
| Lever | Savings | Tradeoff |
|---|---|---|
Use cheaper embedding model (e.g., text-embedding-3-small vs -large) |
6x | 2-4% recall loss; test |
| Reduce embedding dimension (Matryoshka models) | 2-4x storage, faster search | Small recall loss per halving |
| Product Quantization (pgvector IVFFlat+PQ, Qdrant SQ) | 4-32x storage | Recall drop; rerank to recover |
Smaller k + rerank |
2x query cost, better quality | Extra rerank call |
| Filter before ANN search | Big wins on multi-tenant | Requires selective metadata |
| Haiku/gpt-4o-mini for extraction, Opus/GPT-4o only for synthesis | 10-20x | Prompt engineering per tier |
| Prompt caching (provider) | 10x on static prefix | Prefix must be >= min tokens |
| Batch embedding requests | 2x throughput, fewer HTTP | Tail-latency on small batches |
Matryoshka Embedding Truncation
OpenAI text-embedding-3-* and Nomic nomic-embed-text-v1.5 expose dimensions parameter; truncate then L2-renormalize.
import numpy as np
def truncate_renorm(v: list[float], d: int = 512) -> list[float]:
arr = np.array(v[:d], dtype=np.float32)
return (arr / np.linalg.norm(arr)).tolist()
SLA Targets
| Tier | p50 | p95 | p99 |
|---|---|---|---|
| Retrieval only | 50ms | 150ms | 300ms |
| Retrieval + rerank | 150ms | 400ms | 800ms |
| Full RAG (small model) | 600ms | 1.5s | 3s |
| Full RAG (large model) | 1.5s | 4s | 8s |
Measure per stage. Streaming (SSE) the LLM response lets you hide a 2s generation behind first-token latency of ~400ms.
Capacity Planning
Simple model for ANN capacity:
memory_bytes ~= num_vectors * (4 * dim + 24) # float32 + HNSW overhead
+ index_metadata (~20%)
QPS_per_replica ~= 1000ms / p95_query_ms * parallelism_factor(0.6-0.8)
replicas = ceil(target_qps / QPS_per_replica) + 1 (headroom)
Rules of thumb:
- Keep per-replica index size < 50 GB for in-memory HNSW (else shard).
- Plan for 2x query volume spikes (traffic + rebuild catch-up).
- Reserve 30% CPU headroom on embedding/rerank servers; GPU utilization target 60-70%.
Horizontal Scaling Patterns
| Component | Scaling axis | Notes |
|---|---|---|
| Embedder | Stateless |
Установить rag-production в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditFAQ
Что делает скилл rag-production?
Operational concerns for RAG at scale. Incremental indexing (CDC, doc diffing), blue-green re-indexing, index aliases/versioning, embedding-model hot-swap, cost optimization (dimension reduction, cheaper embed models), capacity and token budgets, p50/p95/p99 SLAs, horizontal scaling, multi-tenant isolation, async ingestion (Kafka/Pub-Sub). USE WHEN: user mentions "incremental indexing", "reindex", "index alias", "blue-green reindex", "RAG cost optimization", "multi-tenant RAG", "RAG capacity planning", "async ingestion", "CDC for RAG", "embedding model swap" DO NOT USE FOR: caching - use `rag-caching`; tracing/metrics - use `rag-observability`; access control / PII - use `rag-security`
Как установить скилл rag-production?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл rag-production запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic