跳轉到

解構 RAG 架構:從向量空間到圖形拓撲

文章資訊

作者:RichaGSingh  日期:2026-06-13

原文標題:Demystifying RAG Architectures: From Vector Space to Graph Topologies

Medium 原連結https://medium.com/@richagoel5842/demystifying-rag-architectures-from-vector-space-to-graph-topologies-35396b74de33

🎧 摘要語音

📝 重點摘要

TL;DR

程式碼類 RAG 應用,純向量搜尋會漏掉跨檔依賴,混合向量—圖架構才是生產標準。

核心問題

AI 程式助理在重構多檔案程式庫時容易產生「幻覺」——傳錯型別、漏掉 import,導致建置失敗。作者主張這並非提示工程問題,而是檢索架構問題。純向量資料庫只懂語意相似度,不理解檔案間的真實依賴關係,因此需要更進階的架構。

關鍵發現 / 數據

  • 向量搜尋用 Cosine 而非 L2:源碼檔案長度差異大(如 15 行工具函式 vs 150 行伺服器檔),歐氏距離會依 token 數懲罰長檔,餘弦只看夾角故不受檔長影響。
  • 斷裂連結失效:向量檢索能撈到呼叫端 Chunk 1(傳 string),卻漏掉位於別目錄、要求 integer 的 helper Chunk 2,產生靜默執行期錯誤。
  • 「Schema Drift」陳舊資訊:向量庫無法判斷兩個被檢回的檔是否已彼此失步。
  • 檢索策略 K=50 → K=5:"retrieve more, rerank fewer",向量先撈 50 候選,圖擴展鄰接節點,再用 Cross-Encoder 重排留前 5 塞進 token 預算。

方法亮點

  • AST 結構化切塊:用 Tree-sitter 等增量解析器依括號/縮排切分,避免從函式中間切斷破壞語法。
  • Entity-Resolved Knowledge Graph (ERKG):用確定性 AST 解析 import 路徑建邊,避免 auth.jsauthz.js 因正規化過度而「實體碰撞」合併。
  • 混合管線:向量當「模糊前門」處理人類口語查詢找入口節點,圖庫沿 IMPORTS/QUERIES 邊擴展 2-3 跳拉出依賴。
  • 圖維護:commit 後先刪舊出邊再重算,主動剪除過期 import 防止陳舊映射。

對我的研究有用嗎?

有參考價值的是把 GraphRAG 定位成「結構精度補充向量語意覆蓋」的框架,以及 Karpathy 的 CPU/RAM/SSD 記憶體分頁類比,可作為 context engineering 的直覺模型。ERKG 與「確定性建邊 vs 模糊文字匹配」的對比,對知識圖譜抽取階段的雜訊控制有啟發;圖維護的邊剪除策略也呼應 KG 動態更新議題。

評語

入門科普佳、類比清晰,但屬經驗性敘述、無真實 benchmark 或實驗數據,所有「結論」皆為個人專案心得,非嚴謹研究——可快速瀏覽概念,不值深讀。


🌐 中英對照

Author: RichaGSingh
作者:RichaGSingh

Published:
發布日期

Source: https://medium.com/@richagoel5842/demystifying-rag-architectures-from-vector-space-to-graph-topologies-35396b74de33
來源:https://medium.com/@richagoel5842/demystifying-rag-architectures-from-vector-space-to-graph-topologies-35396b74de33

Fetched: 2026-06-13T00:31:10.213028
擷取時間:2026-06-13T00:31:10.213028


Demystifying RAG Architectures: From Vector Space to Graph Topologies / 揭開 RAG 架構的神秘面紗:從向量空間到圖拓撲

When building LLM-driven tools for production environments where mistakes cause immediate outages, standard prompting fails. If an AI coding assistant hallucinates a variable property, passes a wrong argument type, or misses a critical file import while refactoring a codebase, the entire build breaks.

當你為「一旦出錯就會立刻造成服務中斷」的生產環境 (production environment) 打造大型語言模型 (LLM) 驅動的工具時,標準的提示 (prompting) 方式並不可靠。如果一個 AI 程式撰寫助手在重構程式碼庫 (codebase) 時,幻覺 (hallucinate) 出一個不存在的變數屬性、傳入錯誤的引數型別,或漏掉一個關鍵的檔案匯入,整個建置 (build) 就會崩潰。

