Skip to main content
Version: dev

MS-RAG

Multi-Source Enhanced Retrieval-Augmented Generation Framework (MS-RAG)

Principles deep-dive

This page is the framework reference. For the why behind indexing and the agentic retrieval loop, read the design docs first:

Introduction

Large Language Models (LLMs) are powerful, but they can only answer based on the data they were trained on. When users need up-to-date or domain-specific information โ€” such as internal documents, proprietary databases, or the latest reports โ€” LLMs alone fall short.

Retrieval-Augmented Generation (RAG) bridges this gap by retrieving relevant information from external knowledge sources and feeding it as context to the LLM before generating a response. This ensures answers are grounded in real data rather than memorized patterns.

DB-GPT implements a Multi-Source RAG (MS-RAG) framework that goes beyond basic document Q&A. It supports multiple knowledge sources (documents, URLs, databases, knowledge graphs, git repos), multiple indexing strategies, and integrates deeply with the DB-GPT agent and workflow ecosystem. Conversation over a knowledge base is performed by an agentic RAG loop โ€” the agent can rewrite the query, retrieve multiple times, fuse and rerank results, and produce a cited answer โ€” rather than a single retrieve-then-generate pass.

Architecture

Two phases: indexing and conversationโ€‹

INDEXING (runs at document-sync time)              CONVERSATION (runs at chat time)
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Knowledge Source โ†’ Chunking โ†’ Indexes User question
โ”‚ โ”‚
one chunking, โ–ผ
multiple indexes: Agentic RAG loop
โ€ข Vector โ€ข Keyword (query rewrite โ†’ retrieve
โ€ข Knowledge-graph (triplets, multiple times โ†’ fuse +
โ€ข document-paragraph, Markdown rerank โ†’ assemble prompt)
โ€ข heading, code AST) โ”‚
โ–ผ
LLM generates a cited answer

Indexing and conversation are decoupled: indexing happens once when documents are synced; chat only retrieves and never re-indexes.

Indexing pipelineโ€‹

Building an index is an ETL pipeline โ€” one extract + one chunk feeds every enabled index; only the per-index transform and load differ.

Extract                Transform                          Load
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Knowledge.load() โ†’ ChunkManager.split() โ†’ persist into the index store
parse source โ†’ + per-index transform: ยท EmbeddingAssembler โ†’ vector DB
raw text ยท embed (vector) ยท BM25Assembler โ†’ Elasticsearch
ยท tokenize (keyword / BM25) ยท graph store + RepoGraphBuilder
ยท triplets / heading / โ†’ graph store / code graph
code AST (knowledge graph) ยท SummaryAssembler โ†’ vector DB
ยท summary (summary) ยท DBSchemaAssembler โ†’ vector DB
attach metadata (header path,
chunk_id, โ€ฆ) for retrieval/citation
  1. Extract โ€” KnowledgeFactory routes each data source (file / URL / text / git repo) to the right Knowledge implementation, which parses it into raw text (Knowledge.load()).
  2. Transform โ€” ChunkManager.split() chunks the text (by size / page / paragraph / separator / markdown headers) and each index applies its own transform โ€” embedding, BM25 tokenization, LLM triplet / heading / code-AST extraction, summary, or schema embedding โ€” attaching metadata (Header1โ€ฆHeader6, chunk_id, โ€ฆ) that later underpins retrieval and citation.
  3. Load โ€” the per-index driver persists the transformed representation into the index store: EmbeddingAssembler / BM25Assembler / SummaryAssembler / DBSchemaAssembler for the vector / keyword / summary / schema indexes, and the graph store (aload_document) + RepoGraphBuilder for the knowledge-graph and code-graph indexes. (The structural index is not loaded โ€” it is rebuilt at retrieve time from the HeaderN metadata written in this stage.)
  4. Retrieval & Generation โ€” this is the agentic RAG conversation (see next section).

Indexing ETL pipelineโ€‹

BaseAssembler defines the common Extract โ†’ Transform โ†’ Load shape; each index type plugs in its own transform + load. One extract + one chunking feeds every enabled index โ€” only the transform + load differ per index.

