rag-patterns

RAG patterns: involves embedding generation, chunking, hybrid retrieval (BM25 + vector), re-ranking, CRAG, and multi-hop retrieval. Trigger terms include RAG, embeddings, pgvector, Qdrant, Pinecone, Weaviate, re-rankers, and semantic search.

Last repository push
GitHub Stars
180
Forks
21
Issues / PRs
0

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "rag-patterns" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-e1259211fbdc658e4f7169b41a8147cb32d9680a92de08afcde75d95783e0002. Verify the upstream source and version against https://github.com/softspark/ai-toolkit before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

github.com

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

RAG patterns: involves embedding generation, chunking, hybrid retrieval (BM25 + vector), re-ranking, CRAG, and multi-hop retrieval. Trigger terms include RAG, embeddings, pgvector, Qdrant, Pinecone, Weaviate, re-rankers, and semantic search.

0 Downloads

Introduction source: third_party · softspark · 0.0.1 Reference

SkillPi interpretation

Tasks
RAG: embeddings, chunking, hybrid search (BM25+vector), reranking, CRAG, multi-hop. Triggers: RAG, embedding, pgvector, Qdrant, Pinecone, Weaviate, reranker, semantic search.
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: rag-patterns
description: "RAG: embeddings, chunking, hybrid search (BM25+vector), reranking, CRAG, multi-hop. Triggers: RAG, embedding, pgvector, Qdrant, Pinecone, Weaviate, reranker, semantic search."
effort: medium
user-invocable: false
allowed-tools: Read

RAG Patterns Skill

Core Patterns

1. Hybrid Search

Combine dense (vector) and sparse (BM25) retrieval with RRF fusion:

# RAG-MCP hybrid search
result = await hybrid_search_kb(
    query="rate limiting configuration",
    service="nginx",
    limit=10
)

2. Corrective RAG (CRAG)

Self-correcting retrieval with relevance validation:

result = await crag_search(
    query="fuzzy query",
    relevance_threshold=0.4,
    max_retries=2
)

# Or via smart_query
result = await smart_query(query="...", use_crag=True)

3. HyDE (Hypothetical Document Embeddings)

Generate hypothetical answers for better retrieval on conceptual queries:

result = await smart_query(
    query="conceptual question about design patterns",
    use_hyde=True
)

4. Multi-hop Retrieval

Complex queries requiring multiple retrieval steps:

result = await multi_hop_search(
    query="Compare nginx with varnish for Magento cache",
    max_hops=3
)

# Or via smart_query
result = await smart_query(query="compare A vs B", use_multi_hop=True)

Indexing Best Practices

Aspect Recommendation
Chunk size 512-1024 tokens
Overlap 10-20% of chunk
Structure Preserve headers, sections
Metadata Include title, path, date, category, tags
Frontmatter YAML with standardized fields

Frontmatter Template

---
title: "Document Title"
service: {project-name}
category: reference|howto|procedures|troubleshooting|decisions|best-practices
tags: [tag1, tag2, tag3]
last_updated: "YYYY-MM-DD"
---

MCP Tools Reference (v5.5.0)

Tool Use Case Speed
smart_query ⭐ Default for 90% of queries 2-4s
hybrid_search_kb Raw vector + text search <1s
get_document Full document content <1s
crag_search Vague/fuzzy queries 1-3s
multi_hop_search Complex reasoning 20-30s

Tool Selection Guide

# Default - auto-routing
smart_query("specific technical question")

# Vague query - self-correcting
crag_search("jak to skonfigurować")

# Complex comparison
multi_hop_search("nginx vs varnish performance comparison")

# Known document
get_document(path="kb/reference/architecture.md")

Quality Metrics

Metric Description Target
Faithfulness Answer based on context >70%
Relevancy Answer addresses question >70%
Context Precision Found context is accurate >60%
Latency (p95) Response time <2s
Precision@k Relevant results in top-k >80%

Retrieval Optimization

Reranking

# Retrieve more, rerank to top-k
initial_results = await hybrid_search_kb(query, limit=20)
reranked = rerank_results(initial_results, query)
final_results = reranked[:5]

