AI Phase 07 — RAG / Knowledge / Memory(Day 61–70)

100-Day AI Knowledge Challenge

AI Phase 07 — RAG / Knowledge / Memory(Day 61–70)

這 10 天的目標不是「學會 LangChain」,也不是「會把文件丟進 Pinecone」。真正的能力是:看著一條 RAG 管線,能解釋每一層為什麼存在、拿掉它會壞在哪裡1。所以這個 Phase 每加一層,就故意做錯一次,拿數字比較。

主教材是 LlamaIndex 的官方文件(ingestion、indexing、retrieval、query engine);搭配兩份:Qdrant 文件負責 Embedding → Vector → Collection → Search → Metadata filter 這一段,Sentence Transformers 文件負責讓你真正理解 embedding model 與 reranker2。整個 Phase 圍繞同一條管線,一天加一塊3:

Markdown → Parser → Chunk → Embedding → Vector DB → Retrieval → Reranking → LLM

然後故意做錯並記錄結果:chunk 太大、chunk 太小、retrieval 太多、retrieval 太少、沒有 metadata、沒有 reranking3。Day 61–68 每天加一層並做對應的錯誤實驗,Day 69 把六種錯誤做成一張對照表,Day 70 組成 Project 2:Production RAG——Documents → ingestion → embedding → retrieval → reranking → LLM → citations,展示 retrieval quality、chunking 對照、latency、cost、evaluation4。

總綱第 4 節的重疊對照表在這個 Phase 列了三天:embedding 與相似度(Backend Day 82)、倒排索引/BM25/向量索引(Backend Day 83)、混合檢索與 chunking(Backend Day 84)。這些原理不重寫,Day 62、63、64、67 開頭各有一段連過去,只寫「真實套件裡長什麼樣」與「故意做錯的對照實驗」這兩個新角度5。

環境: 用 Phase 06 的同一個 Python(教材作者用 Python 3.12.8)再裝五個套件:

pip install llama-index-core llama-index-embeddings-huggingface \
            llama-index-vector-stores-qdrant qdrant-client sentence-transformers

教材作者 2026-10-17 實跑的版本是 llama-index-core 0.14.25、llama-index-embeddings-huggingface 0.8.0、llama-index-vector-stores-qdrant 0.10.4、qdrant-client 1.19.1、sentence-transformers 6.1.0(torch 2.14.1)。第一次執行會從 Hugging Face 下載兩個小模型(embedding 用 sentence-transformers/all-MiniLM-L6-v2,reranker 用 cross-encoder/ms-marco-MiniLM-L6-v2),需要網路,之後就用快取。Qdrant 一律用 Python client 的 local mode(QdrantClient(":memory:") 或 path=),不需要 Docker、不需要 server;整個 Phase 也不呼叫任何付費 LLM,生成那一步用一個「替身 LLM」代替(Day 68 說明為什麼這樣還是能驗證引用)。所有檔案放在同一個資料夾 p07/,路徑裡不要有以 . 開頭的資料夾(教材作者實測:SimpleDirectoryReader 在這種路徑下會回報 No files found)。

預期輸出怎麼讀: 下面每段「預期」都是教材作者實跑的輸出。hit rate、MRR、分數、排名在同樣的套件版本下可重現;毫秒數會隨機器不同,只看相對大小。

教材查證的範圍(請先看): 2026-10-17 查證時,下面引用的每一頁都實際開過,但只確認到「小節標題+該節重點」的層級,沒有逐字比對。Qdrant 的 Points、Filtering、Search 三頁與 Sentence Transformers 的 Quickstart、Pretrained Models 兩頁超過 10 萬字元,尾端沒讀到(引用的小節都在讀到的範圍內)。Qdrant 官方 Local Quickstart 用的是 Docker,local mode 的說明是在 qdrant-client 的 GitHub README,所以 Day 63 連的是 README。

Day 61 — RAG 的五個階段與第一條最小管線

今天要回答的問題

RAG 由哪幾個階段組成?每個階段的輸入和輸出是什麼?把一個問題丟進去,哪一步決定了 LLM 最後「看得到」哪些文字?

主教材(Core)

  • LlamaIndex 文件 — Introduction to RAG(Stages within RAG、Important concepts within RAG 兩節),預估 20 分鐘
  • LlamaIndex 文件 — Querying(Stages of querying、Customizing the stages of querying 兩節),預估 20 分鐘
  • 實作,預估 60 分鐘

搭配(Companion,選讀)

  • LlamaIndex 文件 — High-Level Concepts(Retrieval Augmented Generation (RAG)、Use cases 兩節),看 Query Engine 與 Chat Engine 這兩個名詞的定義;預估 10 分鐘

讀的時候抓這幾個重點

  • RAG 要解決的問題很具體。 Introduction to RAG 開頭說:LLM 用大量資料訓練過,但沒有用你的資料訓練過;RAG 的做法是把你的資料加進 LLM 能看到的範圍。注意它不是「讓模型學會你的資料」,而是每次問問題時,把相關的幾段文字放進 prompt。所以 RAG 的品質上限,就是「放進去的那幾段對不對」。
  • 五個階段:Loading、Indexing、Storing、Querying、Evaluation。 Loading 把資料從來源讀進來,Indexing 建出可以查詢的結構(通常是 embedding 加 metadata),Storing 把結果存起來免得每次重算,Querying 檢索並生成答案,Evaluation 衡量答案準不準、忠不忠於來源、夠不夠快。很多教學只講中間三個;這個 Phase 的 Day 69 會把第五個補上。
  • Querying 本身又拆成三段。 Querying 頁的 Stages of querying 一節列出:Retrieval(從索引找最相關的文件,最常見的是 top-k 語意檢索)、Postprocessing(對撈回來的 node 重新排序、轉換或過濾)、Response synthesis(把問題、相關資料和 prompt 組起來送給 LLM)。今天的程式會用 response_mode="no_text" 只跑到 Retrieval,先看清楚「被撈回來的是什麼」。
  • Document 和 Node 不是同一個東西。 Document 是你讀進來的原始單位(一個檔案),Node 是切開之後真正被 embedding、被檢索的單位。今天的預設設定下,4 份文件只產生 4 個 node——每份文件整份就是一個 chunk。記住這個數字,Day 64 會解釋它為什麼是個問題。

實作

在 p07/ 建立 corpus.py。這是整個 Phase 共用的練習語料:一個虛構的訊息佇列產品 Relay 的文件,加上 12 題評估題。v1 與 v2 兩份文件刻意寫得幾乎一樣,只差幾個數字:

"""Phase 07 的練習語料:一個虛構的訊息佇列產品 Relay 的文件,加上一組評估題。

v1 與 v2 兩份文件的章節幾乎一樣,只有幾個數字不同——這是故意的,
Day 66 會用它來看「沒有 metadata」時檢索會拿錯版本。
"""
from pathlib import Path


def markdown(title, sections):
    """把 (小節標題, 內文) 組成一份 Markdown 文件。"""
    body = "\n\n".join(f"## {heading}\n{text}" for heading, text in sections)
    return f"# {title}\n\n{body}\n"


DOCS = {
    "relay-v1.md": ("v1", markdown("Relay v1 Operator Guide", [
        ("Overview",
         "Relay is a hosted message queue. Producers publish messages to a topic and consumers read them through subscriptions. Each subscription keeps its own cursor, so two services can read the same topic at different speeds without affecting each other."),
        ("Message size limits",
         "Every message has a body and optional headers. The broker rejects any message whose body is larger than 256 KB and returns error code RLY-413 to the producer. Headers do not count toward this limit, but a single message may carry at most 32 headers."),
        ("Retention",
         "Messages stay on the broker after they are acknowledged. Unacknowledged and acknowledged messages are both kept for 7 days, after which a background job deletes them. Retention is configured per topic and cannot be changed for a single subscription."),
        ("Delivery guarantees",
         "Relay delivers each message at least once. A consumer must acknowledge a message within the visibility timeout, which defaults to 30 seconds; otherwise the message becomes visible again and is redelivered. Consumers should therefore be idempotent."),
        ("Dead letter queue",
         "After 5 failed delivery attempts a message is moved to the dead letter queue of its subscription. Operators can inspect the dead letter queue in the console and replay messages back to the original topic."),
    ])),
    "relay-v2.md": ("v2", markdown("Relay v2 Operator Guide", [
        ("Overview",
         "Relay is a hosted message queue. Producers publish messages to a topic and consumers read them through subscriptions. Each subscription keeps its own cursor, so two services can read the same topic at different speeds without affecting each other."),
        ("Message size limits",
         "Every message has a body and optional headers. The broker rejects any message whose body is larger than 1 MB and returns error code RLY-413 to the producer. Headers do not count toward this limit, but a single message may carry at most 64 headers."),
        ("Retention",
         "Messages stay on the broker after they are acknowledged. Unacknowledged and acknowledged messages are both kept for 14 days, after which a background job deletes them. Retention is configured per topic and cannot be changed for a single subscription."),
        ("Delivery guarantees",
         "Relay delivers each message at least once. A consumer must acknowledge a message within the visibility timeout, which defaults to 60 seconds; otherwise the message becomes visible again and is redelivered. Consumers should therefore be idempotent."),
        ("Dead letter queue",
         "After 10 failed delivery attempts a message is moved to the dead letter queue of its subscription. Operators can inspect the dead letter queue in the console and replay messages back to the original topic."),
    ])),
    "billing.md": ("all", markdown("Relay Billing", [
        ("Pricing model",
         "Relay charges for two things: the number of API requests and the amount of data stored. Every publish, pull, and acknowledge call counts as one request. Batching several messages into one publish call therefore lowers the bill."),
        ("Free tier",
         "Each account gets the first one million requests per month for free. Storage above 10 GB-month is always billed, even inside the free tier."),
        ("Invoices",
         "Invoices are issued on the first business day of each month. The invoice lists usage per project, so teams that share an account can split the cost without extra tooling."),
    ])),
    "security.md": ("all", markdown("Relay Security", [
        ("Authentication",
         "Clients authenticate with project-scoped API keys. A key is sent in the Authorization header and can be rotated without downtime by creating a second key, switching clients over, and then revoking the first one."),
        ("Encryption",
         "All traffic uses TLS 1.2 or newer. Message bodies are encrypted at rest with keys managed by the platform; customer-managed keys are available on the enterprise plan."),
        ("Audit log",
         "Every administrative action, such as creating a topic or revoking a key, is written to the audit log. The audit log is kept for one year and can be exported to object storage."),
    ])),
}

