Community程式設計與開發github.com

RAG 實作模式

實作檢索增強生成(RAG)系統的全面指南,涵蓋向量資料庫選型、分塊策略、嵌入模型、檢索優化及生產環境部署模式。

RAG 實作模式 是什麼?

這份技能為開發者提供了一套端到端的 RAG 系統實作指南,從向量資料庫的選擇與設定開始,詳細比較了 Qdrant、Pinecone、Chroma、Weaviate 和 Milvus 等主流方案。它深入探討了四種關鍵的分塊策略:固定大小分塊、語意分塊、階層式分塊和滑動窗口分塊,並針對不同場景提供了最佳實踐建議。技能也涵蓋了嵌入模型的選擇,包括 OpenAI、Sentence Transformers 和 Cohere 等選項,並提供了實際的程式碼範例。此外,還介紹了混合搜尋、查詢擴展、重新排序和元資料過濾等高階檢索優化技術,以及上下文管理與引用追蹤等生產級模式。這個技能適用於任何想要建立高品質 RAG 系統的 AI 代理使用者,支援 LangChain、LlamaIndex 和 Haystack 等框架,並提供了跨多個向量資料庫的實作方法。

相容平台~Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/applied-artificial-intelligence/claude-code-toolkit/tree/main/skills/rag-implementation

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

RAG 實作模式 是做什麼的?

實作檢索增強生成(RAG)系統的全面指南,涵蓋向量資料庫選型、分塊策略、嵌入模型、檢索優化及生產環境部署模式。


快速參考

在以下情況使用此技能:

  • 建立 RAG / 語意搜尋系統
  • 實作文檔檢索管線
  • 優化向量資料庫效能
  • 除錯檢索品質問題
  • 選擇向量資料庫方案
  • 設計分塊策略
  • 實作混合搜尋

涵蓋的技術:

  • 向量資料庫:Qdrant, Pinecone, Chroma, Weaviate, Milvus
  • 嵌入模型:OpenAI, Sentence Transformers, Cohere
  • 框架:LangChain, LlamaIndex, Haystack

第一部分:向量資料庫選型

資料庫比較矩陣

資料庫最佳用途部署方式效能成本
Qdrant自託管、生產環境Docker/K8s極佳(Rust)免費(自託管)
Pinecone受管服務、快速原型雲端極佳按用量付費
Chroma本地開發、嵌入式程序內良好(Python)免費
Weaviate複雜 schema、GraphQLDocker/雲端極佳(Go)免費 + 雲端版
Milvus大規模、分散式K8s極佳(C++)免費(自託管)

Qdrant 設定(生產環境建議)

from qdrant_client import QdrantClient
from qdrant_client.models import Distance, VectorParams, PointStruct

# 初始化客戶端(本地或雲端)
client = QdrantClient(url="http://localhost:6333")  # 或雲端 URL

# 建立集合
client.create_collection(
    collection_name="documents",
    vectors_config=VectorParams(
        size=1536,  # OpenAI text-embedding-3-small 維度
        distance=Distance.COSINE  # 或 DOT, EUCLID
    )
)

# 插入向量及 payload
client.upsert(
    collection_name="documents",
    points=[
        PointStruct(
            id=1,
            vector=[0.1, 0.2, ...],  # 1536 維度
            payload={
                "text": "文件內容",
                "source": "doc.pdf",
                "page": 1,
                "metadata": {...}
            }
        )
    ]
)

# 搜尋
results = client.search(
    collection_name="documents",
    query_vector=[0.1, 0.2, ...],
    limit=5,
    score_threshold=0.7  # 最低相似度
)

Pinecone 設定(受管服務)

from pinecone import Pinecone, ServerlessSpec

# 初始化
pc = Pinecone(api_key="your-key")

# 建立索引
pc.create_index(
    name="documents",
    dimension=1536,
    metric="cosine",
    spec=ServerlessSpec(cloud="aws", region="us-east-1")
)

# 取得索引
index = pc.Index("documents")

# 上傳向量
index.upsert(vectors=[
    ("doc1", [0.1, 0.2, ...], {"text": "...", "source": "..."})
])

# 查詢
results = index.query(
    vector=[0.1, 0.2, ...],
    top_k=5,
    include_metadata=True
)

第二部分:分塊策略

策略 1:固定大小分塊(簡單、快速)

def fixed_size_chunking(text: str, chunk_size: int = 512, overlap: int = 50) -> list[str]:
    """
    將文字分割成固定大小的塊,並帶有重疊。

    優點:簡單,分塊大小可預測
    缺點:可能從句子中間切斷,語意邊界不明確
    """
    words = text.split()
    chunks = []

    for i in range(0, len(words), chunk_size - overlap):
        chunk = ' '.join(words[i:i + chunk_size])
        chunks.append(chunk)

    return chunks

# 使用方式
chunks = fixed_size_chunking(document, chunk_size=512, overlap=50)