Context Window Management

  • Place critical info at start/end (serial position effect)
  • Summarize long documents before insertion
  • Use tiered context: critical → supporting → background

Query Enhancement

  • Query expansion with synonyms
  • Query decomposition for complex questions
  • Entity extraction for filtering

Anti-Patterns

❌ Don't:

  • Skip reranking for final results
  • Use very large chunks (>2000 tokens)
  • Ignore metadata in retrieval
  • Trust LLM output without citation
  • Use latest for model versions

✅ Do:

  • Use top-k=20 → rerank → top-5
  • Chunk semantically (by section)
  • Enrich metadata at indexing time
  • Require source attribution in answers
  • Pin model versions for reproducibility

RAG System Implementation

Key Files (Typical Structure)

scripts/
├── search_core.py           # Core search
├── query_enhancements.py    # HyDE, query expansion
├── corrective_rag.py        # CRAG
├── multi_hop.py             # Multi-hop
├── unified_indexer.py       # Indexing
└── rag_evaluator.py         # Evaluation

Running RAG Commands

Direct execution:

# Index KB
make index

# Evaluate RAG
python scripts/evaluate_rag.py

# Detect gaps
python scripts/knowledge_gaps.py --detect

Docker execution (if containerized):

# Index KB
docker exec {app-container} make index

# Evaluate RAG
docker exec {api-container} python3 scripts/evaluate_rag.py

# Detect gaps
docker exec {api-container} python3 scripts/knowledge_gaps.py --detect

Rules

  • MUST chunk by document structure (headers, lists, code fences), not by fixed byte/token count — structure-aware chunking recovers 20-40% of retrieval quality on technical docs
  • MUST always use hybrid search (BM25 + vector) for keyword-heavy queries — pure vector search misses exact identifiers (function names, config keys)
  • NEVER trust a single embedding model on multilingual corpora; pair with a bilingual model or translate queries at the edge
  • NEVER index without content-hash change detection — full rebuilds on every change waste embedding budget and corrupt orphan tracking
  • CRITICAL: every response includes verifiable citations (source path + exact chunk). A RAG answer without traceable sources is a hallucination wearing a badge.
  • MANDATORY: evaluate with a golden dataset (faithfulness, relevancy, context precision) before promoting any pipeline change to production

Gotchas

  • Top-k cosine similarity is not relevance — semantically close chunks may be topically wrong. Always compare hybrid vs pure-vector scores on a held-out set before committing to one.
  • Default embedding models (e.g., text-embedding-ada-002) underperform on long technical docs (>8k tokens). For long-form content consider chunking before embedding, not embedding then slicing.
  • Chunk overlap (10-20%) helps narrative text but duplicates storage and token cost. Code and structured tables do not benefit from overlap — disable per content type.
  • Cross-encoder rerankers (e.g., bge-reranker) add 100-300ms per query. For real-time UX, rerank only the top-20 candidates, not the top-100.
  • RAG failure modes are structural (retrieval, routing, chunking), not prompt-level. Before "tuning the prompt", check retrieval metrics — a prompt fix on top of broken retrieval is theater.
  • Query rewriting (HyDE, hypothetical doc generation) improves some queries and degrades others. A/B test before enabling globally; a blanket "always rewrite" often regresses simple lookups.

When NOT to Load

  • For executing a reindex — use /index (task skill)
  • For measuring RAG quality — use /evaluate (task skill)
  • For chunking documentation strategy without an index — this skill assumes you already have a vector store; use /architecture-decision for pipeline choice
  • For MCP-specific retrieval via smart_query() — the tool is already built; reach for this skill only when tuning the underlying index
  • For prompt engineering alone without retrieval concerns — use /prompt-caching-patterns or the relevant language skill