# 每一題:問題、要求的版本(None = 不限)、正確答案一定會出現的字串
EVAL = [
    {"q": "What is the maximum message body size in Relay v2?", "version": "v2", "answer": "larger than 1 MB"},
    {"q": "How long are messages retained in Relay v2?", "version": "v2", "answer": "kept for 14 days"},
    {"q": "What is the default visibility timeout in Relay v2?", "version": "v2", "answer": "defaults to 60 seconds"},
    {"q": "After how many failed attempts does Relay v2 move a message to the dead letter queue?", "version": "v2", "answer": "After 10 failed"},
    {"q": "How many headers can a Relay v1 message carry?", "version": "v1", "answer": "at most 32 headers"},
    {"q": "How long does Relay v1 keep acknowledged messages?", "version": "v1", "answer": "kept for 7 days"},
    {"q": "Which error code does the broker return for an oversized message?", "version": None, "answer": "RLY-413"},
    {"q": "How do I rotate an API key without downtime?", "version": None, "answer": "creating a second key"},
    {"q": "Is storage billed inside the free tier?", "version": None, "answer": "always billed"},
    {"q": "How can I lower my bill when publishing many messages?", "version": None, "answer": "Batching several messages"},
    {"q": "How long is the audit log kept?", "version": None, "answer": "kept for one year"},
    {"q": "Can customers bring their own encryption keys?", "version": None, "answer": "customer-managed keys"},
]


def write_docs(folder="data"):
    out = Path(folder)
    out.mkdir(exist_ok=True)
    for name, (_, text) in DOCS.items():
        (out / name).write_text(text, encoding="utf-8")
    return sorted(p.name for p in out.glob("*.md"))


if __name__ == "__main__":
    print("written:", write_docs())
    print("eval questions:", len(EVAL), "| with version:", sum(1 for e in EVAL if e["version"]))

執行 python corpus.py,預期:

written: ['billing.md', 'relay-v1.md', 'relay-v2.md', 'security.md']
eval questions: 12 | with version: 6

接著建立 rag_min.py,用 LlamaIndex 最少的程式碼跑完 Loading → Indexing → Querying(只到 Retrieval):

from llama_index.core import Settings, SimpleDirectoryReader, VectorStoreIndex
from llama_index.embeddings.huggingface import HuggingFaceEmbedding

from corpus import write_docs

# Loading
write_docs("data")
documents = SimpleDirectoryReader("data").load_data()
print("documents:", len(documents))

# Indexing(預設把 Document 切成 Node,每個 Node 算一個 embedding)
Settings.embed_model = HuggingFaceEmbedding(model_name="sentence-transformers/all-MiniLM-L6-v2")
Settings.llm = None
index = VectorStoreIndex.from_documents(documents)
print("nodes:", len(index.docstore.docs))

# Querying:no_text 只跑檢索、不把 context 送給 LLM
engine = index.as_query_engine(similarity_top_k=2, response_mode="no_text")
for q in ["How long are messages retained in Relay v2?", "How do I rotate an API key without downtime?"]:
    response = engine.query(q)
    print("\nQ:", q)
    for n in response.source_nodes:
        first_line = n.node.get_content().strip().splitlines()[0]
        print(f"  {n.score:.3f}  {n.node.metadata['file_name']:<12} {first_line}")

執行 python rag_min.py。預期(教材作者實跑結果;模型載入訊息省略):

documents: 4
nodes: 4

Q: How long are messages retained in Relay v2?
  0.642  relay-v2.md  # Relay v2 Operator Guide
  0.622  relay-v1.md  # Relay v1 Operator Guide

Q: How do I rotate an API key without downtime?
  0.278  security.md  # Relay Security
  0.080  billing.md   # Relay Billing

你的分數會跟上面差一點點(教材作者換一個資料夾重跑,第一題變成 0.634 與 0.617),排名不變。原因是 SimpleDirectoryReader 會把檔案的絕對路徑當成 metadata,而 metadata 預設會被放進 embedding 的文字裡——資料夾不同,embedding 就不同。Day 66 會細講這件事。第一題撈回了整份 v2 與整份 v1 文件,兩者分數只差約 0.02。最後在筆記裡畫一張圖:把 rag_min.py 的每一行對應到 Introduction to RAG 的五個階段之一,並標出哪個階段今天沒有出現。

過關標準

  • 能回答:RAG 的五個階段各自的輸入與輸出是什麼?rag_min.py 缺了哪一個?
  • 能回答:Querying 的三段裡,response_mode="no_text" 停在哪一段?為什麼先停在這裡有助於除錯?
  • 能回答:第一題撈回的兩個 node 各有多長?如果把它們整份送進 LLM,會多花什麼?
  • 產出:corpus.py、rag_min.py 與它的輸出,以及「程式碼行 ↔ RAG 階段」對應圖
  1. 依 AI 課程線總綱(curriculum/ai/00-master-curriculum.md)第 12 節「Phase 07 — RAG / Knowledge / Memory」的目標
  2. 依總綱第 12 節「主教材」與「搭配」
  3. 依總綱第 12 節「實作」
  4. 依總綱第 12 節「驗收 → Project 2:Production RAG」
  5. 依總綱第 4 節跟 Backend 課程的重疊對照表(Phase 07 ↔ Backend Day 82、83、84)與第 12 節「跟 Backend 課程重疊」

Day 62 — Embedding model:Sentence Transformers

今天要回答的問題

embedding model 把一句話變成什麼?「相似度高」在這個模型裡到底代表什麼——為什麼兩句意思相反的話也可能分數很高?

主教材(Core)

  • Sentence Transformers 文件 — Quickstart(Sentence Transformer、Cross Encoder 兩節),預估 20 分鐘
  • Sentence Transformers 文件 — Semantic Textual Similarity(Similarity Calculation 一節),預估 15 分鐘
  • Sentence Transformers 文件 — Pretrained Models(Original Models、Semantic Search Models 兩節),預估 20 分鐘
  • 實作,預估 50 分鐘

搭配(Companion,選讀)

  • LlamaIndex 文件 — Embeddings(Concept、Choosing an embedding model、Local Embedding Models 三節),看 LlamaIndex 怎麼包裝同一個模型;預估 15 分鐘

讀的時候抓這幾個重點

  • 這部分已在 Backend Day 82 講過:embedding 是把文字映射成稠密向量、cosine 與內積怎麼算、為什麼正規化之後兩者等價。今天的新角度是:拿一個真實模型,看它在「只差一個數字」的兩句話上會不會分得開。
  • Bi-encoder 每段文字各自編碼。 Quickstart 說 Sentence Transformer 為每個輸入產生固定長度的 embedding,算相似度很快,所以常被當成兩階段檢索的第一步;Cross Encoder 則一次讀「一對」輸入,通常更準但更慢。今天只用前者,Day 67 才用後者,但現在先記住這個速度與準度的取捨。
  • 相似度函式是模型的設定,不是你隨便選。 Semantic Textual Similarity 頁說相似度函式存在 similarity_fn_name,預設是 cosine;如果模型最後一層是 Normalize,用內積會跟 cosine 結果一樣但更快。今天的程式會印出向量長度,讓你親眼確認 all-MiniLM-L6-v2 的輸出是否已經正規化。
  • 選模型要在自己的資料上試。 Pretrained Models 頁說 all-MiniLM-L6-v2 比 all-mpnet-base-v2 快 5 倍、品質仍然不錯,但也強調排行榜成績不保證在你的資料上一樣好,要自己實驗。Semantic Search Models 一節另外列了用問答資料訓練的 Multi-QA 與 MSMARCO 系列,是專門給「問題找段落」用的。

