Provides best practices and architecture patterns for designing RAG systems.

Install

mkdir -p .claude/skills/rag-patterns && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/17024" && unzip -o skill.zip -d .claude/skills/rag-patterns && rm skill.zip

Installs to .claude/skills/rag-patterns

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Retrieval-Augmented Generation architecture patterns. Chunking strategies, retrieval pipelines, re-ranking, hybrid search, evaluation, and production RAG system design. USE WHEN: user mentions "RAG", "retrieval augmented generation", "document Q&A", "knowledge base chatbot", "semantic search pipeline", "chunking strategy" DO NOT USE FOR: vector database specifics - use `vector-databases`; LangChain implementation - use `langchain`; direct LLM API calls - use Claude/OpenAI SDK skills
487 chars✓ has a “when” triggerlonger than Claude Code's old 250-char listing cap (fine on current versions)
Advanced

Key capabilities

  • Implement standard RAG pipelines
  • Apply various chunking strategies for documents
  • Enrich chunks with metadata
  • Utilize hybrid search (keyword + semantic)
  • Perform re-ranking of retrieved documents
  • Evaluate RAG system performance

How it works

The skill outlines patterns for Retrieval-Augmented Generation, starting with document chunking and embedding, followed by retrieval using hybrid search and re-ranking. It also covers prompt construction and system evaluation using metrics like faithfulness and answer relevancy.

Inputs & outputs

You give it
Documents, user query, evaluation dataset
You get back
Chunked documents, retrieved documents, re-ranked results, or RAG evaluation metrics

When to use rag-patterns

  • Designing knowledge base chatbots
  • Implementing semantic search
  • Optimizing chunking strategies

About this skill

RAG Patterns

Standard RAG Pipeline

Documents → Chunk → Embed → Store (vector DB)
Query → Embed → Retrieve → Augment prompt → Generate answer

Chunking Strategies

from langchain_text_splitters import RecursiveCharacterTextSplitter

# Recommended defaults
splitter = RecursiveCharacterTextSplitter(
    chunk_size=800,      # chars (not tokens)
    chunk_overlap=200,
    separators=["\n\n", "\n", ". ", " ", ""],
)
chunks = splitter.split_documents(docs)
StrategyBest ForChunk Size
Fixed-size with overlapGeneral text500-1000 chars
Recursive characterStructured docs500-1000 chars
Semantic (by meaning)Long-form contentVariable
Document-aware (markdown headers)Technical docsSection-based

Metadata Enrichment

for chunk in chunks:
    chunk.metadata.update({
        "source": doc.metadata["source"],
        "section": extract_section_title(chunk),
        "doc_id": doc.metadata["id"],
        "chunk_index": i,
    })

Retrieval Strategies

Hybrid Search (keyword + semantic)

from langchain.retrievers import EnsembleRetriever
from langchain_community.retrievers import BM25Retriever

bm25 = BM25Retriever.from_documents(docs, k=5)
vector_retriever = vectorstore.as_retriever(search_kwargs={"k": 5})

hybrid = EnsembleRetriever(
    retrievers=[bm25, vector_retriever],
    weights=[0.3, 0.7],
)

Re-ranking

from cohere import Client

cohere = Client(api_key=COHERE_API_KEY)

def rerank(query: str, documents: list[str], top_n: int = 5):
    response = cohere.rerank(
        model="rerank-english-v3.0",
        query=query,
        documents=documents,
        top_n=top_n,
    )
    return [documents[r.index] for r in response.results]

Multi-query Retrieval

# Generate multiple query variations for better recall
prompt = """Generate 3 different versions of this question
to retrieve relevant documents: {question}"""

queries = llm.invoke(prompt).split("\n")
all_docs = set()
for q in queries:
    all_docs.update(retriever.invoke(q))

Prompt Construction

SYSTEM_PROMPT = """Answer based only on the provided context.
If the context doesn't contain the answer, say "I don't have enough information."
Cite sources using [Source: filename] format.

Context:
{context}"""

