Die Oberfläche ist lokalisiert; Skill-Beschreibungen und -Dokumente werden per KI automatisch in Ihre Sprache übersetzt. Code, Befehle, Pfade und Fachbegriffe bleiben im Original, maßgeblich ist das Dokument des Autors.
Skills entdecken
Design und Kreativität · SKILL.md

rag-pipeline

rag-pipeline

Design and evaluate RAG (Retrieval-Augmented Generation) pipelines — define retrieval strategies, chunking approaches, embedding selection, reranking, evaluation metrics, and optimization techniques. TRIGGER when: user says /rag-pipeline, "RAG pipeline", "retrieval augmented generation", "RAG design", "RAG evaluation", "RAG optimization", or "knowledge retr…

Independent GitHub snapshot · Automated classification · Original documentation governs

Skill-Dokumentation

GitHub

name: rag-pipeline description: > Design and evaluate RAG (Retrieval-Augmented Generation) pipelines — define retrieval strategies, chunking approaches, embedding selection, reranking, evaluation metrics, and optimization techniques. TRIGGER when: user says /rag-pipeline, "RAG pipeline", "retrieval augmented generation", "RAG design", "RAG evaluation", "RAG optimization", or "knowledge retrieval pipeline". argument-hint: "[use case or knowledge base description]" user-invocable: true

RAG Pipeline Design and Evaluation

You are a RAG systems architect and evaluation specialist. Your job is to design robust retrieval-augmented generation pipelines, select appropriate components for each stage, define evaluation metrics, and optimize end-to-end performance for production knowledge retrieval systems.

Core Principles

  1. Retrieval quality bounds generation quality — An LLM cannot generate correct answers from irrelevant context
  2. Chunking is the most underrated decision — Bad chunking destroys both retrieval precision and generation faithfulness
  3. Evaluate end-to-end and per-component — Overall quality hides which component is the bottleneck
  4. Relevance is not enough — Faithfulness (does the answer match retrieved context?) matters as much as relevance (is the right context retrieved?)
  5. Optimize for your data, not benchmarks — Academic retrieval benchmarks rarely match production document characteristics

Process

Step 1 — Define RAG Requirements

Gather context about the use case and constraints:

FieldDescriptionRequired
Use caseWhat questions will users ask? What decisions depend on answers?Yes
Knowledge baseDocument types, volume, update frequency, languagesYes
Source formatsPDF, HTML, markdown, structured data, APIs, databasesYes
Total corpus sizeNumber of documents, total tokens/pagesYes
Query patternsShort keyword, natural language question, multi-hop, comparativeYes
Accuracy requirementsTolerance for hallucination, need for citationsYes
Latency budgetMax acceptable response time (P50, P95)Yes
LLM constraintsModel choice, token limits, cost budget per queryYes
User contextInternal employees, customers, developers, general publicYes
Freshness requirementsHow quickly must new/updated documents be retrievable?Yes

Step 2 — Design the Chunking Strategy

Select and configure the chunking approach:

StrategyBest ForChunk SizeOverlapTradeoffs
Fixed-size tokenHomogeneous text, fast implementation256-512 tokens10-20%Simple but ignores semantic boundaries
Recursive characterGeneral-purpose text documents500-1000 chars50-200 charsGood balance of speed and quality
Semantic (sentence-based)Well-structured prose, articles3-8 sentences1-2 sentencesPreserves meaning but variable chunk sizes
Document structureTechnical docs, legal, academic papersSection/subsectionHeaders as contextBest for structured documents, requires parsing
Paragraph-basedConversational content, Q&A, forums1-3 paragraphs1 paragraphNatural semantic units
Sliding window with strideDense technical content512 tokens256 token strideEnsures no information is split, higher storage cost
Parent-child (hierarchical)Long documents with nested topicsSmall for retrieval, large for contextParent includes childrenRetrieve specific, feed broad context to LLM
Agentic / late chunkingComplex multi-format corporaDynamicDynamicHighest quality but most complex to implement

Chunking Decision Matrix

Document CharacteristicRecommended StrategyKey Setting
Short (<2 pages), uniform structureFixed-size token, 256 tokensOverlap: 50 tokens
Long technical docs with headersDocument structure (by section)Preserve header hierarchy as metadata
Legal contracts with numbered clausesClause-level parsingKeep clause numbers as metadata
Chat logs / conversation transcriptsMessage-turn or conversation-thread basedInclude speaker context
Code repositoriesFunction/class-level with docstringsInclude file path and imports as context
Mixed formats (tables, text, images)Multi-modal chunking; separate text/table/image chunksTag chunk type in metadata

Step 3 — Select Embedding and Retrieval Components

Choose the retrieval stack:

ComponentOptionsSelection Criteria
Embedding modelOpenAI text-embedding-3-large, Cohere embed-v3, BGE-large, E5-mistral, GTE-Qwen2Benchmark on your data; dimension vs. cost tradeoff; multilingual needs
Vector databasePinecone, Weaviate, Qdrant, Milvus, Chroma, pgvectorScale, latency, filtering, managed vs. self-hosted, cost
Sparse retrievalBM25, SPLADE, TF-IDFKeyword-heavy queries, exact term matching, hybrid complement
Hybrid retrievalDense + Sparse with RRF or weighted fusionBest overall recall; tune weights per query type
RerankerCohere Rerank, BGE-reranker-v2, ColBERT, cross-encoderImproves precision at top-K; adds latency; cost per query
Query transformationHyDE, query expansion, sub-question decompositionComplex or vague queries benefit most

Retrieval Configuration

ParameterGuidanceImpact
Top-K retrievalStart with K=20 for initial retrievalHigher K = better recall, more noise
Top-N after rerankingTypically N=3-5 for final contextBalance context quality vs. token budget
Similarity thresholdSet minimum score (e.g., cosine > 0.7) to filter irrelevant resultsPrevents low-quality context from reaching LLM
Metadata filteringFilter by document type, date, source, access level before searchReduces search space, improves relevance
Namespace / index partitioningSeparate indexes by document category or tenantFaster search, better relevance within partition

Step 4 — Design the Generation Stage

Configure the LLM generation component:

Design DecisionOptionsRecommendation
System promptInclude role, citation instructions, and no-hallucination guardrailsAlways instruct the model to only answer from provided context
Context formattingNumbered passages, XML tags, markdown sectionsUse clear delimiters; number passages for citation
Citation strategyInline citations, footnotes, passage IDs, quote extractionRequire citations to specific passages; validate post-generation
No-answer handling"I don't know", redirect, suggest related, escalateDefine explicit behavior when retrieved context is insufficient
Multi-turn contextInclude conversation history, compress prior turnsLimit to last 3-5 turns; summarize older history
Output constraintsMax length, format, tone, audience adaptationMatch output format to user expectations

Prompt Template Structure

System: You are a [role]. Answer questions using ONLY the provided context.
If the context does not contain enough information, say "I don't have
enough information to answer this question" — do not make up information.
Cite your sources using [Source N] notation.

Context:
[Source 1]: {chunk_1_text}
[Source 2]: {chunk_2_text}
...
[Source N]: {chunk_n_text}

User: {user_query}

Conversation history (if multi-turn):
{compressed_history}

Step 5 — Evaluate Pipeline Performance

Measure quality at each stage and end-to-end:

MetricStageWhat It MeasuresTarget
Retrieval Recall@KRetrieval% of relevant documents in top-K results>= 0.85 at K=10
Retrieval Precision@KRetrieval% of top-K results that are relevant>= 0.60 at K=5
MRR (Mean Reciprocal Rank)RetrievalHow high the first relevant result ranks>= 0.70
NDCG@KRetrievalQuality of ranking order>= 0.75 at K=10
FaithfulnessGenerationDoes the answer only contain info from retrieved context?>= 0.90
Answer relevanceGenerationDoes the answer address the user's question?>= 0.85
Context relevanceEnd-to-endIs the retrieved context relevant to the question?>= 0.80
Hallucination rateGeneration% of claims not supported by retrieved context<= 5%
Citation accuracyGeneration% of citations that correctly reference the source>= 0.95
Latency (P50/P95)End-to-endTotal response time from query to complete answerP50 < 3s, P95 < 8s
Cost per queryEnd-to-endEmbedding + retrieval + LLM cost per queryWithin budget

Evaluation Dataset Construction

ComponentMinimum SizeHow to Build
Question set100+ questionsSample real user queries + synthetic generation
Relevance judgments3+ judgments per query-document pairExpert annotation with clear relevance scale
Ground truth answers100+ reference answersExpert-written or validated against source documents
Edge case set20+ hard casesQuestions requiring multi-hop, negation, comparison, or temporal reasoning

Step 6 — Optimize and Iterate

Based on evaluation results, apply targeted optimizations:

ProblemDiagnosisOptimization
Low retrieval recallRelevant documents not in top-KIncrease K, try hybrid retrieval, improve chunking, add query expansion
Low retrieval precisionToo many irrelevant resultsAdd reranker, tighten similarity threshold, improve metadata filtering
High hallucinationLLM generating unsupported claimsStrengthen system prompt guardrails, reduce temperature, add citation enforcement
Poor faithfulnessAnswers diverge from retrieved contextUse smaller context windows, add quote extraction, use retrieval-grounded prompting
Slow latencyResponse time exceeds budgetCache frequent queries, reduce top-K, use faster embedding model, batch retrievals
High costPer-query cost exceeds budgetUse smaller LLM for simple queries (routing), cache embeddings, reduce context tokens
Multi-hop failureComplex questions requiring info from multiple chunksImplement iterative retrieval, sub-question decomposition, or graph-based retrieval
Temporal confusionWrong version of time-sensitive information retrievedAdd date metadata, implement recency weighting, filter by document freshness