實作

建立 embed.py:

import numpy as np
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")

query = "How long are messages retained in Relay v2?"
sentences = [
    "Unacknowledged and acknowledged messages are both kept for 14 days.",  # v2 的正確答案
    "Unacknowledged and acknowledged messages are both kept for 7 days.",   # v1,只差一個數字
    "Retention is configured per topic and cannot be changed for a single subscription.",
    "Invoices are issued on the first business day of each month.",
]

q_emb = model.encode([query])
s_emb = model.encode(sentences)
print("dim:", s_emb.shape[1])
print("norms:", np.round(np.linalg.norm(s_emb, axis=1), 3))

scores = model.similarity(q_emb, s_emb)[0]
for s, score in sorted(zip(sentences, scores.tolist()), key=lambda x: -x[1]):
    print(f"{score:.3f}  {s}")

v2, v1 = s_emb[0], s_emb[1]
print("v1 vs v2 sentence similarity:", round(float(model.similarity(v1[None], v2[None])[0][0]), 3))

執行 python embed.py。預期(教材作者實跑結果):

dim: 384
norms: [1. 1. 1. 1.]
0.585  Unacknowledged and acknowledged messages are both kept for 14 days.
0.582  Unacknowledged and acknowledged messages are both kept for 7 days.
0.212  Retention is configured per topic and cannot be changed for a single subscription.
0.015  Invoices are issued on the first business day of each month.
v1 vs v2 sentence similarity: 0.989

「14 天」與「7 天」對問題的分數只差 0.003,兩句彼此的相似度是 0.989——對這個模型來說它們幾乎是同一句話。接著做兩個小實驗並記錄分數:(1) 把問題裡的 Relay v2 拿掉,排名有沒有變?(2) 從 Pretrained Models 頁的 Semantic Search Models 一節挑一個 Multi-QA 模型換上去(換掉兩處模型名稱即可,第一次執行會下載),「14 天」和「7 天」的差距有沒有拉開?

過關標準

  • 能回答:all-MiniLM-L6-v2 輸出的向量長度是多少?為什麼這代表 cosine 和內積排序相同?
  • 能回答:為什麼 embedding 分不開「7 天」和「14 天」?這對「v1 和 v2 文件放在同一個索引」意味著什麼?
  • 產出:embed.py 與兩個小實驗的分數表(原本、拿掉 Relay v2、換 Multi-QA 模型)

Day 63 — Vector DB:Qdrant 的 collection、point、payload、search

今天要回答的問題

向量資料庫裡存的一筆資料長什麼樣?除了向量,還存了什麼、為什麼要存?查詢時能不能說「只在某些資料裡找」?

主教材(Core)

  • Qdrant 文件 — Collections(Create a Collection 一節),預估 15 分鐘
  • Qdrant 文件 — Points(Point IDs、Upload Points、Idempotence 三節),預估 20 分鐘
  • Qdrant 文件 — Search(Query API、Filtering Results by Score、Payload and Vector in the Result 三節),預估 20 分鐘
  • qdrant-client — GitHub README(Local mode 一節),預估 5 分鐘
  • 實作,預估 50 分鐘

搭配(Companion,選讀)

  • Qdrant 文件 — Local Quickstart(Create a collection、Add vectors、Run a query、Add a filter 四節),同樣的操作用 Docker 起的 server 做一次;預估 15 分鐘

讀的時候抓這幾個重點

  • 這部分已在 Backend Day 83 講過:向量索引(例如 HNSW)怎麼用近似換速度、跟倒排索引與 BM25 的差異。今天的新角度是:在真實的向量資料庫裡,一筆資料由向量加上 payload 組成,而 payload 就是之後做過濾的依據。
  • Collection 綁定維度與距離。 Collections 頁說同一個 collection 裡所有向量的維度必須相同、用同一種距離(Dot、Cosine、Euclid、Manhattan),而 Cosine 是對正規化後的向量做內積,上傳時會自動正規化。所以 size=384 不是你隨便填的數字,它必須等於 Day 62 印出的 dim。
  • Point = id + vector + payload,upsert 是冪等的。 Points 頁說 point id 可以是無號 64 位元整數或 UUID;upsert 時 id 不存在就新增、存在就覆蓋,重複送同一批不會變多。這跟你在 Backend 做 idempotent API 是同一件事:重跑 ingestion 不該讓資料翻倍,前提是 id 要穩定。
  • ANN 是近似的。 Search 頁說 HNSW 是近似最近鄰,排名在不同請求之間可能有些微變動;exact 參數可以關掉近似、改成全掃描,但大 collection 會很慢。另外 with_payload 預設不回傳 payload,要明講才拿得到。(今天用的 local mode 資料量很小,看不到近似帶來的差異。)

實作

今天先不用 LlamaIndex,直接用 qdrant-client 做一次,看清楚底層長什麼樣。建立 qdrant_raw.py,每個 ## 小節存成一個 point:

from qdrant_client import QdrantClient, models
from sentence_transformers import SentenceTransformer

from corpus import DOCS

model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
client = QdrantClient(":memory:")  # local mode:不用起 server,資料只在這個程式的記憶體裡

client.create_collection(
    collection_name="relay_sections",
    vectors_config=models.VectorParams(size=384, distance=models.Distance.COSINE),
)

# 一個 "## " 小節 = 一個 point;payload 記下它來自哪份文件、哪個版本、哪一節
points, pid = [], 0
for file_name, (version, text) in DOCS.items():
    for block in text.split("\n## ")[1:]:
        section, body = block.split("\n", 1)
        pid += 1
        points.append(models.PointStruct(
            id=pid,
            vector=model.encode(body).tolist(),
            payload={"file": file_name, "version": version, "section": section, "text": body.strip()},
        ))
client.upsert(collection_name="relay_sections", points=points)
print("points:", client.count("relay_sections").count)

# 同一批 id 再 upsert 一次:是覆蓋,不是新增
client.upsert(collection_name="relay_sections", points=points)
print("points after re-upsert:", client.count("relay_sections").count)

query = "How long are messages retained in Relay v2?"
hits = client.query_points(
    collection_name="relay_sections",
    query=model.encode(query).tolist(),
    limit=3,
    with_payload=True,
).points
for h in hits:
    print(f"{h.score:.3f}  {h.payload['file']:<12} {h.payload['section']}")

# 同一個問題,加上 payload filter:只在 v2 的 point 裡找
v2_only = models.Filter(must=[models.FieldCondition(key="version", match=models.MatchValue(value="v2"))])
hits = client.query_points(
    collection_name="relay_sections",
    query=model.encode(query).tolist(),
    query_filter=v2_only,
    limit=3,
    with_payload=True,
).points
print("--- with filter version=v2 ---")
for h in hits:
    print(f"{h.score:.3f}  {h.payload['file']:<12} {h.payload['section']}")

執行 python qdrant_raw.py。預期(教材作者實跑結果):

points: 16
points after re-upsert: 16
0.646  relay-v2.md  Delivery guarantees
0.643  relay-v1.md  Delivery guarantees
0.612  relay-v2.md  Retention
--- with filter version=v2 ---
0.646  relay-v2.md  Delivery guarantees
0.612  relay-v2.md  Retention
0.531  relay-v2.md  Overview

注意兩件事:問的是保存期限(Retention),第一名卻是 Delivery guarantees;加了 filter 之後 v1 的結果消失了,但第一名還是錯的。在筆記裡回答:filter 解決了什麼問題、沒解決什麼問題?然後試一次把 vector=model.encode(body) 改成連小節標題一起編碼(f"{section}\n{body}"),記錄前三名有沒有變(教材作者實測:前三名順序不變,分數都略降)。

過關標準

  • 能回答:VectorParams(size=384, ...) 的 384 從哪裡來?填錯會怎樣?
  • 能回答:為什麼重複 upsert 之後 point 數量不變?如果每次 ingestion 都用隨機 UUID 當 id,會發生什麼事?
  • 能回答:payload filter 跟「撈回來之後再用 Python 過濾」有什麼差別?(提示:想想 limit=3)
  • 產出:qdrant_raw.py、兩次查詢的輸出,以及「filter 解決了什麼/沒解決什麼」的筆記

Day 64 — Loading 與 Chunking:chunk 太大、chunk 太小

今天要回答的問題

文件要切成多大的 chunk?切太大、切太小各會壞在哪裡——是「找不到」,還是「找得到但太貴」?

主教材(Core)

  • LlamaIndex 文件 — Loading Data (Ingestion)(Loaders、Transformations 兩節,含 Splitting Your Documents into Nodes 與 Adding Metadata),預估 25 分鐘
  • LlamaIndex 文件 — Node Parser Modules(MarkdownNodeParser、SentenceSplitter、SentenceWindowNodeParser、HierarchicalNodeParser 四節),預估 15 分鐘
  • LlamaIndex 文件 — Qdrant Vector Store(Creating a Qdrant client、Build the VectorStoreIndex 兩節),預估 10 分鐘
  • 實作,預估 60 分鐘