Knowledge.load()  โ†’  ChunkManager.split()  โ†’  Assembler.persist()  โ†’  Assembler.as_retriever()
# Extract # Transform # Load # retrieve-time (chat)
IndexTransformLoad driver (implementation)Index store
Vectorchunk โ†’ embeddingEmbeddingAssembler.persist()Vector DB (Chroma, Milvus, โ€ฆ)
Keywordchunk โ†’ BM25 tokensBM25Assembler.persist()Elasticsearch
Knowledge graphchunk โ†’ LLM triplets + document/heading/code-AST graphgraph store aload_document + RepoGraphBuilderTuGraph / Neo4j / Memgraph
Summarychunk โ†’ LLM summary โ†’ embeddingSummaryAssembler.persist()Vector DB
DB schemaschema โ†’ embeddingDBSchemaAssembler.persist()Vector DB
Code graphcode โ†’ tree-sitter ASTRepoGraphBuilder โ†’ CodeGraphStorecode-graph tables
Structural(none โ€” built at retrieve time)retrieve-time DocTreeIndex from HeaderN metadataโ€”

The assemblers are the Load-stage drivers for the vector / keyword / summary / schema indexes. The knowledge-graph and code-graph indexes are built by the graph store and RepoGraphBuilder respectively. All of them consume the same chunks produced in the Extract + Transform stage โ€” which is why chunking quality is the shared foundation under every index.

Indexes

DB-GPT selects which indexes to build per knowledge space via index_methods (a string list). Three index methods are persisted; structural index and code graph are two extra shapes layered on top. All indexes operate on the same chunks, so chunking quality dominates retrieval quality.

Indexindex_methods valueBuilt at sync time?What it gives you
VectorVectorStoreyessemantic similarity ranking via embeddings + cosine
KeywordFullTextyesexact term / BM25 hits
Knowledge-graphKnowledgeGraphyesgraph traversal over entities, document structure, headings, and code
Structural(retrieve-time tree)no โ€” rebuilt at query time from HeaderN chunk metadatamarkdown-header tree / parent-child section navigation
Code graph(layered on KnowledgeGraph; also for GIT_REPO spaces)yesAST of code files as function / class nodes with defines edges
tip

The knowledge-graph index is not one graph but a family: an LLM-extracted triplet graph, a documentโ€“paragraph structure graph, a Markdown heading-hierarchy graph, and (for code/git repos) a code AST graph. They share one build path. Details and the code-graph tree-sitter parsing are in Knowledge Base Indexing Principles.

Conversation: agentic RAG

When a user asks a question over a knowledge base, DB-GPT does not do a single retrieve-then-generate. Instead an agent drives the loop:

question
โ”‚
โ–ผ
query rewrite / multi-query โ—„โ”€โ”€ LLM expands the question for better recall
โ”‚
โ–ผ
retrieve (vector + keyword + graph, possibly repeated) โ—„โ”€โ”€ may iterate: retrieve โ†’ judge โ†’ retrieve again
โ”‚
โ–ผ
fusion + rerank
โ”‚
โ–ผ
assemble context, generate answer with citations

This agentic loop โ€” multi-step retrieval, query rewriting, result fusion and reranking, and citation โ€” is what lets DB-GPT answer complex or multi-part questions that a one-shot RAG cannot. The full flow is documented in Agentic RAG Conversation Principles.

Retrieval strategiesโ€‹

You can configure the retrieve mode in the knowledge base settings:

StrategyDescriptionBackend Required
SemanticVector similarity search using embeddingsVector Store
KeywordBM25-based keyword matchingElasticsearch
HybridCombines vector + keyword search with Reciprocal Rank Fusion (RRF)Vector Store + Elasticsearch
TreeTree-structured retrieval over the markdown heading hierarchyVector Store

Query enhancementโ€‹

Beyond raw retrieval, the agentic loop provides advanced query processing:

  • Query Rewrite โ€” Uses an LLM to expand and rephrase the original query into multiple search queries for better recall, and to decide whether another retrieval round is needed.
  • Reranking โ€” After retrieval, a reranker re-scores and re-orders the results for higher precision before they enter the prompt.

Supported Rerankersโ€‹

RerankerTypeDescription
CrossEncoderRankerLocalUses sentence-transformers CrossEncoder models
QwenRerankEmbeddingsLocalQwen3-Reranker via transformers
OpenAPIRerankEmbeddingsAPICompatible with OpenAI-style rerank APIs
RRFRankerAlgorithmReciprocal Rank Fusion for merging multi-source results
DefaultRankerAlgorithmSimple score-based sorting

Knowledge Sources

DB-GPT supports loading knowledge from multiple source types. In the Web UI, you can select a datasource type when uploading:

Datasource Typesโ€‹