何時使用:

  • 簡單的文件(日誌、逐字稿)
  • 原型 / MVP
  • 需要一致的 token 預算

策略 2:語意分塊(品質較佳)

from langchain.text_splitter import RecursiveCharacterTextSplitter

def semantic_chunking(text: str, chunk_size: int = 1000, overlap: int = 200) -> list[str]:
    """
    根據語意邊界(段落、句子)進行分割。

    優點:保留語意,檢索品質較好
    缺點:分塊大小不一,處理速度較慢
    """
    splitter = RecursiveCharacterTextSplitter(
        chunk_size=chunk_size,
        chunk_overlap=overlap,
        separators=["\n\n", "\n", ". ", " ", ""],  # 優先順序
        length_function=len
    )

    return splitter.split_text(text)

# 使用方式
chunks = semantic_chunking(document, chunk_size=1000, overlap=200)

何時使用:

  • 長篇文件(文章、書籍、報告)
  • 品質 > 速度
  • 自然語言內容

策略 3:階層式分塊(最適合結構化文件)

def hierarchical_chunking(document: dict) -> list[dict]:
    """
    根據文件結構(章節、小節)進行分塊。

    優點:保留階層結構,支援父子檢索
    缺點:需要結構化輸入,較為複雜
    """
    chunks = []

    for section in document['sections']:
        # 父塊(章節摘要)
        chunks.append({
            'text': section['title'] + '\n' + section['summary'],
            'type': 'parent',
            'section_id': section['id']
        })

        # 子塊(段落)
        for para in section['paragraphs']:
            chunks.append({
                'text': para,
                'type': 'child',
                'parent_id': section['id']
            })

    return chunks

何時使用:

  • 技術文件
  • 有目錄的書籍
  • 法律文件
  • 需要保留上下文階層

策略 4:滑動窗口(最大化上下文保留)

def sliding_window_chunking(text: str, window_size: int = 512, stride: int = 256) -> list[str]:
    """
    使用重疊窗口以最大化上下文。

    優點:邊界處無資訊損失
    缺點:儲存開銷(內容重複)
    """
    words = text.split()
    chunks = []

    for i in range(0, len(words) - window_size + 1, stride):
        chunk = ' '.join(words[i:i + window_size])
        chunks.append(chunk)

    return chunks

何時使用:

  • 需要極高檢索準確度
  • 簡短查詢需要更廣的上下文
  • 儲存成本不構成考量

第三部分:嵌入模型

模型選擇指南

模型維度速度品質成本使用案例
OpenAI text-embedding-3-small1536快極佳$0.02/百萬 tokens生產環境、通用
OpenAI text-embedding-3-large3072中等最佳$0.13/百萬 tokens高品質檢索
all-MiniLM-L6-v2384非常快良好免費自託管、原型開發
all-mpnet-base-v2768快非常好免費自託管、高品質
Cohere embed-english-v3.01024快極佳$0.10/百萬 tokens專注於語意搜尋

OpenAI 嵌入(推薦)

from openai import OpenAI

client = OpenAI(api_key="your-key")

def get_embeddings(texts: list[str], model: str = "text-embedding-3-small") -> list[list[float]]:
    """
    使用 OpenAI 生成嵌入向量。

    批次大小:每次請求最多 2048 個輸入
    速率限制:請查閱階層限制
    """
    response = client.embeddings.create(
        model=model,
        input=texts
    )

    return [item.embedding for item in response.data]

# 使用方式
chunks = ["chunk 1", "chunk 2", ...]
embeddings = get_embeddings(chunks)

Sentence Transformers(自託管)

from sentence_transformers import SentenceTransformer

# 載入模型(首次下載後會快取)
model = SentenceTransformer('all-MiniLM-L6-v2')

def get_embeddings_local(texts: list[str]) -> list[list[float]]:
    """
    在本地生成嵌入向量(無 API 成本)。

    批次大於 100 時建議使用 GPU
    小批次可使用 CPU
    """
    return model.encode(texts, show_progress_bar=True).tolist()

# 使用方式
embeddings = get_embeddings_local(chunks)

第四部分:檢索優化

技術 1:混合搜尋(稠密 + 稀疏)

from qdrant_client.models import Filter, FieldCondition, MatchValue

def hybrid_search(query: str, query_vector: list[float], top_k: int = 10):
    """
    結合稠密(向量)和稀疏(關鍵字)搜尋。

    稠密:語意相似度
    稀疏:精確關鍵字匹配
    """
    # 稠密搜尋
    dense_results = client.search(
        collection_name="documents",
        query_vector=query_vector,
        limit=top_k * 2  # 取得更多候選
    )

    # 稀疏搜尋(透過 metadata 進行 BM25)
    sparse_results = client.search(
        collection_name="documents",
        query_filter=Filter(
            must=[
                FieldCondition(
                    key="text",
                    match=MatchValue(value=query)
                )
            ]
        ),
        limit=top_k * 2
    )

    # 合併並重新排名
    combined = merge_results(dense_results, sparse_results, weights=(0.7, 0.3))
    return combined[:top_k]