To solve this, we use Retrieval-Augmented Generation (RAG) to ground the AI model in real, verified source code. However, as I have been diving into this for my own project, I have realized that not all RAG architectures are created equal. A basic vector database works well for searching flat text documents, but highly interconnected systems like codebases require a more advanced architectural design.

為了解決這個問題,我們使用檢索增強生成 (Retrieval-Augmented Generation, RAG) 技術,讓 AI 模型立足於真實、已驗證的原始碼之上。然而,當我為了自己的專案深入鑽研這個領域時,我意識到並非所有 RAG 架構都是同等的。一個基本的向量資料庫 (vector database) 很適合用來搜尋扁平的文字文件,但像程式碼庫這種高度互相連結的系統,則需要更進階的架構設計。

As I continue my work utilising RAG, let’s together explore different types of RAG available and their mechanics. We will look at how I came to understand the math behind vector search, see where standard vector search breaks down, and explore the hybrid vector-graph architecture that looks to be the real production standard.

隨著我持續使用 RAG 進行工作,讓我們一起探索目前可用的各種 RAG 類型及其運作機制。我們將看看我是如何理解向量搜尋 (vector search) 背後的數學原理、檢視標準向量搜尋在哪裡會失效,並探討看似真正成為生產標準的「向量—圖混合架構 (hybrid vector-graph architecture)」。

To keep things practical, I am going to anchor all these concepts around a single use case I have been studying -how a generalized AI coding assistant reads, navigates, and refactors a multi-file software codebase.

為了讓內容貼近實務,我會將所有這些概念都圍繞在我一直在研究的單一使用案例上——一個通用型 AI 程式撰寫助手是如何閱讀、瀏覽並重構一個多檔案的軟體程式碼庫的。

The RAG Taxonomy: Three Ways to Store Knowledge / RAG 的分類法:儲存知識的三種方式

To build a reliable AI coding assistant, the data storage and retrieval architecture must match the structure of the codebase itself.

要打造一個可靠的 AI 程式撰寫助手,資料的儲存與檢索架構必須與程式碼庫本身的結構相匹配。

Press enter or click to view image in full size

按 Enter 或點擊以檢視完整尺寸的圖片

Diagram 1: RAG Ingestion Pathways.

圖 1:RAG 資料攝取 (ingestion) 路徑。

Vector-Based RAG (The Geometric Approach) / 基於向量的 RAG(幾何學方法)

Vector RAG breaks code documents into small text chunks, converts those chunks into numerical vectors called embeddings, and stores them in a vector database. When a developer asks a question or highlights a line of code, the system fetches the top $K$ nearest chunks based purely on semantic proximity.

向量 RAG 會將程式碼文件拆分成一個個小的文字區塊 (chunk),把這些區塊轉換成稱為嵌入 (embedding) 的數值向量,並將它們儲存在向量資料庫中。當開發者提出問題或標示出某一行程式碼時,系統會純粹根據語意上的鄰近程度,擷取出最相近的前 $K$ 個區塊。

When searching across source code, cosine similarity is highly favored over Euclidean distance (L2). Because source files vary drastically in length, such as a minimal utility function of 15 lines versus a hardened production server file of 150 lines, Euclidean distance incorrectly penalizes larger files based on token count. Cosine similarity resolves this by measuring only the angle θ between vectors, ensuring files with identical programming logic and keyword characteristics remain grouped together regardless of file size.

在跨原始碼進行搜尋時,餘弦相似度 (cosine similarity) 遠比歐幾里得距離 (Euclidean distance,又稱 L2) 更受青睞。因為原始檔的長度差異極大,例如一個僅 15 行的精簡工具函式,相對於一個經過強化、有 150 行的生產級伺服器檔案,歐幾里得距離會基於 token 數量而錯誤地懲罰較大的檔案。餘弦相似度透過只測量向量之間的夾角 θ 來解決這個問題,確保具有相同程式邏輯與關鍵字特徵的檔案,無論檔案大小如何,都能被歸為一組。

