rag-patterns
БесплатноБез исполняемых скриптовНе проверенRetrieval-Augmented Generation patterns and best practices. Implement chunking, embedding, retrieval, reranking, and generation pipelines. Use for…
от majiayu000★ 31 звезда на GitHubОб этом скилле
RAG Patterns
Expert guidance for Retrieval-Augmented Generation systems.
Basic RAG Pipeline
from openai import OpenAI
from sentence_transformers import SentenceTransformer
import chromadb
# Initialize
client = OpenAI()
embedder = SentenceTransformer('all-MiniLM-L6-v2')
chroma = chromadb.Client()
collection = chroma.create_collection("documents")
# Index documents
def index_documents(documents: list[str]):
embeddings = embedder.encode(documents)
collection.add(
documents=documents,
embeddings=embeddings.tolist(),
ids=[f"doc_{i}" for i in range(len(documents))]
)
# Retrieve and generate
def rag_query(query: str, top_k: int = 5) -> str:
# Embed query
query_embedding = embedder.encode([query])[0]
# Retrieve
results = collection.query(
query_embeddings=[query_embedding.tolist()],
n_results=top_k
)
# Format context
context = "\n\n".join(results['documents'][0])
# Generate
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": f"Answer based on context:\n\n{context}"},
{"role": "user", "content": query}
]
)
return response.choices[0].message.content
Chunking Strategies
Fixed Size Chunking
def chunk_fixed_size(text: str, chunk_size: int = 500, overlap: int = 50) -> list[str]:
chunks = []
start = 0
while start < len(text):
end = start + chunk_size
chunk = text[start:end]
chunks.append(chunk)
start = end - overlap
return chunks
Semantic Chunking
from langchain.text_splitter import RecursiveCharacterTextSplitter
splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=200,
separators=["\n\n", "\n", ". ", " ", ""]
)
chunks = splitter.split_text(document)
Sentence-Based Chunking
import nltk
nltk.download('punkt')
def chunk_by_sentences(text: str, sentences_per_chunk: int = 5) -> list[str]:
sentences = nltk.sent_tokenize(text)
chunks = []
for i in range(0, len(sentences), sentences_per_chunk):
chunk = " ".join(sentences[i:i + sentences_per_chunk])
chunks.append(chunk)
return chunks
Document Structure Chunking
import re
def chunk_by_sections(text: str) -> list[dict]:
# Split by headers
sections = re.split(r'(#{1,6}\s+.+)', text)
chunks = []
current_header = ""
for i, section in enumerate(sections):
if re.match(r'#{1,6}\s+', section):
current_header = section.strip()
elif section.strip():
chunks.append({
"header": current_header,
"content": section.strip()
})
return chunks
Embedding Strategies
Hybrid Embeddings
from sentence_transformers import SentenceTransformer
from rank_bm25 import BM25Okapi
class HybridRetriever:
def __init__(self, documents: list[str]):
self.documents = documents
self.embedder = SentenceTransformer('all-MiniLM-L6-v2')
self.embeddings = self.embedder.encode(documents)
# BM25 for keyword matching
tokenized = [doc.lower().split() for doc in documents]
self.bm25 = BM25Okapi(tokenized)
def search(self, query: str, top_k: int = 5, alpha: float = 0.5) -> list[str]:
# Semantic search
query_emb = self.embedder.encode([query])[0]
semantic_scores = np.dot(self.embeddings, query_emb)
# BM25 search
bm25_scores = self.bm25.get_scores(query.lower().split())
# Normalize and combine
semantic_norm = (semantic_scores - semantic_scores.min()) / (semantic_scores.max() - semantic_scores.min())
bm25_norm = (bm25_scores - bm25_scores.min()) / (bm25_scores.max() - bm25_scores.min() + 1e-6)
combined = alpha * semantic_norm + (1 - alpha) * bm25_norm
top_indices = np.argsort(combined)[-top_k:][::-1]
return [self.documents[i] for i in top_indices]
Multi-Vector Embeddings
from openai import OpenAI
def create_multi_vector_embeddings(document: str) -> dict:
client = OpenAI()
# Generate summary
summary = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": f"Summarize:\n{document}"}]
).choices[0].message.content
# Generate questions
questions = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": f"Generate 3 questions this answers:\n{document}"}]
).choices[0].message.content
# Embed all representations
embeddings = client.embeddings.create(
model="text-embedding-3-small",
input=[document, summary, questions]
)
return {
"document": document,
"document_embedding": embeddings.data[0].embedding,
"summary_embedding": embeddings.data[1].embe
Установить rag-patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл rag-patterns?
Retrieval-Augmented Generation patterns and best practices. Implement chunking, embedding, retrieval, reranking, and generation pipelines. Use for knowledge-grounded AI, document QA, and semantic search applications.
Как установить скилл rag-patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл rag-patterns запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
docx
Use this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx files) or Word templates (.dotx files). Triggers include…
от AnthropicUse this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple…
от Anthropicxlsx
Use this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing…
от Anthropicpptx
Use this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or…
от Anthropic