搭配(Companion,選讀)

  • LlamaIndex 文件 — Storing(Persisting to disk、Using Vector Stores 兩節),了解預設的記憶體存放與換成向量資料庫的差別;預估 10 分鐘

讀的時候抓這幾個重點

  • 這部分已在 Backend Day 84 講過:chunking 策略(固定長度、按段落、重疊)與它對檢索的影響。今天的新角度是:在同一份語料上量出 chunk 大小對 hit rate 與 context 量的實際影響。
  • 切 node 是 transformation 的一種。 Loading Data 頁說 transformation 吃 node、吐 node,可以串起來;切 chunk、抽 metadata、算 embedding 都是 transformation。範例用 SentenceSplitter(chunk_size=512, chunk_overlap=10),可以設成全域的 Settings.text_splitter,也可以在建索引時用 transformations= 傳進去。今天的 lab.py 用後者,這樣每個實驗可以用不同大小。
  • chunk_size 的單位是 token,而且 metadata 也算在裡面。 今天切 40 token 時你會看到 Metadata length (12) is close to chunk size (40) 的警告:LlamaIndex 會把 metadata 文字也放進每個 chunk,扣掉之後真正的內文只剩不到 30 token。這是 Day 66 要細講的「metadata 會被注入」的第一個徵兆。
  • 不只有固定長度一種切法。 Node Parser Modules 頁列了 MarkdownNodeParser(依 Markdown 結構切)、SentenceWindowNodeParser(一句一個 node,前後幾句存在 metadata 裡)、HierarchicalNodeParser(多種大小的巢狀 chunk,小的連到大的)。後兩種都是在處理同一個矛盾:小 chunk 檢索準、大 chunk 上下文完整。

實作

建立 lab.py,這是 Day 64–69 共用的實驗台:建索引(存進 Qdrant local mode)、檢索、評估。評估的定義寫在 evaluate 的 docstring 裡——hit 是「前 k 個 chunk 裡有沒有任何一個包含標準答案字串」,MRR 是「第一個命中的排第幾名」取倒數再平均:

"""Phase 07 的共用實驗台:建索引、檢索、評估。Day 64 起每天都 import 它。"""
import time

from llama_index.core import Document, Settings, StorageContext, VectorStoreIndex
from llama_index.core.node_parser import SentenceSplitter
from llama_index.core.vector_stores import FilterOperator, MetadataFilter, MetadataFilters
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.vector_stores.qdrant import QdrantVectorStore
from qdrant_client import QdrantClient

from corpus import DOCS, EVAL

EMBED_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
Settings.embed_model = HuggingFaceEmbedding(model_name=EMBED_MODEL)
Settings.llm = None  # 這個 Phase 的檢索實驗不呼叫 LLM


def load_documents(with_metadata=True):
    docs = []
    for name, (version, text) in DOCS.items():
        meta = {"file_name": name, "version": version} if with_metadata else {}
        docs.append(Document(text=text, metadata=meta))
    return docs


def build_index(chunk_size=128, chunk_overlap=20, with_metadata=True, collection="relay"):
    client = QdrantClient(":memory:")
    store = QdrantVectorStore(client=client, collection_name=collection)
    splitter = SentenceSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
    index = VectorStoreIndex.from_documents(
        load_documents(with_metadata),
        storage_context=StorageContext.from_defaults(vector_store=store),
        transformations=[splitter],
    )
    n_nodes = len(splitter.get_nodes_from_documents(load_documents(with_metadata)))
    return index, n_nodes


def version_filter(version):
    if version is None:
        return None
    return MetadataFilters(filters=[MetadataFilter(key="version", operator=FilterOperator.EQ, value=version)])


def evaluate(index, top_k=3, use_filter=False, reranker=None, fetch_k=None):
    """回傳 hit rate、MRR、平均送進 LLM 的 context 字數、平均檢索延遲(毫秒)。

    hit:前 top_k 個 chunk 裡有任何一個包含標準答案字串。
    MRR:第一個命中的 chunk 排第幾名,取倒數再平均;沒命中算 0。
    """
    hits, rr, chars, ms = 0, 0.0, 0, 0.0
    for item in EVAL:
        filters = version_filter(item["version"]) if use_filter else None
        k = fetch_k if reranker else top_k
        retriever = index.as_retriever(similarity_top_k=k, filters=filters)
        t0 = time.perf_counter()
        nodes = retriever.retrieve(item["q"])
        if reranker:
            nodes = reranker.postprocess_nodes(nodes, query_str=item["q"])[:top_k]
        ms += (time.perf_counter() - t0) * 1000
        texts = [n.node.get_content() for n in nodes]
        chars += sum(len(t) for t in texts)
        for rank, t in enumerate(texts, start=1):
            if item["answer"] in t:
                hits += 1
                rr += 1 / rank
                break
    n = len(EVAL)
    return {"hit": hits / n, "mrr": rr / n, "ctx_chars": chars / n, "ms": ms / n}


def fmt(row):
    return f"hit={row['hit']:.2f}  mrr={row['mrr']:.2f}  ctx_chars={row['ctx_chars']:.0f}  ms={row['ms']:.1f}"

再建立 day64_chunking.py:

from lab import build_index, evaluate, fmt

for chunk_size, overlap in [(40, 10), (64, 16), (512, 20)]:
    index, n_nodes = build_index(chunk_size=chunk_size, chunk_overlap=overlap)
    for k in (1, 3):
        print(f"chunk_size={chunk_size:<4} nodes={n_nodes:<3} top_k={k}  {fmt(evaluate(index, top_k=k))}")

執行 python day64_chunking.py。預期(教材作者實跑結果;chunk_size=40 時會先印出數行 Metadata length ... is close to chunk size (40) 的警告,這裡省略):

chunk_size=40   nodes=40  top_k=1  hit=0.83  mrr=0.83  ctx_chars=104  ms=4.9
chunk_size=40   nodes=40  top_k=3  hit=0.92  mrr=0.88  ctx_chars=298  ms=4.0
chunk_size=64   nodes=25  top_k=1  hit=0.83  mrr=0.83  ctx_chars=184  ms=4.2
chunk_size=64   nodes=25  top_k=3  hit=1.00  mrr=0.92  ctx_chars=548  ms=4.4
chunk_size=512  nodes=4   top_k=1  hit=0.83  mrr=0.83  ctx_chars=1026  ms=5.4
chunk_size=512  nodes=4   top_k=3  hit=1.00  mrr=0.92  ctx_chars=3141  ms=4.1

在筆記裡寫下兩個觀察:chunk 太小(40)時,top_k=3 仍然漏掉一題(v2 的訊息大小上限)——教材作者檢查過,答案那句「larger than 1 MB」被切成獨立的一個 chunk,跟小節標題「Message size limits」分開了,撈回來的前三名反而是只有標題和第一句的 chunk;chunk 太大(512)時 hit 沒變差,但每題送進 LLM 的字數是 64 的近 6 倍。最後把 SentenceSplitter 換成 MarkdownNodeParser(照 Node Parser Modules 頁的範例建立,範例裡沒有設 chunk 大小),記錄 node 數與 top_k=1、3 的結果。

過關標準

  • 能回答:在這份語料上,chunk 太小與太大各自「壞」在哪個指標上?為什麼 chunk 太大時 hit 沒有下降?
  • 能回答:v2 訊息大小上限那題,為什麼答案句明明在索引裡,chunk 40 時卻排不進前三?
  • 能回答:Metadata length is close to chunk size 這個警告代表什麼?
  • 產出:lab.py、day64_chunking.py 的輸出,以及加上 MarkdownNodeParser 那一列的對照表

Deep Dive(選讀)

  • 讀 Node Parser Modules 頁的 SemanticSplitterNodeParser 一節:它用 embedding 相似度決定在哪裡斷句。想想看在 Relay 這種「每節講一件事」的文件上,它跟 MarkdownNodeParser 的結果會不會差很多,再實測。

Day 65 — Retrieval:top-k 太多、太少,以及怎麼量

今天要回答的問題

一次要撈幾個 chunk?撈太少會漏掉答案,撈太多會怎樣——如果 hit rate 已經是 1.0,多撈還有什麼代價?

主教材(Core)

  • LlamaIndex 文件 — Indexing(What is an embedding?、Vector Store Index embeds your documents、Top K Retrieval 三節),預估 20 分鐘
  • LlamaIndex 文件 — Usage Pattern (Retrieval)(Using RetrieverEvaluator、Building an Evaluation Dataset 兩節),預估 15 分鐘
  • LlamaIndex 文件 — Cost Analysis(Overview of Cost Structure、Query Time 兩節),預估 15 分鐘
  • 實作,預估 45 分鐘