The Coding Assistant Example: Imagine you have hundreds of helper functions and system utilities. Vector RAG searches across all utility files to find the specific function signatures that match the semantic intent of your coding prompt.

程式撰寫助手範例:想像你有數百個輔助函式 (helper function) 與系統工具程式。向量 RAG 會跨所有工具檔案進行搜尋,找出與你的程式撰寫提示在語意意圖上相符的特定函式簽章 (function signature)。

The Best Chunking Strategy: For code files, standard paragraph or token-size splitting can cut a class or function block right in the middle, destroying the syntax. Instead, you must use structural splitting based on indentations, brackets, or Abstract Syntax Tree (AST) parsing (using industry-standard incremental parsers like Tree-sitter) to keep related structural blocks completely intact.

最佳的分塊 (chunking) 策略:對於程式碼檔案,標準的段落或固定 token 大小的切分方式,可能會從正中間切斷一個類別 (class) 或函式區塊,破壞其語法。取而代之,你必須使用基於縮排、括號,或抽象語法樹 (Abstract Syntax Tree, AST) 解析的結構化切分(使用像 Tree-sitter 這種業界標準的增量式解析器),來讓相關的結構區塊保持完整無缺。

Graph-Based RAG (The Network Approach) / 基於圖的 RAG(網路方法)

GraphRAG organizes information as a network of discrete entities (nodes) and the explicit relationships that connect them (edges). Instead of estimating how files relate based on mathematical proximity, it maps the actual imports, call graphs, and inheritance lines.

GraphRAG(圖 RAG)將資訊組織成一個網路,由離散的實體(節點 (node))以及連結它們的明確關係(邊 (edge))所構成。它不是基於數學上的鄰近程度去「估計」檔案之間的關聯,而是直接對應出實際的匯入關係、呼叫圖 (call graph) 與繼承關係。

The Coding Assistant Example: Think of a standard web backend. You have an API Route file, a User Controller, and a Database Client. GraphRAG turns each of these files, classes, or functions into a node and draws direct lines between them to show exactly how code execution flows.

程式撰寫助手範例:想想一個標準的網頁後端。你有一個 API 路由 (API Route) 檔案、一個使用者控制器 (User Controller) 和一個資料庫客戶端 (Database Client)。GraphRAG 會把這些檔案、類別或函式各自轉換成一個節點,並在它們之間畫出直接的連線,以精確地顯示程式碼的執行流程是如何流動的。

Hybrid RAG (The Combined Approach) / 混合式 RAG(結合方法)

Hybrid systems use vector search to find the right starting point in a massive repository, and then use a graph network to pull all the connected components. This is the architecture most teams end up building for complex production environments.

混合式系統使用向量搜尋在龐大的儲存庫 (repository) 中找到正確的起始點,接著再使用圖網路把所有相連的元件 (connected component) 拉取出來。這正是大多數團隊最終為複雜的生產環境所建構的架構。

Where Standard Vector Space Fails / 標準向量空間在哪裡會失效

While Cosine Similarity is excellent for matching individual code patterns, standard vector search hits a wall when dealing with codebases that depend on multiple files. Vector databases do not understand relationships between separate chunks.

雖然餘弦相似度非常擅長比對個別的程式碼模式,但標準的向量搜尋在處理「依賴多個檔案」的程式碼庫時就會撞牆。向量資料庫並不理解各個獨立區塊之間的關係。

Press enter or click to view image in full size

按 Enter 或點擊以檢視完整尺寸的圖片

Diagram 2: Broken connections failure.

圖 2:連結斷裂的失敗情況。

The Failure of Broken Connections / 連結斷裂的失敗

Imagine a developer asks the coding assistant to update an API endpoint. The codebase configuration is split into separate chunks during data ingestion:

想像一位開發者要求程式撰寫助手更新一個 API 端點 (endpoint)。在資料攝取的過程中,程式碼庫的設定被拆分成數個獨立的區塊:

Chunk 1: Describes the API endpoint controller, which calls a backend database helper function getUser(id) passing a string identifier.