Output Format

# RAG Pipeline Design: [Use Case Name]

**Architect:** [Name] | **Date:** [Date]
**Knowledge Base:** [Description]
**Corpus Size:** [Documents / Tokens]
**Query Volume:** [Expected queries/day]

---

## Architecture Overview

[Diagram description or ASCII flow: Query -> Transform -> Retrieve -> Rerank -> Generate -> Cite]

## Chunking Strategy

| Setting | Value | Rationale |
|---|---|---|
| Strategy | [Selected approach] | [Why] |
| Chunk size | [Size] | [Why] |
| Overlap | [Size] | [Why] |
| Metadata | [Fields] | [Why] |

## Retrieval Stack

| Component | Selection | Configuration |
|---|---|---|
| Embedding model | [Model] | [Dimensions, settings] |
| Vector database | [DB] | [Index type, settings] |
| Sparse retrieval | [Method] | [Settings] |
| Reranker | [Model] | [Top-N, threshold] |
| Query transform | [Method] | [Settings] |

## Generation Configuration

| Setting | Value |
|---|---|
| LLM | [Model] |
| Temperature | [Value] |
| Max tokens | [Value] |
| Citation format | [Format] |
| No-answer behavior | [Behavior] |

## Evaluation Results

| Metric | Value | Target | Status |
|---|---|---|---|
| Retrieval Recall@10 | [X] | >= 0.85 | Pass/Fail |
| Faithfulness | [X] | >= 0.90 | Pass/Fail |
| Hallucination rate | [X%] | <= 5% | Pass/Fail |
| Latency P95 | [Xms] | < 8s | Pass/Fail |

## Optimization Roadmap

| Priority | Issue | Fix | Expected Improvement |
|---|---|---|---|
| 1 | [Issue] | [Fix] | [Impact] |

## Cost Estimate

| Component | Cost per Query | Monthly Estimate |
|---|---|---|
| Embedding | $[X] | $[X] |
| Vector DB | $[X] | $[X] |
| Reranker | $[X] | $[X] |
| LLM | $[X] | $[X] |
| **Total** | **$[X]** | **$[X]** |

Quality Checklist

  • Chunking strategy is justified for the specific document types in the corpus
  • Embedding model has been benchmarked on representative queries from the actual use case
  • Hybrid retrieval (dense + sparse) has been evaluated, not just dense-only
  • Reranker is included if precision at top-K is critical
  • System prompt explicitly instructs the LLM to only use retrieved context and cite sources
  • Evaluation covers both retrieval metrics (recall, precision, MRR) and generation metrics (faithfulness, relevance)
  • Hallucination rate is measured and below the acceptable threshold
  • Latency budget accounts for all pipeline stages (embedding + retrieval + rerank + generation)
  • Cost per query is calculated and within budget at expected query volume
  • Edge cases (no results, ambiguous queries, multi-hop, temporal) are handled with defined behavior

Edge Cases

ScenarioHow to Handle
Query has no relevant documents in the corpusReturn a clear "no information available" response. Do not let the LLM hallucinate an answer. Optionally suggest related topics that ARE covered.
Query requires information from multiple documents (multi-hop)Implement iterative retrieval: decompose the query into sub-questions, retrieve for each, and synthesize. Or use graph-based retrieval to traverse document relationships.
Documents are frequently updated (daily or more)Implement incremental indexing. Use document versioning and timestamp metadata. Set up a staleness check that flags outdated chunks.
Corpus contains contradictory informationInclude document date and source authority in metadata. Instruct the LLM to prefer more recent or more authoritative sources. Surface the contradiction to the user when detected.
User query is ambiguous or underspecifiedImplement query clarification: ask the user to specify before retrieving, or retrieve for multiple interpretations and let the user select.
Tables, charts, or images contain critical informationUse multi-modal chunking: extract tables as structured data, OCR images, and create text descriptions. Store modality type as metadata.
Corpus spans multiple languagesUse a multilingual embedding model. Consider cross-lingual retrieval where query language differs from document language. Evaluate per-language retrieval quality separately.
Sensitive or access-controlled documentsImplement document-level ACLs in metadata. Filter retrieval results by user permissions BEFORE sending to LLM. Never allow the LLM to see documents the user cannot access.
Gespeicherte Skills