搭配(Companion,選讀)

  • Qdrant 文件 — Search(Filtering Results by Score 一節),看「依分數門檻截斷」這個 top-k 以外的選項;預估 10 分鐘

讀的時候抓這幾個重點

  • top-k 是檢索最直接的旋鈕。 Indexing 頁的 Top K Retrieval 一節說:問題會被 embedding,跟所有存好的 embedding 比相似度,回傳最相似的 k 個。k 決定了「LLM 最多能看到幾段」,所以它同時影響答得出來的機率與 prompt 的長度。
  • hit rate 和 MRR 量的是不同的東西。 Usage Pattern (Retrieval) 頁的 RetrieverEvaluator 用 mrr 與 hit_rate 兩個指標,但頁面本身沒有定義它們;今天就以 lab.py 的 docstring 為準:hit 只問「有沒有撈到」,MRR 還問「排第幾」。hit 一樣、MRR 較低,代表答案有撈到但被排在後面——之後如果要截斷 context,排在後面的就最先被丟掉。
  • 多撈的代價在 LLM 那一端。 Cost Analysis 頁的 Query Time 一節說:VectorStoreIndex 每次查詢至少一次 LLM 呼叫,而 similarity_top_k 與 chunk_size 調大會讓這次呼叫的 token 變多。檢索本身幾乎不花錢(今天的毫秒數會證明這點),花錢的是把撈到的東西送進 LLM。
  • 評估資料集不一定要手寫。 Building an Evaluation Dataset 一節用 generate_question_context_pairs 讓 LLM 從 node 自動出題。這個 Phase 不呼叫 LLM,所以用 corpus.py 手寫的 12 題;但要知道手寫題目的偏差:你只會問你想得到的問題。

實作

建立 day65_topk.py:

from lab import build_index, evaluate, fmt

index, n_nodes = build_index(chunk_size=64, chunk_overlap=16)
print("nodes:", n_nodes)
for k in (1, 2, 3, 5, 10):
    print(f"top_k={k:<3} {fmt(evaluate(index, top_k=k))}")

執行 python day65_topk.py。預期(教材作者實跑結果):

nodes: 25
top_k=1   hit=0.83  mrr=0.83  ctx_chars=184  ms=5.6
top_k=2   hit=1.00  mrr=0.92  ctx_chars=381  ms=4.3
top_k=3   hit=1.00  mrr=0.92  ctx_chars=548  ms=4.1
top_k=5   hit=1.00  mrr=0.92  ctx_chars=923  ms=4.2
top_k=10  hit=1.00  mrr=0.92  ctx_chars=1763  ms=4.2

從 k=2 開始 hit 與 MRR 都不再變,但 context 一路從 381 漲到 1763 字元,檢索時間則幾乎不變。在筆記裡做兩件事:(1) 用你在 Phase 06 Day 57 的成本追蹤方式,以「1 token 約 4 個英文字元」粗估,算出 k=2 與 k=10 每題多送進 LLM 多少 token;(2) 找出 k=1 時沒命中的那兩題(提示:在 evaluate 裡印出沒命中的 item["q"]),寫下你猜它們為什麼排不上第一名。

過關標準

  • 能回答:hit rate 與 MRR 的差別是什麼?什麼情況下 hit 一樣但 MRR 不同?
  • 能回答:為什麼 k 從 2 調到 10,hit 不變而成本變高?什麼樣的語料會讓 k=10 反而降低答案品質?
  • 產出:day65_topk.py 的輸出、k=2 與 k=10 的 token 估算,以及 k=1 沒命中的兩題與你的猜測

Day 66 — Metadata 與 filter:沒有 metadata 會拿錯版本

今天要回答的問題

v1 與 v2 的文件幾乎一模一樣,問「v2 的保存期限」時,系統怎麼知道該拿 v2 那份?metadata 有哪兩種用法,各自解決什麼?

主教材(Core)

  • LlamaIndex 文件 — Defining and Customizing Documents(Metadata、Advanced - Metadata Customization 兩節),預估 20 分鐘
  • LlamaIndex 範例 — Qdrant Vector Store - Metadata Filter(Define metadata filters、Retrieve from vector store with filters、Multiple Metadata Filters with AND condition 三節),預估 15 分鐘
  • Qdrant 文件 — Filtering(Filtering clauses、Must、Exact Match conditions 三節,以及頁首關於 payload index 的提示),預估 20 分鐘
  • 實作,預估 45 分鐘

搭配(Companion,選讀)

  • LlamaIndex 文件 — Vector Stores(Vector Store Options & Feature Support 一節),看哪些向量資料庫支援 Metadata Filtering 與 Hybrid Search;預估 10 分鐘

讀的時候抓這幾個重點

  • metadata 預設會被注入 embedding 的文字。 Defining and Customizing Documents 頁說:Document 的 metadata 會複製到切出來的每個 node,而且預設會被放進送給 embedding 模型與 LLM 的文字裡。這就是 Day 64 那個 Metadata length 警告的來源,也是今天第一種用法:「讓 embedding 看到版本號」。
  • 你可以控制誰看得到哪些 metadata。 同一頁的 excluded_embed_metadata_keys 讓某些 key 不進 embedding(避免無關資訊干擾檢索),excluded_llm_metadata_keys 讓某些 key 不進 LLM;用 get_content(metadata_mode=MetadataMode.EMBED) 可以直接看到 embedding 模型實際收到的文字。今天的程式會印出來給你看。
  • filter 是第二種用法,而且更硬。 Metadata Filter 範例用 MetadataFilters 加 MetadataFilter(key=..., operator=FilterOperator.EQ, value=...),再 index.as_retriever(filters=filters)。它不是「讓分數偏向 v2」,而是「v1 根本不在候選裡」。Qdrant 的 Filtering 頁說 must 是 AND、should 是 OR、must_not 是 NOT,並建議對要過濾的欄位建 payload index,而且最好在灌資料之前建。
  • filter 需要有人知道要過濾什麼。 今天的評估題裡 version 是直接給的;真實系統裡它可能來自使用者的帳號設定、URL 或 UI 的下拉選單,也可能要從問題裡解析。這是產品決策,不是檢索演算法能替你決定的事。

實作

建立 day66_metadata.py,比較三種情況:完全沒有 metadata、metadata 只注入文字、metadata 加上 filter:

from llama_index.core.schema import MetadataMode

from corpus import EVAL
from lab import build_index, evaluate, fmt

with_meta, _ = build_index(chunk_size=64, chunk_overlap=16, with_metadata=True)
no_meta, _ = build_index(chunk_size=64, chunk_overlap=16, with_metadata=False)

print("no metadata         ", fmt(evaluate(no_meta, top_k=1)))
print("metadata in text    ", fmt(evaluate(with_meta, top_k=1)))
print("metadata + filter   ", fmt(evaluate(with_meta, top_k=1, use_filter=True)))

# embedding 模型實際看到的文字長什麼樣
node = with_meta.as_retriever(similarity_top_k=1).retrieve(EVAL[1]["q"])[0].node
print("\n--- what the embedding model saw ---")
for line in node.get_content(metadata_mode=MetadataMode.EMBED)[:160].splitlines():
    print("    " + line)

print("\n--- top-1 misses without metadata ---")
retriever = no_meta.as_retriever(similarity_top_k=1)
for item in EVAL:
    top = retriever.retrieve(item["q"])[0].node.get_content()
    if item["answer"] not in top:
        print("MISS:", item["q"])

執行 python day66_metadata.py。預期(教材作者實跑結果):

no metadata          hit=0.67  mrr=0.67  ctx_chars=265  ms=5.5
metadata in text     hit=0.83  mrr=0.83  ctx_chars=184  ms=4.0
metadata + filter    hit=0.92  mrr=0.92  ctx_chars=183  ms=4.1

--- what the embedding model saw ---
    file_name: relay-v2.md
    version: v2
    
    ## Retention
    Messages stay on the broker after they are acknowledged. Unacknowledged and acknowledged messages are both kept

--- top-1 misses without metadata ---
MISS: How long are messages retained in Relay v2?
MISS: After how many failed attempts does Relay v2 move a message to the dead letter queue?
MISS: How many headers can a Relay v1 message carry?
MISS: How long does Relay v1 keep acknowledged messages?

沒有 metadata 時,沒命中的四題全部都是指定版本的題目——v1 和 v2 的段落太像,而切開之後的 chunk 裡沒有版本號(版本號只在文件標題那一行)。最後做一個實驗:在 lab.py 的 load_documents 裡,對每個 Document 設 excluded_embed_metadata_keys = ["version"],重跑並記錄「metadata in text」那一列的變化,用 Day 62 的結果解釋。

過關標準

  • 能回答:「metadata 注入文字」與「metadata filter」各自的機制是什麼?為什麼後者在這份語料上比前者更好?
  • 能回答:開了 filter 之後 hit 仍然不是 1.00,剩下那題的問題出在哪一層?(提示:教材作者查過,沒命中的是 v2 dead letter queue 那題,撈到的第一名是同一節的另一半:「Operators can inspect the dead letter queue…」)
  • 產出:day66_metadata.py 的輸出,以及排除 version 不進 embedding 之後的結果與解釋