區塊 1:描述 API 端點控制器,它會呼叫後端資料庫輔助函式 getUser(id),並傳入一個字串型別的識別碼。

Chunk 2: Describes the database helper module, which strictly validates that id must be an integer, throwing a fatal runtime error otherwise.

區塊 2:描述資料庫輔助模組,它嚴格驗證 id 必須是整數,否則就會拋出致命的執行期錯誤 (runtime error)。

If your vector database searches for the endpoint logic, it might pull Chunk 1 because the text matches the user’s prompt perfectly. However, it completely misses Chunk 2 because the database helper definition sits in a different directory. The LLM modifies the endpoint code, maintaining the string variable argument and directly violating the database module type checks.

如果你的向量資料庫去搜尋端點邏輯,它可能會擷取出區塊 1,因為其文字與使用者的提示完美匹配。然而,它完全錯過了區塊 2,因為資料庫輔助函式的定義位於不同的目錄中。於是 LLM 修改了端點程式碼,卻保留了字串型別的變數引數,直接違反了資料庫模組的型別檢查。

Because standard vector search cannot look outside its own retrieved chunks to check dependencies, it introduces silent, critical runtime compilation errors.

由於標準向量搜尋無法越過它自己所擷取的區塊去檢查相依性 (dependency),它便引入了無聲卻嚴重的執行期/編譯錯誤。

The Problem of Stale Information (Schema Drift) / 過時資訊的問題(綱要漂移)

As codebases change, files are updated at different times. If you modify a database schema property but the api controller files are still running on older import logic, the two systems drift. A vector database only knows if individual chunks match a search query. It has no way to tell you that two retrieved code files are now completely out of sync with each other.

隨著程式碼庫的變動,檔案會在不同的時間點被更新。如果你修改了某個資料庫綱要 (schema) 屬性,但 API 控制器檔案仍在使用舊的匯入邏輯運作,這兩個系統就會發生漂移。向量資料庫只知道個別區塊是否與搜尋查詢相符,它無法告訴你兩個被擷取出來的程式碼檔案此刻已經完全彼此不同步了。

These two failure modes, broken cross-file dependencies and schema drift, are exactly what push production teams beyond pure vector search and toward a graph-aware architecture.

這兩種失敗模式——跨檔案相依性斷裂與綱要漂移 (schema drift)——正是促使生產團隊跳脫純向量搜尋、轉向「具備圖意識 (graph-aware)」架構的原因。

Evolving to GraphRAG for Interconnected Data / 為互連資料演進到 GraphRAG

To build a tool that inherently understands how components fit together, you must move from flat text lists to a connected graph network of your codebase.

要打造一個天生就能理解各元件如何彼此契合的工具,你必須從扁平的文字清單,轉移到把程式碼庫組織成相互連結的圖網路。

Press enter or click to view image in full size

按 Enter 或點擊以檢視完整尺寸的圖片

Diagram 3: Dependency topology.

圖 3:相依性拓撲 (topology)。

How to Build a Knowledge Graph for a Codebase

如何為程式碼庫建立知識圖譜 (Knowledge Graph)

Parse the Data: Run your code files through an AST parser to isolate class definitions, function calls, and module exports.

解析資料:將你的程式碼檔案透過 AST 解析器處理,以分離出類別定義、函式呼叫與模組匯出。

Create Nodes: Save each source file or logical module as a node inside a graph database like Neo4j.

建立節點:把每個原始檔或邏輯模組儲存成一個節點,放進像 Neo4j 這樣的圖資料庫 (graph database) 中。

Connect the Dots: Write parser scripts to scan for imports. If your API controller imports a database client helper, draw a direct line labeled IMPORTS between those two nodes.

連點成線:撰寫解析器腳本來掃描匯入關係。如果你的 API 控制器匯入了一個資料庫客戶端輔助函式,就在這兩個節點之間畫一條標記為 IMPORTS 的直接連線。

The Danger of Entity Collision (A Critical Warning)

實體碰撞的危險(一則關鍵警告)

As I was researching graph databases, I discovered a major risk when building a graph index, a phenomenon called Entity Collision. If we normalize terms too aggressively (such as basic string matching, stemming, or lowercasing), we risk merging completely distinct code concepts.