def format_context(docs, max_tokens=3000):
    context_parts = []
    for doc in docs:
        source = doc.metadata.get("source", "unknown")
        context_parts.append(f"[Source: {source}]\n{doc.page_content}")
    return "\n\n---\n\n".join(context_parts)

Evaluation

MetricMeasuresTool
Context RelevanceAre retrieved docs relevant?RAGAS, manual
FaithfulnessDoes answer match context?RAGAS
Answer RelevanceDoes answer address question?RAGAS
Retrieval RecallAre correct docs retrieved?Custom eval set
from ragas import evaluate
from ragas.metrics import faithfulness, answer_relevancy, context_precision

result = evaluate(dataset, metrics=[faithfulness, answer_relevancy, context_precision])

Anti-Patterns

Anti-PatternFix
Chunks too large (>1500 chars)Use 500-1000 char chunks with 200 overlap
No metadata on chunksStore source, section, page number
No retrieval evaluationBuild eval set, measure recall and precision
Stuffing all chunks in promptLimit to top-K (3-5), use re-ranking
Ignoring hybrid searchCombine BM25 + vector for better recall
No citation/source trackingPass metadata through pipeline

Production Checklist

  • Chunking strategy tuned with eval set
  • Hybrid search (BM25 + vector) enabled
  • Re-ranking on retrieval results
  • Source attribution in answers
  • Guardrails for out-of-scope questions
  • Monitoring: retrieval latency, answer quality scores
  • Incremental indexing for new documents

When not to use it

  • When making direct LLM API calls

Limitations

  • Does not cover vector database specifics
  • Does not cover LangChain implementation details
  • Does not cover direct LLM API calls

How it compares

This skill provides structured patterns and best practices for building RAG systems, offering a systematic approach to improve retrieval and generation quality compared to ad-hoc implementations.

Compared to similar skills

rag-patterns side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
rag-patterns (this skill)05moNo flagsAdvanced
qdrant-vector-search188moReviewAdvanced
langchain269moReviewIntermediate
cocoindex610moReviewIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

You might also like

qdrant-vector-search

zechenzhangAGI

High-performance vector similarity search engine for RAG and semantic search. Use when building production RAG systems requiring fast nearest neighbor search, hybrid search with filtering, or scalable vector storage with Rust-powered performance.

18161

langchain

zechenzhangAGI

Framework for building LLM-powered applications with agents, chains, and RAG. Supports multiple providers (OpenAI, Anthropic, Google), 500+ integrations, ReAct agents, tool calling, memory management, and vector store retrieval. Use for building chatbots, question-answering systems, autonomous agents, or RAG applications. Best for rapid prototyping and production deployments.

26138

cocoindex

cocoindex-io

Comprehensive toolkit for developing with the CocoIndex library. Use when users need to create data transformation pipelines (flows), write custom functions, or operate flows via CLI or API. Covers building ETL workflows for AI data processing, including embedding documents into vector databases, building knowledge graphs, creating search indexes, or processing data streams with incremental updates.

6116

rag-implementation

wshobson

Build Retrieval-Augmented Generation (RAG) systems for LLM applications with vector databases and semantic search. Use when implementing knowledge-grounded AI, building document Q&A systems, or integrating LLMs with external knowledge bases.

10101

reasoningbank-with-agentdb

ruvnet

Implement ReasoningBank adaptive learning with AgentDB's 150x faster vector database. Includes trajectory tracking, verdict judgment, memory distillation, and pattern recognition. Use when building self-learning agents, optimizing decision-making, or implementing experience replay systems.

579

ai-sdk

vercel

Answer questions about the AI SDK and help build AI-powered features. Use when developers: (1) Ask about AI SDK functions like generateText, streamText, ToolLoopAgent, embed, or tools, (2) Want to build AI agents, chatbots, RAG systems, or text generation features, (3) Have questions about AI providers (OpenAI, Anthropic, Google, etc.), streaming, tool calling, structured output, or embeddings, (4) Use React hooks like useChat or useCompletion. Triggers on: "AI SDK", "Vercel AI SDK", "generateText", "streamText", "add AI to my app", "build an agent", "tool calling", "structured output", "useChat".

1150

Search skills

Search the agent skills registry