Day 67 — Reranking:bi-encoder 撈、cross-encoder 排

今天要回答的問題

向量檢索已經給了分數,為什麼還要再排一次?reranker 能修好什麼、修不好什麼?

主教材(Core)

  • Sentence Transformers 文件 — Retrieve & Re-Rank(Retrieve & Re-Rank Pipeline、Retrieval: Bi-Encoder、Re-Ranker: Cross-Encoder 三節),預估 20 分鐘
  • Sentence Transformers 文件 — Cross Encoder Usage(Usage 一節),預估 10 分鐘
  • LlamaIndex 文件 — Node Postprocessor Modules(Choosing a reranker、SimilarityPostprocessor、SentenceTransformerRerank 三節),預估 15 分鐘
  • Qdrant 文件 — Hybrid and Multi-Stage Queries(Hybrid Search、Reciprocal Rank Fusion (RRF)、Choosing a Fusion Method 三節),預估 15 分鐘
  • 實作,預估 40 分鐘

搭配(Companion,選讀)

  • LlamaIndex 文件 — Qdrant Vector Store(Hybrid Search 一節),看 enable_hybrid=True 怎麼同時建稠密與稀疏索引。這一節需要另外安裝 fastembed,教材作者沒有實跑;預估 10 分鐘

讀的時候抓這幾個重點

  • 這部分已在 Backend Day 84 講過:混合檢索(關鍵字+向量)與 RRF 怎麼合併多份排名。今天的新角度是:第二階段不一定是「再找一份排名來合併」,也可以是「用更貴更準的模型重排前幾名」,以及量出它的效果與代價。
  • 兩階段是速度與準度的分工。 Retrieve & Re-Rank 頁說:retriever 必須在上百萬筆文件裡夠快,所以用 bi-encoder;但它可能撈到不太相關的文件,所以第二階段用 cross-encoder 把問題和每個候選一起讀、重新打分。頁面也說對上千上萬組(問題, 文件)都跑 cross-encoder 會很慢,所以只排前面那一小批。
  • cross-encoder 的分數不是機率。 Cross Encoder Usage 頁的範例分數是 8.61 與 -4.32:MS MARCO 系列輸出的是原始 logit,只能拿來排序,不能當成「相關的機率」去設門檻;要 0 到 1 之間的值得另外套 sigmoid。
  • LlamaIndex 裡 reranker 是一種 node postprocessor。 Node Postprocessor Modules 頁的 SentenceTransformerRerank 範例用 cross-encoder/ms-marco-MiniLM-L2-v2、top_n=3,並註明是挑速度較快、準度尚可的模型。今天用的是 Cross Encoder Usage 頁範例裡的 L6 版本。
  • Hybrid 是另一條路。 Qdrant 的 Hybrid Queries 頁說 hybrid 是結合稠密與稀疏向量,用 prefetch 各撈一批再融合;沒有評估集時 RRF 是安全的預設,有評估集時可以調加權 RRF。今天只讀不做;實作 hybrid 需要額外的稀疏向量模型。

實作

建立 day67_rerank.py:先撈 10 個,再用 cross-encoder 排出第一名,跟直接取向量檢索第一名比:

from llama_index.core.postprocessor import SentenceTransformerRerank

from lab import build_index, evaluate, fmt

reranker = SentenceTransformerRerank(model="cross-encoder/ms-marco-MiniLM-L6-v2", top_n=10)

with_meta, _ = build_index(chunk_size=64, chunk_overlap=16, with_metadata=True)
no_meta, _ = build_index(chunk_size=64, chunk_overlap=16, with_metadata=False)
evaluate(with_meta, top_k=1, reranker=reranker, fetch_k=10)  # 暖機:第一次呼叫要載入模型

for name, index in [("metadata", with_meta), ("no metadata", no_meta)]:
    print(f"{name:<12} vector top-1          {fmt(evaluate(index, top_k=1))}")
    print(f"{name:<12} fetch 10 -> rerank 1  {fmt(evaluate(index, top_k=1, reranker=reranker, fetch_k=10))}")

執行 python day67_rerank.py。預期(教材作者實跑結果):

metadata     vector top-1          hit=0.83  mrr=0.83  ctx_chars=184  ms=4.1
metadata     fetch 10 -> rerank 1  hit=1.00  mrr=1.00  ctx_chars=188  ms=14.4
no metadata  vector top-1          hit=0.67  mrr=0.67  ctx_chars=265  ms=4.1
no metadata  fetch 10 -> rerank 1  hit=0.67  mrr=0.67  ctx_chars=264  ms=17.0

這四列要一起看:有 metadata 時,reranker 把 hit 從 0.83 拉到 1.00;沒有 metadata 時,reranker 完全沒幫上忙。在筆記裡用一段話解釋為什麼(提示:cross-encoder 讀的是 chunk 的哪段文字?那段文字裡有沒有「v2」?Day 66 印出的 embedding 文字給了答案)。再記下 reranking 讓每題延遲增加了多少毫秒。

過關標準

  • 能回答:bi-encoder 與 cross-encoder 各自讀什麼輸入?為什麼前者能先算好存起來、後者不能?
  • 能回答:為什麼沒有 metadata 時 reranker 救不回來?這說明 reranker 能修好哪一類錯誤、修不好哪一類?
  • 能回答:hybrid search(RRF)與 cross-encoder reranking 都是「第二階段」,它們解決的問題有什麼不同?
  • 產出:day67_rerank.py 的輸出與上面那段解釋,以及 reranking 的延遲成本

Day 68 — 生成與引用:讓答案指得出來源

今天要回答的問題

把撈到的 chunk 交給 LLM 之後,要怎麼讓答案「指得出來源」?引用對不對,能不能用程式檢查,而不是靠人看?

主教材(Core)

  • LlamaIndex 文件 — Response Synthesizer(Concept、Configuring the Response Mode 兩節),預估 20 分鐘
  • LlamaIndex 範例 — CitationQueryEngine(Create the CitationQueryEngine w/ Default Arguments、Inspecting the Actual Source、Adjusting Settings 三節),預估 20 分鐘
  • 實作,預估 60 分鐘

搭配(Companion,選讀)

  • LlamaIndex 文件 — Evaluating(Response Evaluation 一節),先看 Faithfulness 這類「答案有沒有忠於來源」的 LLM 評審,明天會用到;預估 10 分鐘

讀的時候抓這幾個重點

  • Response mode 決定 LLM 被呼叫幾次。 Response Synthesizer 頁列出 refine(每個 chunk 呼叫一次、逐步修正答案)、compact(預設,先把 chunk 塞滿再呼叫,次數較少)、tree_summarize(分批摘要再遞迴合併)等模式。Day 61 用的 no_text 只跑檢索、不呼叫 LLM。選哪一種直接影響延遲與成本,不只影響答案風格。
  • CitationQueryEngine 的做法是先把來源切細、編號。 範例說 citation_chunk_size 控制引用的粒度(預設 512),比原本的 node 還大就沒有作用;答案裡會出現 [1]、[2],對應 Source 1:、Source 2:。注意它提醒的 off-by-one:Source 1 在 response.source_nodes[0]。
  • 引用是可以驗證的輸出。 一旦答案格式是「主張 [n]」,後端就能檢查:n 有沒有超出範圍、主張的內容在不在第 n 個來源裡。這跟你在 Phase 06 驗證 structured output 是同一個精神——不相信模型,驗證模型。今天的 check_citations 用最嚴格的版本:主張必須是來源裡的原文。真實 LLM 會改寫句子,到時候要換成較寬鬆的比對(例如 Day 69 的 Faithfulness 評審),但「每個 [n] 都要檢查」這件事不變。

實作

這個 Phase 不呼叫付費 LLM。生成那一步用一個替身 LLM:從來源裡挑出跟問題最相關的一句原文,標上它來自第幾個來源。它的輸入(問題+編號來源)和輸出(帶 [n] 的文字)跟真的 LLM 形狀相同,所以 prompt 組裝與引用檢查都能真的被測到。建立 cite.py:

import re

from sentence_transformers import CrossEncoder

from lab import build_index, version_filter

cross_encoder = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")


def retrieve(index, question, version=None, k=3):
    nodes = index.as_retriever(similarity_top_k=k, filters=version_filter(version)).retrieve(question)
    return [n.node.get_content() for n in nodes]


def build_prompt(question, sources):
    context = "\n\n".join(f"[{i}] {s}" for i, s in enumerate(sources, start=1))
    return (
        "Answer using only the sources below. Cite every claim with [n].\n"
        "If the sources do not contain the answer, say you don't know.\n\n"
        f"{context}\n\nQuestion: {question}\nAnswer:"
    )