在我研究圖資料庫的過程中,我發現建立圖索引時有一個重大風險,這是一種稱為實體碰撞 (Entity Collision) 的現象。如果我們把詞彙正規化 (normalize) 得太過激進(例如基本的字串比對、字幹還原 (stemming) 或轉小寫),我們就有可能把完全不同的程式碼概念合併在一起。

For example, an authentication controller named auth.js and an authorization helper named authz.js could easily collapse into the same entity node during basic normalization. The graph database would draw incorrect dependency lines between them, causing our AI to generate insecure module routing or broken code logic.

舉例來說,一個名為 auth.js 的身分驗證 (authentication) 控制器,與一個名為 authz.js 的授權 (authorization) 輔助函式,在基本正規化的過程中很容易就被收縮成同一個實體節點。圖資料庫會在它們之間畫出錯誤的相依性連線,導致我們的 AI 產生不安全的模組路由,或是錯誤的程式碼邏輯。

To mitigate this, I learned that production systems build Entity-Resolved Knowledge Graphs (ERKGs). For application code, we shouldn’t use fuzzy text matching to construct edges. Instead, we must use deterministic AST parsers to extract strict import pathways and namespaces to guarantee zero connections are built on assumptions.

為了緩解這個問題,我學到生產系統會建構實體解析知識圖譜 (Entity-Resolved Knowledge Graphs, ERKGs)。對於應用程式碼,我們不應該使用模糊的文字比對來建構邊。相反地,我們必須使用具決定性 (deterministic) 的 AST 解析器,去抽取出嚴格的匯入路徑與命名空間 (namespace),以保證沒有任何一條連結是建立在假設之上的。

The Graph Retrieval Loop in Action / 圖檢索迴圈的實際運作

When a developer prompts the system to modify a specific API controller, the retrieval process changes: The system performs a quick search to find the exact file node the user is targeting.

當開發者提示系統去修改某個特定的 API 控制器時,檢索流程就會改變:系統會執行一次快速搜尋,找出使用者所鎖定的確切檔案節點。

The engine follows the connected IMPORTS and QUERIES lines to pull every related code node within two or three steps.

引擎接著沿著相連的 IMPORTS 與 QUERIES 連線,在兩到三步的範圍內拉取出每一個相關的程式碼節點。

The system packages the target controller code along with its connected class definitions and schemas into the prompt context.

系統把目標控制器的程式碼,連同其相連的類別定義與綱要,一起打包進提示的上下文 (context) 中。

This keeps your context perfectly aligned. The LLM receives the controller code and the strict database parameters at the exact same moment, preventing runtime conflicts.

這能讓你的上下文保持完美對齊。LLM 在完全相同的時刻收到控制器程式碼與嚴格的資料庫參數,從而防止執行期衝突。

The Architecture Most Teams End Up Shipping: Hybrid Vector-Graph / 大多數團隊最終出貨的架構:向量—圖混合式

While comparing vector and graph databases is helpful, as I dug deeper, I realized that real-world teams running these tools rarely choose just one.

雖然比較向量資料庫與圖資料庫很有幫助,但隨著我深入挖掘,我意識到實際在運行這些工具的團隊,很少只選擇其中一種。

Pure graph systems have a major weakness: If a developer types a prompt using informal language or description (like “fix the login route”), a rigid graph database struggles to find the right starting point. Vector search is the exact opposite: It is incredibly resilient against messy, descriptive human language, but bad at managing complex structures.

純圖系統有一個重大弱點:如果開發者用非正式的語言或描述來輸入提示(例如「修一下登入路由」),一個僵硬的圖資料庫會很難找到正確的起始點。向量搜尋則恰恰相反:它對於雜亂、描述性的人類語言具有極強的韌性,但卻不擅長管理複雜的結構。

Production systems combine both into a Hybrid Vector-Graph architecture.

生產系統會把兩者結合成一個「向量—圖混合架構」。

Press enter or click to view image in full size

按 Enter 或點擊以檢視完整尺寸的圖片

Diagram 4 — Hybrid Pipeline

