Provides a comprehensive production deployment checklist for RAG systems covering data indexing, retrieval, generation, monitoring, and operations.
Ships in rag-architect. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Everything you need to deploy RAG systems that are reliable, scalable, and maintainable.
Document pipeline defined
Index refresh strategy
Data quality
Metadata on every chunk
Embedding pipeline robust
Retrieval strategy selected
Embeddings
Vector store
m, ef_construction, query-time ef) and checked against recall and latency on your dataAccess control enforced at retrieval
LLM configuration
Prompt engineering
Fallback responses defined
Evaluation baseline
rag-evaluation)┌─────────────────────────────────────────────────────────────┐
│ Load Balancer │
└─────────────────────────────────────────────────────────────┘
│
┌───────────────┼───────────────┐
▼ ▼ ▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ API Server │ │ API Server │ │ API Server │
│ (Stateless) │ │ (Stateless) │ │ (Stateless) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │ │
└───────────────┼───────────────┘
│
┌───────────────┼───────────────┐
▼ ▼ ▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Redis Cache │ │ Vector Store │ │ LLM Gateway │
│ (Query Cache) │ │ (Retrieval) │ │ (Rate Limit) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
import asyncio
import time
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class QueryRequest(BaseModel):
query: str
top_k: int = 5
filters: dict | None = None
@app.post("/query")
async def query_rag(request: QueryRequest):
start = time.perf_counter()
try:
result = await asyncio.wait_for(rag.query(request.query, request.top_k, request.filters), timeout=30.0)
except asyncio.TimeoutError:
raise HTTPException(status_code=504, detail="Query timed out")
except Exception:
logger.exception("rag_error")
raise HTTPException(status_code=500, detail="Internal error") # don't leak details
return {
"answer": result["answer"],
"sources": [d.metadata["source"] for d in result["documents"]],
"latency_ms": (time.perf_counter() - start) * 1000,
}
Add per-user rate limiting at the gateway or with middleware (for example slowapi for FastAPI).
from abc import ABC, abstractmethod
class LLMProvider(ABC):
@abstractmethod
async def generate(self, prompt: str, **kwargs) -> str:
pass
class OpenAIProvider(LLMProvider):
async def generate(self, prompt: str, **kwargs) -> str:
# OpenAI implementation
pass
class AnthropicProvider(LLMProvider):
async def generate(self, prompt: str, **kwargs) -> str:
# Anthropic implementation
pass
class RAGService:
def __init__(self, llm_provider: LLMProvider, retriever):
self.llm = llm_provider
self.retriever = retriever
async def query(self, question: str) -> str:
docs = await self.retriever.ainvoke(question)
context = self._format_context(docs)
return await self.llm.generate(
f"Context: {context}\n\nQuestion: {question}"
)
The cache key must include everything that changes the answer: the query, filters, and the caller's permission scope. Otherwise one user's cached answer can leak documents to another.
import hashlib
import json
import redis
class RAGCache:
def __init__(self, redis_client: redis.Redis, ttl: int = 3600):
self.redis = redis_client
self.ttl = ttl
def _cache_key(self, query: str, filters: dict | None, acl_scope: str) -> str:
raw = json.dumps({"q": query, "f": filters or {}, "acl": acl_scope}, sort_keys=True)
return f"rag:query:{hashlib.sha256(raw.encode()).hexdigest()}"
async def get_or_compute(self, query: str, filters: dict | None, acl_scope: str, compute_fn) -> dict:
key = self._cache_key(query, filters, acl_scope)
cached = self.redis.get(key)
if cached:
return json.loads(cached)
result = await compute_fn(query, filters)
self.redis.setex(key, self.ttl, json.dumps(result))
# Remember which cache entries used which sources, for invalidation
for source in result.get("sources", []):
self.redis.sadd(f"rag:by_source:{source}", key)
return result
def invalidate_source(self, source: str):
"""Call when a source document changes or is deleted."""
keys = self.redis.smembers(f"rag:by_source:{source}")
if keys:
self.redis.delete(*keys)
self.redis.delete(f"rag:by_source:{source}")
class EmbeddingCache:
"""Cache embeddings to avoid recomputation."""
def __init__(self, redis_client: redis.Redis):
self.redis = redis_client
def get_embedding(self, text: str) -> list[float] | None:
key = f"emb:{hashlib.md5(text.encode()).hexdigest()}"
cached = self.redis.get(key)
return json.loads(cached) if cached else None
def set_embedding(self, text: str, embedding: list[float]):
key = f"emb:{hashlib.md5(text.encode()).hexdigest()}"
self.redis.setex(key, 86400 * 7, json.dumps(embedding)) # 7 days
class ResilientRAG:
"""RAG with comprehensive error handling."""
def __init__(self, primary_llm, fallback_llm, retriever):
self.primary_llm = primary_llm
self.fallback_llm = fallback_llm
self.retriever = retriever
async def query(self, question: str) -> dict:
try:
# Retrieval with timeout
docs = await asyncio.wait_for(
self.retriever.ainvoke(question),
timeout=5.0
)
except asyncio.TimeoutError:
logger.warning("Retrieval timeout, using empty context")
docs = []
except Exception as e:
logger.error(f"Retrieval error: {e}")
docs = []
if not docs:
return {
"answer": "I couldn't find relevant information to answer your question.",
"sources": [],
"status": "no_results"
}
context = self._format_context(docs)
# Try primary LLM
try:
answer = await asyncio.wait_for(
self.primary_llm.generate(question, context),
timeout=30.0
)
return {"answer": answer, "sources": docs, "status": "success"}
except Exception as e:
logger.warning(f"Primary LLM failed: {e}, trying fallback")
# Try fallback LLM
try:
answer = await self.fallback_llm.generate(question, context)
return {"answer": answer, "sources": docs, "status": "fallback"}
except Exception as e:
logger.error(f"Fallback LLM failed: {e}")
return {
"answer": "I'm having trouble generating a response. Please try again.",
"sources": docs,
"status": "error"
}
import structlog
logger = structlog.get_logger()
async def monitored_query(rag, query: str, user_id: str) -> dict:
"""Query with comprehensive logging."""
request_id = str(uuid.uuid4())
logger.info(
"rag_query_started",
request_id=request_id,
user_id=user_id,
query_length=len(query)
)
start = time.perf_counter()
try:
# Retrieval
retrieval_start = time.perf_counter()
docs = await rag.retriever.ainvoke(query)
retrieval_ms = (time.perf_counter() - retrieval_start) * 1000
logger.info(
"rag_retrieval_complete",
request_id=request_id,
num_docs=len(docs),
latency_ms=retrieval_ms
)
# Generation
gen_start = time.perf_counter()
answer = await rag.generate(query, docs)
gen_ms = (time.perf_counter() - gen_start) * 1000
total_ms = (time.perf_counter() - start) * 1000
logger.info(
"rag_query_complete",
request_id=request_id,
retrieval_ms=retrieval_ms,
generation_ms=gen_ms,
total_ms=total_ms,
answer_length=len(answer)
)
return {"answer": answer, "request_id": request_id}
except Exception as e:
logger.error(
"rag_query_failed",
request_id=request_id,
error=str(e),
error_type=type(e).__name__
)
raise
# Prometheus metrics example
from prometheus_client import Counter, Histogram, Gauge
# Counters
rag_queries_total = Counter(
'rag_queries_total',
'Total RAG queries',
['status'] # success, no_results, error
)
# Histograms
rag_latency = Histogram(
'rag_latency_seconds',
'RAG query latency',
['stage'], # retrieval, generation, total
buckets=[0.1, 0.5, 1.0, 2.0, 5.0, 10.0]
)
# Gauges
rag_index_size = Gauge(
'rag_index_document_count',
'Number of documents in RAG index'
)
Example starting thresholds; set real ones from your baseline and SLOs:
| Metric | Example Alert Threshold |
|---|---|
| P95 latency | >5 seconds |
| Error rate | >5% |
| Cache hit rate | <50% |
| Empty results rate | >20% |
| LLM fallback rate | >10% |
Prometheus rules for the metrics above. histogram_quantile needs the per-bucket rate, not the raw histogram name:
groups:
- name: rag_alerts
rules:
- alert: RAGHighLatency
expr: histogram_quantile(0.95, sum by (le) (rate(rag_latency_seconds_bucket{stage="total"}[5m]))) > 5
for: 5m
labels:
severity: warning
annotations:
summary: "RAG p95 latency above 5s"
- alert: RAGHighErrorRate
expr: sum(rate(rag_queries_total{status="error"}[5m])) / sum(rate(rag_queries_total[5m])) > 0.05
for: 5m
labels:
severity: critical
annotations:
summary: "RAG error rate above 5%"
Track quality as well as uptime: the empty-results rate, the share of "I don't know" answers, and user feedback (thumbs up/down) often move before error rates do.
Input validation
Data protection
API security
class CostAwareRAG:
"""RAG with cost controls."""
def __init__(self, rag, monthly_budget: float):
self.rag = rag
self.budget = monthly_budget
self.month_spend = 0
async def query(self, question: str) -> dict:
# Check budget
if self.month_spend >= self.budget:
return {"error": "Monthly budget exceeded"}
# Estimate cost before query
estimated_cost = self._estimate_cost(question)
if self.month_spend + estimated_cost > self.budget:
# Use cheaper model
return await self.rag.query_cheap(question)
result = await self.rag.query(question)
self.month_spend += self._actual_cost(result)
return result
def _estimate_cost(self, question: str) -> float:
# HYPOTHETICAL arithmetic: the token heuristics and prices below are
# placeholders. Use your provider's token counter and current pricing page.
input_tokens = len(question.split()) * 1.3 + CONTEXT_TOKENS
output_tokens = 500
return input_tokens * PRICE_PER_INPUT_TOKEN + output_tokens * PRICE_PER_OUTPUT_TOKEN
Set spend alerts with your LLM provider as well; in-process budgets reset when the process restarts.
histogram_quantile: https://prometheus.io/docs/practices/histograms/What SKILL.md sets; muted values are Claude Code's defaults
7 skills in this plugin
/agentic-ragBuild agentic RAG systems with autonomous planning, reflection, and tool use.
Use this skill when implementing agent-driven retrieval, query decomposition,
iterative refinement, or multi-source RAG orchestration.
Activate when: agentic RAG, A-RAG, autonomous retrieval, query planning,
iterative RAG, multi-step retrieval, agent retrieval, RAG agent.
/chunking-strategiesOptimize document chunking for RAG performance and retrieval quality.
Use this skill when splitting documents, choosing chunk sizes, implementing
semantic chunking, or improving RAG retrieval accuracy.
Activate when: chunking, split documents, chunk size, text splitting,
document processing, RAG performance, semantic chunking, overlap.
/Other plugins' skills for the same job
/rag-architect:production-rag-checklistfrom rag-architect
npx claudepluginhub latestaiagents/agent-skills --plugin rag-architect3 plugins in one repository ship this exact skill · first indexed Nov 5, 2026