TypeDescriptionExample
DocumentUpload files in various formatsPDF, Word, Excel, CSV, Markdown, PowerPoint, TXT, HTML, JSON, ZIP
URLFetch and index web page contentAny accessible HTTP/HTTPS URL
TextDirectly input raw textPaste text content in the UI
YuqueImport from Yuque documentation platformYuque document links
Git RepoClone a code repository and index it as a code graphA GitHub/GitLab repo URL

Supported Document Formatsโ€‹

FormatExtensionKnowledge Class
PDF.pdfPDFKnowledge
CSV.csvCSVKnowledge
Markdown.mdMarkdownKnowledge
Word (docx).docxDocxKnowledge
Word (legacy).docWord97DocKnowledge
Excel.xlsxExcelKnowledge
PowerPoint.pptxPPTXKnowledge
Plain Text.txtTXTKnowledge
HTML.htmlHTMLKnowledge
JSON.jsonJSONKnowledge
Code.py .java .js .ts .go .rs .c .cpp โ€ฆCodeFileKnowledge (parsed with tree-sitter into the code graph)

Storage Types

When creating a knowledge base, you choose which index store(s) to use โ€” one or more can be enabled together and are complementary:

Storage Typeindex_methodsDescriptionBest For
Vector StoreVectorStoreStores document embeddings for semantic similarity searchGeneral-purpose document Q&A
Knowledge GraphKnowledgeGraphBuilds the graph family (LLM triplets + document/heading/code structure) for relational retrievalDomain knowledge with entity relationships, code, structured docs
Full TextFullTextFull-text/BM25 index for keyword-based retrievalExact term matching and keyword search

Vector Store Backendsโ€‹

BackendDescriptionInstall Extra
ChromaDBDefault embedded vector database, zero setupstorage_chromadb
MilvusDistributed vector database for production scalestorage_milvus
PGVectorPostgreSQL extension for vector operationsstorage_pgvector
ValkeyHigh-performance in-memory vector store with HNSW/FLAT indexingstorage_valkey
WeaviateCloud-native vector search enginestorage_weaviate
ElasticsearchFull-text + vector hybrid searchstorage_elasticsearch
OceanBaseCloud-native distributed databasestorage_oceanbase

Knowledge Graph Backendsโ€‹

BackendDescription
TuGraphHigh-performance graph database by Ant Group
Neo4jPopular open-source graph database
MemgraphIn-memory graph database for low-latency queries

Full-Text Backendsโ€‹

BackendDescription
ElasticsearchIndustry-standard full-text search engine
OpenSearchAWS-managed search and analytics suite

Knowledge Graph RAG

When the KnowledgeGraph index method is enabled, DB-GPT builds a family of graphs, not a single one. They share one build path and all support edge-traversal retrieval:

  1. LLM triplet graph โ€” An LLM extracts (subject, predicate, object) triplets from each chunk; triplets are upserted as entity -edge- entity into the graph store (TuGraph, Neo4j, or Memgraph). Each edge remembers the chunk it came from, so answers stay citable.
  2. Documentโ€“paragraph graph โ€” a structural skeleton of document โ†’ chunk โ†’ chunk (include / next edges) so retrieval can hop from an entity to the chunk and document that contain it. (With the community-summary variant, communities are also detected and summarised by an LLM.)
  3. Markdown heading graph โ€” for .md files, a file โ†’ H1 โ†’ H2 โ†’ H3 (contains) hierarchy. This is the graph analogue of the structural index.
  4. Code graph โ€” for code files and GIT_REPO spaces, the source is parsed with tree-sitter (Python / Java / JavaScript / TypeScript / Go / Rust / C / C++) and function / class / method / interface / struct โ€ฆ nodes are emitted with file โ†’ defines โ†’ node edges. This enables precise code-level questions such as "where is apply_anthropic_cache_control defined?".
note

The retriever also supports CALLS / INHERITS / IMPLEMENTS edges, but the current code-graph builder only emits contains and defines. Call-chain and inheritance traversals only return data when those edges were produced by another builder. See Knowledge Base Indexing Principles for the full detail and this caveat.

Graph retrieval sub-strategiesโ€‹

At query time, the GraphRetriever combines several sub-strategies:

  • Keyword-based โ€” Match graph nodes by extracted keywords
  • Vector-based โ€” Semantic similarity search on graph node embeddings
  • Text-based โ€” Convert natural language to graph query language (Text2GQL) via LLM
  • Document-based โ€” Retrieve through document-graph associations

Chunking Strategies