圖 4 — 混合式管線 (pipeline)

Why Vector Search is the Best Front Door / 為什麼向量搜尋是最佳的「大門」

Developers rarely use perfect, official code class names when typing prompts. They use abbreviations or write quick descriptions of the problem they are experiencing.

開發者在輸入提示時,很少會使用完美、官方的程式碼類別名稱。他們會使用縮寫,或快速寫下他們所遇到問題的描述。

A vector database acts as a highly forgiving front door. It handles the messy, human aspect of the search to find the single closest matching source file ID. Once that file node ID is discovered, it hands it off to the graph database. The graph database then handles what it does best: instantly pulling every perfectly mapped import, function dependency, and database schema.

向量資料庫扮演了一個高度包容的「大門」角色。它負責處理搜尋中雜亂、屬於人類的那一面,找出單一最相符的原始檔 ID。一旦那個檔案節點 ID 被找到,它就把它交接給圖資料庫。接著圖資料庫負責它最擅長的事:瞬間拉取出每一個被完美對應的匯入關係、函式相依性與資料庫綱要。

Keeping the LLM Grounded: Token Budgets and Rerankers / 讓 LLM 立足於事實:Token 預算與重排序器

While researching how to keep the LLM focused, I came across a great mental model from Andrej Karpathy: Think of the LLM as the CPU, and the context window as RAM. In this analogy, our raw storage (like the vector database) is the solid-state drive (SSD).

在研究如何讓 LLM 保持專注時,我看到了一個來自 Andrej Karpathy 的絕佳心智模型:把 LLM 想成 CPU,把上下文視窗 (context window) 想成 RAM。在這個類比中,我們的原始儲存空間(例如向量資料庫)就是固態硬碟 (SSD)。

This helped me understand why we cannot simply dump our entire codebase into the context window. It is too slow, expensive, and causes the model to lose track of details in the middle of long prompts. Instead, I realized we need to design a sort of active virtual memory paging manager for the LLM context.

這幫助我理解了為什麼我們不能單純地把整個程式碼庫一股腦地塞進上下文視窗。那樣太慢、太昂貴,而且會導致模型在冗長提示的中段遺失對細節的掌握。取而代之,我意識到我們需要為 LLM 的上下文設計一種主動式的虛擬記憶體分頁管理器 (paging manager)。

In my project, I am trying to apply a “retrieve more, rerank fewer” strategy to page-fault contiguous blocks of code context on demand:

在我的專案中,我正試著套用一種 「檢索更多、重排序更少 (retrieve more, rerank fewer)」 的策略,以便依需求對連續的程式碼上下文區塊進行分頁錯失 (page-fault) 處理:

The L2 Cache Directory: The vector index acts as our high-speed directory, fetching a broad pool of candidate files (e.g. K = 50). I found that vector embeddings are excellent at broad semantic coverage but lack structural precision.

L2 快取目錄:向量索引扮演我們的高速目錄角色,擷取出一個範圍廣泛的候選檔案集合(例如 K = 50)。我發現向量嵌入非常擅長廣泛的語意涵蓋,但缺乏結構上的精準度。

The Contiguous Prefetch: The system then queries the graph database to traverse contiguous edges around those 50 nodes. It pre-fetches adjacent modules (such as imported helpers, models, and type definitions) that are structurally connected to our initial candidates.

連續預取 (Contiguous Prefetch):系統接著查詢圖資料庫,去走訪那 50 個節點周圍的連續邊。它會預先取出與我們初始候選項目在結構上相連的鄰近模組(例如被匯入的輔助函式、模型 (model) 與型別定義)。

The Memory Management Unit (MMU): A lightweight, localized Cross-Encoder (Reranker) scores the expanded context pool directly against the query. Unlike the vector index, which encodes the query and each document separately, a cross-encoder scores them together in a single pass, giving it much higher precision for final ranking. It keeps only the absolute top results (e.g. K = 5) to fit cleanly inside our strict LLM token budget, discarding the rest before generation.