def fake_llm(question, sources):
    """教材用的替身 LLM:挑出跟問題最相關的一句原文,標上它來自第幾個 source。
    換成真的 LLM 時,輸入(question + sources)和輸出(帶 [n] 的文字)的形狀不變。"""
    candidates = [
        (i, s.strip())
        for i, src in enumerate(sources, start=1)
        for s in re.split(r"(?<=[.!?])\s+|\n+", src)
        if s.strip() and not s.startswith("#")
    ]
    scores = cross_encoder.predict([(question, s) for _, s in candidates])
    i, sentence = candidates[int(scores.argmax())]
    return f"{sentence} [{i}]"


def check_citations(answer, sources):
    cited = [int(x) for x in re.findall(r"\[(\d+)\]", answer)]
    if not cited:
        return "FAIL: no citation"
    for n in cited:
        if not 1 <= n <= len(sources):
            return f"FAIL: [{n}] out of range"
    claim = re.sub(r"\s*\[\d+\]", "", answer).strip()
    if not any(claim in sources[n - 1] for n in cited):
        return "FAIL: claim not found in cited source"
    return "OK"


if __name__ == "__main__":
    index, _ = build_index(chunk_size=64, chunk_overlap=16)
    q, version = "How long are messages retained in Relay v2?", "v2"
    sources = retrieve(index, q, version)
    print(build_prompt(q, sources)[:300], "...\n")
    answer = fake_llm(q, sources)
    print("answer:", answer)
    print("check :", check_citations(answer, sources))

    wrong = re.sub(r"\[\d+\]", "[3]" if not answer.endswith("[3]") else "[1]", answer)
    print("tampered:", wrong)
    print("check   :", check_citations(wrong, sources))

執行 python cite.py。預期(教材作者實跑結果):

Answer using only the sources below. Cite every claim with [n].
If the sources do not contain the answer, say you don't know.

[1] ## Retention
Messages stay on the broker after they are acknowledged. Unacknowledged and acknowledged messages are both kept for 14 days, after which a background job de ...

answer: Unacknowledged and acknowledged messages are both kept for 14 days, after which a background job deletes them. [1]
check : OK
tampered: Unacknowledged and acknowledged messages are both kept for 14 days, after which a background job deletes them. [3]
check   : FAIL: claim not found in cited source

最後的「tampered」把引用改成 [3],檢查就失敗了——這就是你要在 LLM 輸出上做的事。接著做兩件事:(1) 用 Phase 06 的 Router(或任何你能呼叫的模型,例如 Phase 05 的 Ollama)取代 fake_llm,送出 build_prompt 組好的 prompt,記錄 check_citations 的結果(真實 LLM 會改寫句子,記下嚴格比對失敗的例子,這一步教材作者沒有實跑);(2) 問一個語料裡沒有答案的問題(例如「Relay 支援哪些程式語言的 SDK?」),看替身 LLM 與真實 LLM 各自怎麼回答。

過關標準

  • 能回答:refine 與 compact 兩種 response mode,LLM 呼叫次數有什麼不同?各適合什麼情況?
  • 能回答:check_citations 檢查了哪三件事?如果真實 LLM 會改寫句子,哪一項要放寬、怎麼放寬?
  • 能回答:替身 LLM 對「語料裡沒有答案的問題」會怎麼回答?為什麼這是它跟真實 LLM 最大的差別?
  • 產出:cite.py 與它的輸出;接上真實模型的那次,記錄 prompt、答案與檢查結果

Day 69 — Evaluation:六種故意做錯的對照表

今天要回答的問題

把這個 Phase 每一種「故意做錯」放在同一張表裡比,哪一種錯在這份語料上傷害最大?每一種錯分別傷在品質、延遲還是成本?

主教材(Core)

  • LlamaIndex 文件 — Evaluating(Concept、Response Evaluation、Retrieval Evaluation 三節),預估 20 分鐘
  • LlamaIndex 文件 — Cost Analysis(Indices with no LLM calls、Indices with LLM calls、Using MockLLM、Using MockEmbedding 四節),預估 15 分鐘
  • 實作,預估 60 分鐘

搭配(Companion,選讀)

  • LlamaIndex 文件 — Usage Pattern (Retrieval)(Plugging it into RetrieverEvaluator 一節),對照 LlamaIndex 內建的評估器與你自己寫的 evaluate;預估 10 分鐘

讀的時候抓這幾個重點

  • 評估分兩種,量的東西不同。 Evaluating 頁說 Response Evaluation 檢查生成的答案(用 LLM 當評審,看 Correctness、Faithfulness、Context Relevancy、Answer Relevancy 等),Retrieval Evaluation 檢查撈回來的來源跟問題相不相關,用 MRR、hit-rate、precision 這類排名指標。今天的表是後者;前者需要真的 LLM。
  • 先修檢索,再修生成。 檢索沒撈到,生成再好也答不對;檢索撈到了但答錯,才是生成的問題。所以 Day 61–67 一直在量檢索,Day 68 才碰生成。這個順序也是 debug RAG 時的順序。
  • 成本可以在花錢之前估。 Cost Analysis 頁說 LlamaIndex 有 MockLLM 與 MockEmbedding 這類 token 預測器,可以在不真的呼叫模型的情況下,估出建索引與查詢會用多少 token。今天的表用「送進 LLM 的字元數」當成本的代理指標;你可以用 MockLLM 換成 token 數。
  • 這張表只對這份語料成立。 12 題、4 份短文件是一個很小的評估集,有些錯誤在這裡看不出傷害(例如 chunk 太小在 rerank 之後就救回來了)。表的價值不在數字本身,而在你建好了一個「換語料、換設定就能重跑」的實驗台。

實作

建立 day69_report.py,把六種故意做錯跟 baseline 放在同一張表(baseline:chunk 64、有 metadata 與 filter、撈 10 個 rerank 後取 2 個):

from llama_index.core.postprocessor import SentenceTransformerRerank

from lab import build_index, evaluate

reranker = SentenceTransformerRerank(model="cross-encoder/ms-marco-MiniLM-L6-v2", top_n=10)
indexes = {}