Document chunking is a critical step in RAG quality โ€” it is the shared foundation under every index. DB-GPT supports multiple chunking strategies:

StrategySplitterDescription
Chunk by SizeRecursiveCharacterTextSplitterSplit by character count with configurable size and overlap (default: 512 / 50)
Chunk by PagePageTextSplitterSplit at page boundaries (useful for PDFs)
Chunk by ParagraphParagraphTextSplitterSplit at paragraph boundaries
Chunk by SeparatorSeparatorTextSplitterSplit at custom separator strings
Chunk by Markdown HeaderMarkdownHeaderTextSplitterSplit at markdown heading levels; preserves the heading path used by the structural index and the heading graph

Chunking Parametersโ€‹

ParameterDescriptionDefault
chunk_sizeMaximum characters per chunk512
chunk_overlapOverlapping characters between adjacent chunks50
topkNumber of chunks to retrieve per query5
recall_scoreMinimum relevance score threshold0
recall_typeRecall strategy (TopK)TopK
modelEmbedding model to useDepends on configuration

Embedding Models

DB-GPT supports a wide range of embedding models for converting text into vector representations:

Local Modelsโ€‹

ModelClassDescription
HuggingFaceHuggingFaceEmbeddingsGeneral-purpose HuggingFace models
BGE SeriesHuggingFaceBgeEmbeddingsBAAI BGE models with instruction support (Chinese/English)
InstructorHuggingFaceInstructEmbeddingsInstruction-following embedding models

Remote API Modelsโ€‹

ProviderClassDescription
OpenAI-compatibleOpenAPIEmbeddingsAny OpenAI-compatible embedding API
JinaJinaEmbeddingsJina AI embedding service
OllamaOllamaEmbeddingsLocal Ollama embedding server
Tongyi (Aliyun)TongyiEmbeddingsAlibaba Cloud DashScope
Qianfan (Baidu)QianfanEmbeddingsBaidu Wenxin platform
SiliconFlowSiliconFlowEmbeddingsSiliconFlow embedding service

Usage

Creating a Knowledge Base (Web UI)โ€‹

Step 1 โ€” Open Knowledge Managementโ€‹

Navigate to the Knowledge section in the sidebar.

Step 2 โ€” Create and Configureโ€‹

  1. Click Create to start a new knowledge base.
  2. Select the index methods to enable (Vector Store, Knowledge Graph, Full Text โ€” combinable).
  3. Choose the Embedding Model and configure chunk parameters.

Step 3 โ€” Upload Dataโ€‹

Select a datasource type and upload your content. Supported types include Document (PDF, Word, Excel, CSV, etc.), URL, Text, Yuque, and Git Repo.

Step 4 โ€” Configure Chunkingโ€‹

Choose a chunking strategy and set parameters:

Step 5 โ€” Configure Retrieval Strategy (Optional)โ€‹

You can configure the retrieval strategy for your knowledge base. DB-GPT supports multiple retrieve modes โ€” Semantic, Keyword, Hybrid, and Tree โ€” to suit different query scenarios. Select the mode that best fits your use case in the knowledge base settings.

Step 6 โ€” Chat with Your Knowledgeโ€‹

Go to Chat, click the knowledge base icon in the chat input toolbar, select your knowledge base from the dropdown, and start asking questions. The conversation runs the agentic RAG loop described above.

Programmatic Usage (Python API)โ€‹

from dbgpt.rag import Chunk
from dbgpt_ext.rag.assembler import EmbeddingAssembler
from dbgpt_ext.rag.knowledge import KnowledgeFactory

# Extract: parse the source into raw text
knowledge = KnowledgeFactory.create(file_path="your_document.pdf")

# Transform + Load: chunk, embed, and persist into the vector index
assembler = await EmbeddingAssembler.aload_from_knowledge(
knowledge=knowledge,
index_store=your_vector_store,
embedding_model=your_embedding_model,
)
assembler.persist()

# Retrieve (chat time): the vector index answers similarity queries
retriever = assembler.as_retriever(top_k=5)
chunks = await retriever.aretrieve("What is the main topic?")

Next Steps

TopicLink
Indexing principles (structural / KG / code graph / vector / keyword)Knowledge Base Indexing Principles
Agentic RAG conversation principlesAgentic RAG Conversation Principles
Knowledge Base Web UI GuideKnowledge Base
RAG ConceptsRAG
Graph RAG SetupGraph RAG
AWEL RAG OperatorsAWEL
Source CodeGitHub