記憶體管理單元 (Memory Management Unit, MMU):一個輕量、在地化的交叉編碼器 (Cross-Encoder,即重排序器 Reranker),會直接針對查詢為這個被擴展的上下文集合評分。不同於向量索引是分別對查詢與每份文件進行編碼,交叉編碼器是在單次處理中把它們一起評分,因此在最終排名上具有高得多的精準度。它只保留絕對頂尖的結果(例如 K = 5),以便乾淨俐落地塞進我們嚴格的 LLM token 預算內,並在生成之前捨棄其餘部分。

The Real Challenge: Hydrating and Maintaining the Graph DB / 真正的挑戰:填充與維護圖資料庫

The hardest part of GraphRAG is not querying the data-It is maintaining the graph over time as engineers push commits and code structures mutate. To solve this without causing schema drift, production ingestion pipelines must implement automated reconciliation layers that parse structural relations, update node states, and actively prune deprecated import edges.

GraphRAG 最困難的部分不是查詢資料——而是隨著工程師推送提交 (commit)、程式碼結構不斷變動,去長期維護這張圖。為了在解決這個問題的同時不造成綱要漂移,生產級的資料攝取管線必須實作自動化的協調 (reconciliation) 層,用以解析結構關係、更新節點狀態,並主動修剪掉已被棄用的匯入邊。

By explicitly deleting an existing file’s outgoing edges in your graph database before recalculating and saving its new updates, you ensure that if an engineer deletes an import or refactors a file dependency, the old relationship is pruned instantly. This architectural checkpoint is what prevents the retrieval engine from surfacing stale class mappings.

透過在重新計算並儲存某個既有檔案的新更新「之前」,先明確地刪除它在圖資料庫中的所有外向邊,你就能確保:如果一位工程師刪除了某個匯入,或重構了某個檔案相依性,舊的關係會被立即修剪掉。正是這個架構上的檢查點,防止了檢索引擎浮現出過時的類別對應關係。

5. My Ingestion Selection Matrix / 5. 我的資料攝取選擇矩陣

This is the decision matrix I have put together based on my findings to help choose the right architecture depending on the data complexity:

這是我根據自己的研究發現所整理出的決策矩陣,用以協助依據資料的複雜度來選擇正確的架構:

Flat markdown docs and training manuals / High latency tolerance, general text search / Vector RAG with standard token chunking

扁平的 markdown 文件與訓練手冊 / 高延遲容忍度、一般文字搜尋 / 採用標準 token 分塊的向量 RAG

Independent code files and isolated templates / Zero structural syntax errors within single files / Vector RAG with strict AST-based chunking (Tree-sitter; naive sliding-window chunking breaks syntax and variable scopes)

獨立的程式碼檔案與孤立的範本 / 單一檔案內零結構性語法錯誤 / 採用嚴格 AST 分塊的向量 RAG(Tree-sitter;天真的滑動視窗 (sliding-window) 分塊會破壞語法與變數作用域)

Deeply nested files, multi-file dependencies / Strict validation across multiple files / GraphRAG or Hybrid Vector-Graph with automated dependency tracking

深度巢狀的檔案、多檔案相依性 / 跨多個檔案的嚴格驗證 / 具備自動化相依性追蹤的 GraphRAG 或向量—圖混合式架構

Large-scale mixed corpora: docs, code, configs / High query diversity, latency-sensitive, gradual schema evolution / Hybrid Vector-Graph with versioned nodes and stale edge detection

大規模混合語料庫:文件、程式碼、設定檔 / 高查詢多樣性、對延遲敏感、綱要逐步演進 / 具備版本化節點與過時邊偵測的向量—圖混合式架構

Takeaways / 重點整理

If you are building standard text search tools, sticking with Cosine Similarity seems best to protect search precision from changing file lengths.

如果你正在打造標準的文字搜尋工具,堅持使用餘弦相似度似乎是最好的選擇,能讓搜尋精準度免於受到檔案長度變化的影響。

If your files naturally depend on each other, I learned that writing highly complex prompts to fix broken data chunks is a losing battle. It is much more effective to fix the underlying data pipeline by mapping those relationships explicitly in a graph.

如果你的檔案天生就彼此相依,我學到的是:撰寫高度複雜的提示去修補斷裂的資料區塊,是一場注定失敗的戰役。更有效的做法是修正底層的資料管線,在圖中明確地對應出那些關係。