def get_index(chunk_size, with_metadata):
    key = (chunk_size, with_metadata)
    if key not in indexes:
        indexes[key] = build_index(chunk_size=chunk_size, chunk_overlap=min(16, chunk_size // 4),
                                   with_metadata=with_metadata)[0]
    return indexes[key]


# (名稱, chunk_size, metadata, filter, rerank, top_k)
CONFIGS = [
    ("baseline",             64, True,  True,  True,  2),
    ("chunk too big",       512, True,  True,  True,  2),
    ("chunk too small",      40, True,  True,  True,  2),
    ("top_k too many",       64, True,  True,  True, 10),
    ("top_k too few",        64, True,  True,  False, 1),
    ("no metadata",          64, False, False, True,  2),
    ("no reranking",         64, True,  True,  False, 2),
]

evaluate(get_index(64, True), top_k=1, reranker=reranker, fetch_k=10)  # 暖機
print("| config | hit | MRR | context chars | ms |")
print("|---|---|---|---|---|")
for name, cs, meta, filt, rr, k in CONFIGS:
    r = evaluate(get_index(cs, meta), top_k=k, use_filter=filt,
                 reranker=reranker if rr else None, fetch_k=max(10, k))
    print(f"| {name} | {r['hit']:.2f} | {r['mrr']:.2f} | {r['ctx_chars']:.0f} | {r['ms']:.1f} |")

執行 python day69_report.py。預期(教材作者實跑結果;警告訊息省略):

| config | hit | MRR | context chars | ms |
|---|---|---|---|---|
| baseline | 1.00 | 1.00 | 391 | 23.5 |
| chunk too big | 1.00 | 1.00 | 1628 | 27.7 |
| chunk too small | 1.00 | 1.00 | 200 | 20.5 |
| top_k too many | 1.00 | 1.00 | 1647 | 13.6 |
| top_k too few | 0.92 | 0.92 | 183 | 4.0 |
| no metadata | 0.83 | 0.75 | 541 | 15.3 |
| no reranking | 1.00 | 0.96 | 385 | 4.1 |

把這張表貼進筆記,每一列旁邊寫一句「它傷在哪」(品質/成本/延遲/這份語料看不出來),並回答:在這份語料上傷害最大的是哪一種錯?然後換一份你自己的語料(例如你工作上的一份內部文件,切成 3–5 個 Markdown 檔),在 corpus.py 裡改 DOCS 並至少寫 6 題 EVAL,重跑這張表,記錄哪幾列的結論變了。

過關標準

  • 能回答:Retrieval Evaluation 與 Response Evaluation 各量什麼?今天的表屬於哪一種?
  • 能回答:「chunk too small」在 Day 64 傷到 hit,在今天的表裡卻沒有,差別在哪一層?
  • 產出:兩張對照表(Relay 語料、你自己的語料),每一列都標註傷在哪裡,以及「哪些結論換了語料就變了」的筆記

Day 70 — Project 2:Production RAG

今天要回答的問題

把這個 Phase 的每一層組成一個能重複執行的系統:資料只需要 ingest 一次,查詢時能回報品質、延遲與成本。這個系統還缺什麼才能放上線?

主教材(Core)

  • LlamaIndex 文件 — Ingestion Pipeline(Usage Pattern、Connecting to Vector Databases、Calculating embeddings in a pipeline、Document Management 四節),預估 20 分鐘
  • LlamaIndex 文件 — Storing(Persisting to disk、Using Vector Stores、Inserting Documents or Nodes 三節),預估 10 分鐘
  • 實作,預估 80 分鐘

搭配(Companion,選讀)

  • LlamaIndex 文件 — Using VectorStoreIndex(Handling Document Updates 一節,以及 insert_batch_size 的說明),了解文件更新與大量寫入時的批次設定;預估 10 分鐘

讀的時候抓這幾個重點

  • Ingestion 要能重跑、而且重跑不貴。 Ingestion Pipeline 頁說 pipeline 接上 vector store 時,embedding 必須是 transformation 之一;每個(node, transformation)組合會被雜湊並快取;接上 docstore 之後,會用文件 id 加內容雜湊判斷:id 一樣但內容變了才重新處理並 upsert,沒變就跳過。這跟 Day 63 的 upsert 冪等是同一條線:穩定的 id 是能安全重跑的前提。但要注意:今天的程式雖然把檔名當成 Document id,卻沒有接 docstore,切出來的 node id 每次都是新的——它能安全重跑,靠的是「collection 已存在就整段跳過」這個粗糙的判斷,不是去重。實作的最後一步會讓你親眼看到差別。
  • 儲存讓查詢與 ingestion 分開。 Storing 頁說索引預設只在記憶體裡;接上向量資料庫之後,可以用 VectorStoreIndex.from_vector_store(...) 直接從已存的 embedding 建索引、不用重新讀文件。今天的程式第二次執行會跳過 ingestion,就是這個效果。
  • 驗收要的是一份報告,不是一個能回答的 demo。 Project 2 要展示 retrieval quality、chunking 對照、latency、cost、evaluation。今天的程式在結尾印出一份報告:答對率、引用通過率、平均 prompt 長度、每一階段的 p50 與最大延遲。chunking 對照與完整的錯誤對照表則來自 Day 64 與 Day 69。

實作

建立 project2.py。它把 ingestion 存到磁碟(./qdrant_db),查詢時依序做 filter、檢索 10 個、rerank 取 3 個、組 prompt、生成、檢查引用,並對每個階段計時:

"""Project 2:Production RAG
Documents → ingestion → embedding → retrieval → reranking → LLM → citations
"""
import statistics
import time

from llama_index.core import Document, Settings, VectorStoreIndex
from llama_index.core.ingestion import IngestionPipeline
from llama_index.core.node_parser import SentenceSplitter
from llama_index.core.postprocessor import SentenceTransformerRerank
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.vector_stores.qdrant import QdrantVectorStore
from qdrant_client import QdrantClient

from cite import build_prompt, check_citations, fake_llm
from corpus import DOCS, EVAL
from lab import version_filter

COLLECTION = "relay_prod"
Settings.embed_model = HuggingFaceEmbedding(model_name="sentence-transformers/all-MiniLM-L6-v2")
Settings.llm = None

client = QdrantClient(path="./qdrant_db")  # 存到磁碟,第二次執行不用重算 embedding
store = QdrantVectorStore(client=client, collection_name=COLLECTION)


def ingest():
    docs = [Document(text=text, metadata={"file_name": name, "version": version}, id_=name)
            for name, (version, text) in DOCS.items()]
    pipeline = IngestionPipeline(
        transformations=[SentenceSplitter(chunk_size=64, chunk_overlap=16), Settings.embed_model],
        vector_store=store,
    )
    t0 = time.perf_counter()
    nodes = pipeline.run(documents=docs)
    return len(nodes), (time.perf_counter() - t0) * 1000


if client.collection_exists(COLLECTION):
    print("ingestion: skipped (collection already on disk)")
else:
    n, ms = ingest()
    print(f"ingestion: {n} nodes in {ms:.0f} ms")

index = VectorStoreIndex.from_vector_store(store)
reranker = SentenceTransformerRerank(model="cross-encoder/ms-marco-MiniLM-L6-v2", top_n=3)


def ask(question, version=None):
    timing = {}
    t0 = time.perf_counter()
    nodes = index.as_retriever(similarity_top_k=10, filters=version_filter(version)).retrieve(question)
    timing["retrieve"] = (time.perf_counter() - t0) * 1000

    t0 = time.perf_counter()
    nodes = reranker.postprocess_nodes(nodes, query_str=question)
    timing["rerank"] = (time.perf_counter() - t0) * 1000

    sources = [n.node.get_content() for n in nodes]
    prompt = build_prompt(question, sources)
    t0 = time.perf_counter()
    answer = fake_llm(question, sources)
    timing["generate"] = (time.perf_counter() - t0) * 1000
    return {"answer": answer, "sources": sources, "citation": check_citations(answer, sources),
            "prompt_chars": len(prompt), "timing": timing}


ask(EVAL[0]["q"], EVAL[0]["version"])  # 暖機
results = []
for item in EVAL:
    r = ask(item["q"], item["version"])
    r["correct"] = item["answer"] in r["answer"]
    results.append(r)

r = results[1]
print("\nQ:", EVAL[1]["q"])
print("A:", r["answer"], "|", r["citation"])

n = len(results)
print("\n=== report ===")
print(f"questions          : {n}")
print(f"answer correct     : {sum(r['correct'] for r in results)}/{n}")
print(f"citation OK        : {sum(r['citation'] == 'OK' for r in results)}/{n}")
print(f"avg prompt chars   : {statistics.mean(r['prompt_chars'] for r in results):.0f}")
for stage in ("retrieve", "rerank", "generate"):
    xs = [r["timing"][stage] for r in results]
    print(f"{stage:<9} ms p50/max: {statistics.median(xs):.1f} / {max(xs):.1f}")

client.close()

連續執行 python project2.py 兩次。預期(教材作者實跑結果;毫秒數會隨機器不同):

第一次:

ingestion: 25 nodes in 427 ms

Q: How long are messages retained in Relay v2?
A: Unacknowledged and acknowledged messages are both kept for 14 days, after which a background job deletes them. [1] | OK

=== report ===
questions          : 12
answer correct     : 12/12
citation OK        : 12/12
avg prompt chars   : 797
retrieve  ms p50/max: 5.5 / 6.8
rerank    ms p50/max: 12.4 / 17.8
generate  ms p50/max: 9.2 / 11.5

第二次的第一行變成 ingestion: skipped (collection already on disk),其餘結果相同(毫秒數略有差異)。

接著寫一份一頁的 Project 2 報告(p07/REPORT.md),用下面這張表當骨架,每一格都要指向一個你跑過的輸出:

驗收項目證據來自你的數字或結論
Documents → ingestion → embedding → retrieval → reranking → LLM → citationsproject2.py
Retrieval quality(hit、MRR)Day 69 的表
Chunking 對照Day 64 的輸出
Latency(每階段 p50/max)project2.py 的報告
Cost(每題送進 LLM 的量)project2.py 的 avg prompt chars,換算成 token
Evaluation(答對率、引用通過率)project2.py 的報告

再做一個破壞實驗:刪掉 qdrant_db 資料夾,把 if client.collection_exists(COLLECTION): 改成 if False:,連續執行兩次,每次執行完用 QdrantClient(path="./qdrant_db").count("relay_prod") 看 point 數(教材作者實測:第一次 25,第二次 50——同樣的內容存了兩份)。讀 Ingestion Pipeline 頁的 Document Management 一節,在報告裡寫下要怎麼改才能「內容沒變就跳過、內容變了就更新」(這個改法教材作者沒有實作)。

最後在報告末尾寫「上線前還缺什麼」,至少三點,每點一句話說明為什麼缺它會出事(提示:替身 LLM、filter 的 version 從哪來、文件更新時舊 chunk 怎麼辦)。

過關標準

  • 能回答:為什麼第二次執行可以跳過 ingestion?拿掉這個判斷之後,point 數為什麼會翻倍?Ingestion Pipeline 頁的 Document Management 一節提供了什麼解法?
  • 能回答:報告裡哪一個階段最慢?如果流量變成 100 倍,你會先優化哪一段、為什麼?
  • 產出:project2.py(可重複執行、第二次跳過 ingestion)、兩次執行的輸出,以及填完驗收表與「上線前還缺什麼」的 REPORT.md

Deep Dive(選讀)

  • 這個 Phase 的「Memory」:RAG 是讓模型讀文件,memory 是讓 agent 記住對話,兩者常共用同一套向量檢索。讀 LlamaIndex 的 Memory(Concept、Customizing Memory 兩節):短期記憶是「放得進 token 上限的最近幾則訊息」,超過比例的舊訊息會被沖進長期記憶,而長期記憶的 VectorMemoryBlock 就是把訊息存進向量資料庫再檢索——也就是你這 10 天做的事。Phase 08 的 agent 會用到。