Version history

  1. v6.2.0 GitHub ↗
    Original release notes

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.1.0...v6.2.0

  2. v6.1.0 GitHub ↗
    Original release notes

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.0.0...v6.1.0

  3. v6.0.0 GitHub ↗
    Original release notes

    ## What's Changed * chore: bump softprops/action-gh-release from 3.0.3 to 3.0.4 by @dependabot[bot] in https://github.com/softspark/ai-toolkit/pull/45 * fix: handle Windows status output and clarify Antigravity workflow support by @softspark in https://github.com/softspark/ai-toolkit/pull/46 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.5.0...v6.0.0

  4. v5.5.0 GitHub ↗
    Original release notes

    ### Ecosystem - **OpenCode V2 and V1 compatibility:** `scripts/generate_opencode_plugin.py` emits the documented `id/setup/server` contract for V2 and V1 **1.18.29+**. Upgrade older V1 clients before using this plugin, then run `ai-toolkit update` to regenerate managed copies. `doctor` warns about obsolete V1-only exports. Scoped global/project IDs avoid native collisions; advisory work has one owner per location, while safety guards execute in every registered layer. The current V2 package is `@opencode/cli`; `opencode-ai` still publishes V1. - **Claude guard failure policy:** destructive-command, home-path and configuration guards use `onFailure: block` on Claude Code **2.1.295+**. Legacy entries migrate without duplication; hooks owned by other plugins survive. Older clients do not have this infrastructure-failure guarantee. - **Codex, Gemini and Devin:** Codex refresh accepts the two diagnostic model-request events. Gemini advisory hooks return native JSON and save native completion responses; Devin prompt/edit hooks emit event-labelled context. - **All 13 integrations reviewed:** refresh release metadata and the ecosystem snapshot, distinguish stable/preview channels, and pin Auggie's stable v0 references. User model, effort and approval selections remain unchanged. ### Fixed - **One Claude Stop checker:** remove the duplicate advisory handler from the global and app manifests. `quality-gate.sh` keeps PHPStan advisory through `quality-check.sh --php-only`, preserving checker precedence and Makefile settings. PHPStan now runs synchronously on Stop and TaskCompleted (#43). - **OpenCode guard execution:** replace the unsupported Bun stdin path with real subprocess execution in both APIs. Denial, missing guards, crashes and timeouts block tools. Transactional generation refuses user-owned collisions and symlinked destinations; lifecycle cleanup releases advisory ownership. - **Isolated release smoke:** `scripts/release.sh` installs the packed artifact in a disposable, network-disabled container with no mounts and the OS user's default home. Host settings are not used as a smoke sandbox. ### Changed - Hook entries: 29 to 28 across the same 14 Claude events. Skills remain 116 and agents remain 44. Bats coverage grows from 2012 to 2037 tests. - Refresh compatibility documentation and remove stale inventory counts from the backward-compatibility policy. All protected public surfaces remain. - Skill body budget is unchanged: the largest body remains `design-engineering` at 17,197 bytes, less than 2,000 bytes below the 18,000-byte warning threshold, so the release ratchet does not apply. **Included pull request:** [#43: run the project checker once on Claude Code Stop](https://github.com/softspark/ai-toolkit/pull/43), contributed by @jacekprzybyl. **Full changelog:** https://github.com/softspark/ai-toolkit/compare/v5.4.2...v5.5.0

  5. v5.4.2 GitHub ↗
    Original release notes

    ## What's Changed * fix(install): read state.json on native Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/39 * test: isolate USERPROFILE together with HOME on Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/41 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.4.1...v5.4.2

Only the five most recent versions are shown. View full version history at the source ↗

Current listing version

0.0.1

Verify the source revision ↗

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value85/100

Highlights

  • 提供 RAG 核心模式(混合搜索、CRAG、HyDE、多跳检索)的完整实现指导
  • 涵盖索引最佳实践、质量指标与反模式,具备高度实用价值
Trigger Precision88/100

Highlights

  • 触发词覆盖 RAG 生态主流技术栈(pgvector、Qdrant、Pinecone、Weaviate)
  • 关键词分布合理,边界清晰,不易误触
Structure and Standards92/100

Highlights

  • 文档结构清晰,分章节覆盖从模式到实现的完整链路
  • 包含代码示例、表格、Rules 和 Gotchas,frontmatter 完整
Execution Reliability90/100

Highlights

  • 工具调用示例参数正确,覆盖异常处理与阈值配置
  • 强调混合搜索、内容哈希检测、评估指标等关键可靠性实践
Evidence Verifiability (mean of the first four)89/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

These common operations were not identified in the main document. This does not mean no permissions or risks exist.

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.