For enterprise scale, the hybrid approach makes the most sense to me- use Vector Search as your fuzzy search entry point and a Graph Network to handle the rigid, structural expansion.

對於企業級規模,混合式方法對我來說最為合理——使用向量搜尋作為你的模糊搜尋入口,並用圖網路來處理那種嚴格的、結構性的擴展。

Coming back to where we started: the coding assistant that breaks the build because it missed a type contract in a separate database module. That is not a prompting problem. It is a retrieval architecture problem. Geometry helps our AI understand the meaning of a single concept. Graph topology ensures it understands how that concept connects to every other file it depends on, so when the assistant refactors your API controller, it already has the database schema and the type constraints in context before it writes a single line.

回到我們的起點:那個因為漏掉了另一個資料庫模組中的型別契約 (type contract) 而搞壞建置的程式撰寫助手。那不是一個提示的問題,而是一個檢索架構的問題。幾何學幫助我們的 AI 理解單一概念的意義;而圖拓撲則確保它理解那個概念是如何與它所依賴的每一個其他檔案相互連結的。如此一來,當助手在重構你的 API 控制器時,它早在寫下任何一行程式碼之前,就已經把資料庫綱要與型別限制放進了上下文之中。


🔤 關鍵術語

英文 繁中譯名 文章中的脈絡 / 簡短說明
Retrieval-Augmented Generation (RAG) 檢索增強生成 透過檢索真實來源(如已驗證原始碼)為 LLM 提供根據,減少幻覺
GraphRAG 圖譜檢索增強生成 以節點(實體)與邊(關係)構成網路,映射程式碼真實的 import、呼叫圖與繼承關係
Hybrid Vector-Graph 混合向量-圖譜架構 先用向量搜尋找起點,再以圖譜網路拉出所有相連元件;多數正式環境採用
Vector embeddings 向量嵌入 將文字 chunk 轉成的數值向量,擅長廣泛語意覆蓋但缺乏結構精確度
Vector database 向量資料庫 儲存 embeddings、依語意鄰近度檢索 top-K chunk 的資料庫
Cosine similarity 餘弦相似度 只量測向量夾角 θ,避免檔案長度差異造成的懲罰,優於 L2 距離
Euclidean distance (L2) 歐氏距離(L2) 依 token 數量距離計算,會錯誤懲罰較長檔案
Chunking 分塊 將文件切成小文字塊以利嵌入與檢索的策略
Abstract Syntax Tree (AST) parsing 抽象語法樹剖析 依語法結構切分程式碼,避免在類別/函式中途斷裂破壞語法
Tree-sitter Tree-sitter(增量剖析器) 業界標準的增量剖析器,用於 AST-based chunking
Knowledge Graph 知識圖譜 將原始檔/模組存為節點、以 IMPORTS 等邊相連的連通網路
Neo4j Neo4j 文中用來儲存程式碼節點的圖資料庫
Entity Collision 實體碰撞 過度正規化(字串比對、stemming、轉小寫)導致不同概念被合併成同一節點的風險
Entity-Resolved Knowledge Graphs (ERKGs) 實體解析知識圖譜 以確定性 AST 剖析抽取嚴格 import 路徑與命名空間,避免基於假設建立連線
Entity traversal / Graph Retrieval Loop 實體遍歷/圖譜檢索迴圈 沿著 IMPORTS、QUERIES 邊往外走兩三步拉取相關節點
Schema Drift 結構漂移 不同檔案於不同時間更新,導致彼此 import 邏輯與 schema 失同步
Reranker / Cross-Encoder 重排序器/交叉編碼器 將 query 與文件一起編碼評分,精度高於分別編碼的向量索引,用於最終排序
Context window 上下文視窗 Karpathy 類比中 LLM 的「RAM」,容量有限故需檢索式分頁載入
Token budget Token 預算 上下文長度限制,迫使「retrieve more, rerank fewer」只保留最終 top-K
Call graph 呼叫圖 GraphRAG 映射的程式執行關係之一,顯示函式間呼叫流向