技術 2:查詢擴展

def expand_query(query: str) -> list[str]:
    """
    生成查詢變體以提高召回率。

    技術:
    - 同義詞擴展
    - 問題重述
    - 實體提取
    """
    from openai import OpenAI
    client = OpenAI()

    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{
            "role": "system",
            "content": "Generate 3 alternative phrasings of the user's query."
        }, {
            "role": "user",
            "content": query
        }]
    )

    expanded = [query] + response.choices[0].message.content.split('\n')
    return expanded

# 使用方式
queries = expand_query("How to train neural networks?")
# → ["How to train neural networks?",
#    "What are neural network training techniques?",
#    "Neural network optimization methods",
#    "Deep learning model training"]

技術 3:重新排序

from sentence_transformers import CrossEncoder

# 載入交叉編碼器(比雙編碼器更適合重新排序)
reranker = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')

def rerank_results(query: str, results: list[dict], top_k: int = 5) -> list[dict]:
    """
    使用交叉編碼器對初始結果進行重新排序。

    比初始檢索更準確,但速度較慢
    僅對前 20-50 個候選結果使用
    """
    # 對每個查詢-文件對進行評分
    pairs = [(query, result['text']) for result in results]
    scores = reranker.predict(pairs)

    # 將分數與結果結合
    for result, score in zip(results, scores):
        result['rerank_score'] = float(score)

    # 排序並返回 top_k
    reranked = sorted(results, key=lambda x: x['rerank_score'], reverse=True)
    return reranked[:top_k]

技術 4:元資料過濾

def filtered_search(
    query_vector: list[float],
    filters: dict,
    top_k: int = 5
):
    """
    根據元資料(日期、類別、作者等)過濾搜尋。

    預過濾:速度較快,但可能遺漏結果
    後過濾:更多結果,但速度較慢
    """
    from qdrant_client.models import Filter, FieldCondition, Range

    # 建立過濾條件
    conditions = []

    if 'date_range' in filters:
        conditions.append(
            FieldCondition(
                key="date",
                range=Range(
                    gte=filters['date_range']['start'],
                    lte=filters['date_range']['end']
                )
            )
        )

    if 'category' in filters:
        conditions.append(
            FieldCondition(
                key="category",
                match=MatchValue(value=filters['category'])
            )
        )

    # 使用過濾條件進行搜尋
    results = client.search(
        collection_name="documents",
        query_vector=query_vector,
        query_filter=Filter(must=conditions) if conditions else None,
        limit=top_k
    )

    return results

第五部分:上下文管理

模式 1:檢索上下文最佳化

def optimize_context(query: str, retrieved_docs: list[str], max_tokens: int = 4000) -> str:
    """
    最佳化檢索到的上下文以符合 LLM 上下文視窗。

    策略:
    1. 基於相關性的截斷
    2. 抽取式摘要
    3. 移除重疊
    """
    # 按相關性排序
    sorted_docs = sorted(retrieved_docs, key=lambda d: d['score'], reverse=True)

    # 在 token 預算內建構上下文
    context_parts = []
    total_tokens = 0

    for doc in sorted_docs:
        doc_tokens = estimate_tokens(doc['text'])

        if total_tokens + doc_tokens <= max_tokens:
            context_parts.append(f"[Source: {doc['source']}]\n{doc['text']}")
            total_tokens += doc_tokens
        else:
            # 截斷最後一份文件以符合預算
            remaining = max_tokens - total_tokens
            truncated = truncate_to_tokens(doc['text'], remaining)
            context_parts.append(f"[Source: {doc['source']}]\n{truncated}")
            break

    return "\n\n---\n\n".join(context_parts)

模式 2:引用追蹤

def generate_with_citations(query: str, context: str, sources: list[dict]) -> dict:
    """
    生成帶有引用追蹤的答案。

    返回:
    - answer: 生成的文字
    - citations: 所使用的來源文件列表
    """
    from openai import OpenAI
    client = OpenAI()

    # 建立來源映射
    source_map = {i+1: source for i, source in enumerate(sources)}
    numbered_context = "\n\n".join([
        f"[{i+1}] {source['text']}"
        for i, source in enumerate(sources)
    ])

    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{
            "role": "system",
            "content": "Answer using the provided sources. Cite sources as [1], [2], etc."
        }, {
            "role": "user",
            "content": f"Context:\n{numbered_context}\n\nQuestion: {query}"
        }]
    )

    answer = response.choices[0].message.content

    # 提取使用的引用
    citations = []
    for num, source in source_map.items():
        if f"[{num}]" in answer:
            citations.append(source)

    return {
        "answer": answer,
        "citations": citations
    }

# 使用方式
result = generate_with_citations(
    query="What is RAG?",
    context=optimized_context,
    sources=retrieved_docs
)

Individual skills in this repo

This repo contains 2 individual skills — each has its own dedicated page.

相關技能