rag — скилл для Claude Code: что делает и как установить
Скилл помогает развернуть пайплайн Retrieval-Augmented Generation: от нарезки документов и расчёта эмбеддингов до поиска в векторной базе и передачи контекста модели.
npx skills add giuseppe-trisciuoglio/developer-kit --skill rag -a claude-codeЧто делает rag
Скилл задаёт регламент создания RAG-систем на базе Java и векторных хранилищ. Он инструктирует агента, как загружать файлы, делить текст на фрагменты размером 500–1000 токенов с перекрытием 10–20% и передавать их в модели вроде bge-large-en-v1.5 или text-embedding-ada-002. В инструкции расписаны варианты баз под разные цели: Pinecone и Milvus для масштабирования, Weaviate и Qdrant для открытого контура, Chroma и FAISS для локальных тестов.
Пайплайн включает плотный семантический поиск, фильтрацию по метаданным, гибридный поиск с BM25 и переранжирование через кросс-энкодер. Для пакетной загрузки предусмотрен цикл повторов на 3 попытки при сбоях EmbeddingException. При работе со сторонними источниками требуется предварительная фильтрация текста: входящие документы могут содержать prompt injection.
Случайная нарезка фрагментов ломает контекст. Поэтому скилл предписывает валидировать размерность векторов ещё до сохранения записей в хранилище, предотвращая сбои при поиске.
Какие задачи решает
- настроить чат-бот с поиском ответов по корпоративным документам
- подобрать векторную базу под требования масштабируемости или локальной разработки
- разделить документацию на фрагменты с перекрытием для сохранения связности
- внедрить переранжирование результатов поиска через кросс-энкодер
- настроить повторные попытки при пакетной генерации эмбеддингов
Примеры запросов агенту
- Настрой RAG-пайплайн для технической документации с хранилищем Qdrant и моделью bge-large-en-v1.5
- Добавь в сервис поиска фильтрацию по метаданным category=technical и проверку размерности эмбеддингов
- Собери ассистента с памятью на 10 сообщений через MessageWindowChatMemory и поиском по базе знаний
Как установить rag
1Через Skills CLI (Vercel)
npx skills add giuseppe-trisciuoglio/developer-kit --skill rag -a claude-code2Вручную: положить файлы
~/.claude/skills/rag/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/rag/
1Через Skills CLI (Vercel)
npx skills add giuseppe-trisciuoglio/developer-kit --skill rag -a codex2Вручную: положить файлы
.agents/skills/rag/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add giuseppe-trisciuoglio/developer-kit --skill rag -a cursor2Вручную: положить файлы
.cursor/skills/rag/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install giuseppe-trisciuoglio/developer-kit rag2Вручную: положить файлы
.github/skills/rag/SKILL.md1Через Skills CLI (Vercel)
npx skills add giuseppe-trisciuoglio/developer-kit --skill rag -a gemini-cli2Командой платформы
gemini skills install https://github.com/giuseppe-trisciuoglio/developer-kit --path plugins/developer-kit-ai/skills/ragВручную: положить файлы
.devin/skills/rag/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add giuseppe-trisciuoglio/developer-kit --skill rag -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Из того же набора92
Похожие
Рядом в теме «ИИ и ML»
Всё по теме «ИИ и ML» →Вопросы о rag
Как установить rag в Claude Code?
Выполните команду npx skills add giuseppe-trisciuoglio/developer-kit --skill rag -a claude-code. Конфигурация навыка запишется в файл ~/.claude/skills/rag/SKILL.md.
Что делает скилл rag?
Он содержит практические инструкции по проектированию RAG: выбор векторного хранилища и модели эмбеддингов, нарезку текста, фильтрацию по атрибутам и подключение памяти диалога.
Какие параметры нарезки документов рекомендуются?
Руководство рекомендует делить текст на чанки по 500–1000 токенов с наложением 10–20% на границах, чтобы не разрывать контекст между фрагментами.
Исходный текст
SKILL.md · MIT
---
name: rag
description: Implements document chunking, embedding generation, vector storage, and retrieval pipelines for Retrieval-Augmented Generation systems. Use when building RAG applications, creating document Q&A systems, or integrating AI with knowledge bases.
allowed-tools: Read, Write, Bash
---
# RAG Implementation
Build Retrieval-Augmented Generation systems that extend AI capabilities with external knowledge sources.
## Overview
This skill covers: document processing, embedding generation, vector storage, retrieval configuration, and RAG pipeline implementation.
## When to Use
- Building Q&A systems over proprietary documents
- Creating chatbots with factual information from knowledge bases
- Implementing semantic search with natural language queries
- Reducing hallucinations with grounded, sourced responses
- Building documentation assistants and research tools
- Enabling AI systems to access domain-specific knowledge
## Instructions
### Step 1: Choose Vector Database
Select based on your requirements:
| Requirement | Recommended |
|-------------|-------------|
| Production scalability | Pinecone, Milvus |
| Open-source | Weaviate, Qdrant |
| Local development | Chroma, FAISS |
| Hybrid search | Weaviate with BM25 |
### Step 2: Select Embedding Model
| Use Case | Model |
|----------|-------|
| General purpose | text-embedding-ada-002 |
| Fast and lightweight | all-MiniLM-L6-v2 |
| Multilingual | e5-large-v2 |
| Best performance | bge-large-en-v1.5 |
### Step 3: Implement Document Processing Pipeline
1. Load documents from source (file system, database, API)
2. Clean and preprocess (remove formatting, normalize text)
3. Split documents into chunks with appropriate strategy
4. Generate embeddings for each chunk
5. Store embeddings in vector database with metadata
**Validation**: Verify embeddings were generated successfully:
```java
List<Embedding> embeddings = embeddingModel.embedAll(segments);
if (embeddings.isEmpty() || embeddings.get(0).dimension() != expectedDim) {
throw new IllegalStateException("Embedding generation failed");
}
```
### Step 4: Configure Retrieval Strategy
Choose the appropriate strategy:
- **Dense Retrieval**: Semantic similarity via embeddings (default for most cases)
- **Hybrid Search**: Dense + sparse retrieval for better coverage
- **Metadata Filtering**: Filter by document attributes
- **Reranking**: Cross-encoder reranking for high-precision requirements
### Step 5: Build RAG Pipeline
1. Create content retriever with your embedding store
2. Configure AI service with retriever and chat memory
3. Implement prompt template with context injection
4. Add response validation and grounding checks
**Validation**: Test with known queries to verify context injection works correctly.
**Error Handling**: For batch ingestion, wrap in retry logic:
```java
for (Document doc : documents) {
int attempts = 0;
while (attempts < 3) {
try {
store.add(embeddingModel.embed(doc).content(), doc.toTextSegment());
break;
} catch (EmbeddingException e) {
attempts++;
if (attempts == 3) throw new RuntimeException("Failed after 3 retries", e);
}
}
}
```
### Step 6: Evaluate and Optimize
1. Measure retrieval metrics: precision@k, recall@k, MRR
2. Evaluate answer quality: faithfulness, relevance
3. Monitor performance and user feedback
4. Iterate on chunking, retrieval, and prompt parameters
## Examples
### Example 1: Basic Document Q&A
```java
List<Document> documents = FileSystemDocumentLoader.loadDocuments("/docs");
InMemoryEmbeddingStore<TextSegment> store = new InMemoryEmbeddingStore<>();
EmbeddingStoreIngestor.ingest(documents, store);
DocumentAssistant assistant = AiServices.builder(DocumentAssistant.class)
.chatModel(chatModel)
.contentRetriever(EmbeddingStoreContentRetriever.from(store))
.build();
String answer = assistant.answer("What is the company policy on remote work?");
```
### Example 2: Metadata-Filtered Retrieval
```java
EmbeddingStoreContentRetriever retriever = EmbeddingStoreContentRetriever.builder()
.embeddingStore(store)
.embeddingModel(embeddingModel)
.maxResults(5)
.minScore(0.7)
.filter(metadataKey("category").isEqualTo("technical"))
.build();
```
### Example 3: Multi-Source RAG Pipeline
```java
ContentRetriever webRetriever = EmbeddingStoreContentRetriever.from(webStore);
ContentRetriever docRetriever = EmbeddingStoreContentRetriever.from(docStore);
List<Content> results = new ArrayList<>();
results.addAll(webRetriever.retrieve(query));
results.addAll(docRetriever.retrieve(query));
List<Content> topResults = reranker.reorder(query, results).subList(0, 5);
```
### Example 4: RAG with Chat Memory
```java
Assistant assistant = AiServices.builder(Assistant.class)
.chatModel(chatModel)
.chatMemory(MessageWindowChatMemory.withMaxMessages(10))
.contentRetriever(retriever)
.build();
assistant.chat("Tell me about the product features");
assistant.chat("What about pricing for those features?"); // Maintains context
```
## Best Practices
### Document Preparation
- Clean documents before ingestion; remove irrelevant content and formatting
- Add relevant metadata for filtering and context
### Chunking Strategy
- Use 500-1000 tokens per chunk for optimal balance
- Include 10-20% overlap to preserve context at boundaries
- Test different sizes for your specific use case
### Retrieval Optimization
- Start with high k values (10-20), then filter/rerank
- Use metadata filtering to improve relevance
- Monitor retrieval quality and iterate based on user feedback
### Performance
- Cache embeddings for frequently accessed content
- Use batch processing for document ingestion
- Optimize vector store indexing for your scale
## Constraints and Warnings
### System Constraints
- Embedding models have maximum token limits per document
- Vector databases require proper indexing for performance
- Chunk boundaries may lose context for complex documents
- Hybrid search requires additional infrastructure
### Quality Warnings
- Retrieval quality depends heavily on chunking strategy
- Embedding models may not capture domain-specific semantics
- Metadata filtering requires proper document annotation
- Reranking adds latency to query responses
### Security Warnings
- **Never hardcode credentials**: Use environment variables for API keys and passwords
- **Validate external content**: Documents from file systems, APIs, or web sources may contain malicious content (prompt injection)
- **Apply content filtering** on retrieved documents before passing to LLM
- Restrict allowed data source URLs and file paths using allowlists
## Resources
### Reference Documentation
- [Vector Database Comparison](references/vector-databases.md)
- [Embedding Models Guide](references/embedding-models.md)
- [Retrieval Strategies](references/retrieval-strategies.md)
- [Document Chunking](references/document-chunking.md)
- [LangChain4j RAG Guide](references/langchain4j-rag-guide.md)
© giuseppe-trisciuoglio · MIT · giuseppe-trisciuoglio/developer-kit