# RAG-MCP 功能增强方案（基于LlamaIndex生态）

## 📋 设计理念

**核心原则：最大化利用LlamaIndex生态系统**
- ✅ 优先使用LlamaIndex官方组件
- ✅ 利用社区成熟插件
- ✅ 通过配置和组合实现功能
- ✅ 减少自定义代码开发
- ✅ 保持标准化和可维护性

---

## 🔧 LlamaIndex核心组件应用

### 1. 分数阈值过滤 - 使用 SimilarityPostprocessor

**LlamaIndex内置解决方案**：
```python
from llama_index.core.postprocessor import SimilarityPostprocessor

# 创建相似度后处理器
similarity_processor = SimilarityPostprocessor(
    similarity_cutoff=0.3  # 分数阈值
)

# 应用到查询引擎
query_engine = index.as_query_engine(
    similarity_top_k=10,
    node_postprocessors=[similarity_processor]
)
```

**集成到项目**：
```python
# src/core/query_engine.py
def create_query_engine(
    self,
    index: VectorStoreIndex,
    mode: Optional[str] = None,
    top_k: Optional[int] = None,
    similarity_cutoff: Optional[float] = None  # 新增参数
):
    postprocessors = []
    
    # 添加相似度过滤
    if similarity_cutoff is not None and similarity_cutoff > 0:
        postprocessors.append(
            SimilarityPostprocessor(similarity_cutoff=similarity_cutoff)
        )
    
    return index.as_query_engine(
        similarity_top_k=top_k or self.config.retrieval.top_k,
        node_postprocessors=postprocessors
    )
```

**优势**：
- ✅ 官方支持，稳定可靠
- ✅ 自动处理向量和BM25检索
- ✅ 无需自定义过滤逻辑

---

### 2. 结果重排序 - 使用官方Reranker插件

#### 2.1 基于相似度的重排序（内置）

**使用 LongContextReorder**：
```python
from llama_index.core.postprocessor import LongContextReorder

# 长文本重排序（将最相关的放在首尾）
reorder_processor = LongContextReorder()

query_engine = index.as_query_engine(
    similarity_top_k=10,
    node_postprocessors=[reorder_processor]
)
```

#### 2.2 使用Cohere Rerank（推荐）

**安装插件**：
```bash
pip install llama-index-postprocessors-cohere-rerank
```

**使用方法**：
```python
from llama_index.postprocessors.cohere_rerank import CohereRerank

# Cohere重排序（商业级效果）
cohere_rerank = CohereRerank(
    api_key="your-cohere-api-key",
    top_n=5  # 重排后返回的数量
)

query_engine = index.as_query_engine(
    similarity_top_k=20,  # 初次检索更多
    node_postprocessors=[cohere_rerank]
)
```

#### 2.3 使用SentenceTransformer Rerank

**安装插件**：
```bash
pip install llama-index-postprocessors-sentence-transformer-rerank
```

**使用方法**：
```python
from llama_index.postprocessors.sentence_transformer_rerank import SentenceTransformerRerank

# 本地重排序模型（免费）
reranker = SentenceTransformerRerank(
    model="cross-encoder/ms-marco-MiniLM-L-2-v2",
    top_n=5
)

query_engine = index.as_query_engine(
    similarity_top_k=20,
    node_postprocessors=[reranker]
)
```

**集成到项目配置**：
```python
# src/config/settings.py
class RetrievalConfig(BaseModel):
    # ... 现有配置 ...
    
    # Reranker配置
    use_reranker: bool = Field(default=False)
    reranker_type: Literal["cohere", "sentence-transformer", "none"] = Field(default="none")
    reranker_model: str = Field(default="cross-encoder/ms-marco-MiniLM-L-2-v2")
    reranker_top_n: int = Field(default=5, ge=1, le=20)
    cohere_api_key: str = Field(default="")
```

---

### 3. 元数据过滤 - 使用 MetadataFilters

**LlamaIndex内置解决方案**：
```python
from llama_index.core.vector_stores import (
    MetadataFilters,
    MetadataFilter,
    FilterOperator
)

# 定义过滤器
filters = MetadataFilters(
    filters=[
        MetadataFilter(
            key="file_type",
            value="pdf",
            operator=FilterOperator.EQ
        ),
        MetadataFilter(
            key="created_at",
            value="2024-01-01",
            operator=FilterOperator.GTE
        )
    ]
)

# 应用到检索器
retriever = index.as_retriever(
    similarity_top_k=10,
    filters=filters
)
```

**支持的操作符**：
```python
FilterOperator.EQ        # 等于
FilterOperator.NE        # 不等于
FilterOperator.GT        # 大于
FilterOperator.LT        # 小于
FilterOperator.GTE       # 大于等于
FilterOperator.LTE       # 小于等于
FilterOperator.IN        # 包含于
FilterOperator.NIN       # 不包含于
FilterOperator.CONTAINS  # 包含
```

**集成到项目**：
```python
# src/core/query_engine.py
def create_retriever_with_filters(
    self,
    index: VectorStoreIndex,
    metadata_filters: Optional[Dict] = None,
    top_k: Optional[int] = None
):
    """创建带元数据过滤的检索器"""
    filters = None
    
    if metadata_filters:
        filter_list = []
        for key, filter_def in metadata_filters.items():
            operator = FilterOperator[filter_def.get("operator", "EQ").upper()]
            value = filter_def.get("value")
            
            filter_list.append(
                MetadataFilter(key=key, value=value, operator=operator)
            )
        
        filters = MetadataFilters(filters=filter_list)
    
    return index.as_retriever(
        similarity_top_k=top_k or self.config.retrieval.top_k,
        filters=filters
    )
```

---

### 4. 多样性过滤 - 使用 SentenceEmbeddingOptimizer

**LlamaIndex内置解决方案**：
```python
from llama_index.core.postprocessor import SentenceEmbeddingOptimizer

# 移除冗余文档
optimizer = SentenceEmbeddingOptimizer(
    embed_model=embed_model,
    percentile_cutoff=0.5,  # 保留前50%最相关的
    threshold_cutoff=0.7    # 相似度阈值
)

query_engine = index.as_query_engine(
    similarity_top_k=20,
    node_postprocessors=[optimizer]
)
```

**或使用固定数量优化器**：
```python
from llama_index.core.postprocessor import FixedRecencyPostprocessor

# 基于时间的优化
recency_processor = FixedRecencyPostprocessor(
    top_k=5,
    date_key="created_at"  # 元数据中的日期字段
)
```

---

### 5. 增量索引管理 - 使用内置方法

**LlamaIndex原生支持**：

```python
# 1. 插入新文档
from llama_index.core import Document

new_docs = [
    Document(text="新文档1", metadata={"source": "web"}),
    Document(text="新文档2", metadata={"source": "pdf"})
]

# 插入到现有索引
index.insert_nodes(new_docs)
index.storage_context.persist()  # 持久化

# 2. 刷新文档（更新）
index.refresh_ref_docs(
    documents=updated_docs,
    update_kwargs={"delete_old": True}
)

# 3. 删除文档
index.delete_ref_doc(
    ref_doc_id="doc_id",
    delete_from_docstore=True
)

# 4. 从文档存储获取文档
doc_store = index.storage_context.docstore
all_docs = doc_store.docs
doc = doc_store.get_document(doc_id)
```

**集成到项目**：
```python
# src/core/index_manager.py
class IndexManager:
    def add_documents(self, documents: List[Document]) -> Dict:
        """增量添加文档（使用LlamaIndex原生方法）"""
        if not self.index:
            return {"success": False, "error": "索引未初始化"}
        
        try:
            # 使用LlamaIndex的insert方法
            self.index.insert_nodes(documents)
            
            # 更新BM25索引
            if self.bm25_retriever:
                self._sync_bm25_index(documents)
            
            # 持久化
            self.index.storage_context.persist()
            
            return {
                "success": True,
                "added_count": len(documents),
                "document_ids": [d.doc_id for d in documents]
            }
        except Exception as e:
            logger.error(f"添加文档失败: {e}")
            return {"success": False, "error": str(e)}
    
    def update_document(self, doc_id: str, new_document: Document) -> Dict:
        """更新文档（使用refresh）"""
        try:
            self.index.refresh_ref_docs(
                documents=[new_document],
                update_kwargs={"delete_old": True}
            )
            
            self.index.storage_context.persist()
            
            return {"success": True, "document_id": doc_id}
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    def delete_document(self, doc_id: str) -> Dict:
        """删除文档"""
        try:
            self.index.delete_ref_doc(
                ref_doc_id=doc_id,
                delete_from_docstore=True
            )
            
            self.index.storage_context.persist()
            
            return {"success": True, "document_id": doc_id}
        except Exception as e:
            return {"success": False, "error": str(e)}
```

---

### 6. 批量查询 - 使用async_query

**LlamaIndex支持异步查询**：
```python
import asyncio

async def batch_query(query_engine, questions: List[str]) -> List[str]:
    """异步批量查询"""
    tasks = [query_engine.aquery(q) for q in questions]
    responses = await asyncio.gather(*tasks)
    return [str(r) for r in responses]

# 使用
questions = ["问题1", "问题2", "问题3"]
results = asyncio.run(batch_query(query_engine, questions))
```

**集成到项目**：
```python
# src/services/rag_service.py
async def batch_query_async(
    self,
    questions: List[str],
    mode: Optional[str] = None,
    top_k: Optional[int] = None
) -> List[Dict]:
    """异步批量查询（使用LlamaIndex原生异步支持）"""
    rag = self._get_rag_system()
    query_engine = rag.get_query_engine(mode=mode, top_k=top_k)
    
    # 使用LlamaIndex的aquery方法
    tasks = [query_engine.aquery(q) for q in questions]
    responses = await asyncio.gather(*tasks)
    
    results = []
    for q, r in zip(questions, responses):
        results.append({
            "question": q,
            "answer": str(r),
            "sources": [
                {
                    "text": node.node.text,
                    "score": node.score,
                    "metadata": node.node.metadata
                }
                for node in r.source_nodes
            ]
        })
    
    return {"success": True, "count": len(results), "results": results}
```

---

## 📦 推荐的LlamaIndex插件集成

### 1. Postprocessor插件

| 插件 | 用途 | 安装命令 |
|-----|------|---------|
| `cohere-rerank` | 高质量重排序 | `pip install llama-index-postprocessors-cohere-rerank` |
| `sentence-transformer-rerank` | 本地重排序 | `pip install llama-index-postprocessors-sentence-transformer-rerank` |
| `colbert-rerank` | ColBERT重排序 | `pip install llama-index-postprocessors-colbert-rerank` |
| `flag-embedding-reranker` | 中文优化重排序 | `pip install llama-index-postprocessors-flag-embedding-reranker` |

### 2. 特殊检索器插件

| 插件 | 用途 | 安装命令 |
|-----|------|---------|
| `llama-index-retrievers-bm25` | BM25检索（已使用） | 已集成 |
| `llama-index-retrievers-document-summary` | 文档摘要检索 | `pip install llama-index-retrievers-document-summary` |
| `llama-index-retrievers-knowledge-graph` | 知识图谱检索 | `pip install llama-index-retrievers-knowledge-graph` |

### 3. 评估插件

| 插件 | 用途 | 安装命令 |
|-----|------|---------|
| `llama-index-evaluation` | 检索评估 | `pip install llama-index-evaluation` |

---

## 🎨 组合使用示例

### 场景1: 高质量检索（使用多个Postprocessors）

```python
from llama_index.core.postprocessor import (
    SimilarityPostprocessor,
    SentenceEmbeddingOptimizer
)
from llama_index.postprocessors.cohere_rerank import CohereRerank

# 组合多个后处理器
postprocessors = [
    # 1. 相似度过滤
    SimilarityPostprocessor(similarity_cutoff=0.3),
    
    # 2. 多样性优化
    SentenceEmbeddingOptimizer(
        embed_model=embed_model,
        percentile_cutoff=0.5,
        threshold_cutoff=0.7
    ),
    
    # 3. 重排序
    CohereRerank(api_key=cohere_key, top_n=5)
]

query_engine = index.as_query_engine(
    similarity_top_k=20,  # 初始检索20个
    node_postprocessors=postprocessors  # 应用处理链
)
```

### 场景2: 元数据过滤 + 重排序

```python
from llama_index.core.vector_stores import MetadataFilters, MetadataFilter, FilterOperator

# 定义过滤条件
filters = MetadataFilters(
    filters=[
        MetadataFilter(key="file_type", value="pdf", operator=FilterOperator.EQ),
        MetadataFilter(key="created_at", value="2024-01-01", operator=FilterOperator.GTE)
    ]
)

# 创建带过滤的检索器
retriever = index.as_retriever(
    similarity_top_k=20,
    filters=filters
)

# 创建带重排序的查询引擎
from llama_index.core.query_engine import RetrieverQueryEngine

query_engine = RetrieverQueryEngine(
    retriever=retriever,
    node_postprocessors=[cohere_rerank]
)
```

### 场景3: 混合检索 + 完整后处理链

```python
from llama_index.core.retrievers import QueryFusionRetriever

# 混合检索器
hybrid_retriever = QueryFusionRetriever(
    retrievers=[
        index.as_retriever(similarity_top_k=10, filters=filters),
        bm25_retriever
    ],
    num_queries=1,
    use_async=True
)

# 完整的后处理链
postprocessors = [
    SimilarityPostprocessor(similarity_cutoff=0.2),
    SentenceEmbeddingOptimizer(
        embed_model=embed_model,
        threshold_cutoff=0.7
    ),
    CohereRerank(top_n=5)
]

# 组合成查询引擎
from llama_index.core.query_engine import RetrieverQueryEngine

query_engine = RetrieverQueryEngine(
    retriever=hybrid_retriever,
    node_postprocessors=postprocessors
)
```

---

## 🔧 项目集成方案

### 更新配置文件

```python
# src/config/settings.py
class RetrievalConfig(BaseModel):
    """检索配置（增强版）"""
    # 基础配置
    mode: Literal["vector", "bm25", "hybrid"] = Field(default="hybrid")
    top_k: int = Field(default=5, ge=1, le=100)
    
    # Postprocessor配置
    use_similarity_filter: bool = Field(default=False)
    similarity_cutoff: float = Field(default=0.3, ge=0.0, le=1.0)
    
    use_optimizer: bool = Field(default=False)
    optimizer_percentile: float = Field(default=0.5, ge=0.0, le=1.0)
    optimizer_threshold: float = Field(default=0.7, ge=0.0, le=1.0)
    
    # Reranker配置
    use_reranker: bool = Field(default=False)
    reranker_type: Literal["cohere", "sentence-transformer", "colbert", "flag-embedding"] = "sentence-transformer"
    reranker_model: str = Field(default="cross-encoder/ms-marco-MiniLM-L-2-v2")
    reranker_top_n: int = Field(default=5)
    cohere_api_key: str = Field(default="")
    
    # 元数据过滤
    enable_metadata_filters: bool = Field(default=True)
    
    # BM25配置（保持现有）
    use_bm25: bool = Field(default=True)
    bm25_top_k: int = Field(default=5, ge=1, le=100)
    bm25_language: Literal["chinese", "english"] = Field(default="chinese")
```

### 更新查询引擎管理器

```python
# src/core/query_engine.py
class QueryEngineManager:
    """查询引擎管理器（基于LlamaIndex组件）"""
    
    def __init__(self, config: Optional[ConfigManager] = None):
        self.config = config or get_config_manager()
        self.bm25_store_manager = BM25StoreManager(config=self.config)
    
    def _create_postprocessors(self) -> List:
        """创建后处理器链"""
        postprocessors = []
        retrieval_config = self.config.retrieval
        
        # 1. 相似度过滤
        if retrieval_config.use_similarity_filter:
            from llama_index.core.postprocessor import SimilarityPostprocessor
            postprocessors.append(
                SimilarityPostprocessor(
                    similarity_cutoff=retrieval_config.similarity_cutoff
                )
            )
        
        # 2. 多样性优化
        if retrieval_config.use_optimizer:
            from llama_index.core.postprocessor import SentenceEmbeddingOptimizer
            postprocessors.append(
                SentenceEmbeddingOptimizer(
                    percentile_cutoff=retrieval_config.optimizer_percentile,
                    threshold_cutoff=retrieval_config.optimizer_threshold
                )
            )
        
        # 3. 重排序
        if retrieval_config.use_reranker:
            reranker = self._create_reranker()
            if reranker:
                postprocessors.append(reranker)
        
        return postprocessors
    
    def _create_reranker(self):
        """创建重排序器"""
        retrieval_config = self.config.retrieval
        reranker_type = retrieval_config.reranker_type
        
        try:
            if reranker_type == "cohere":
                from llama_index.postprocessors.cohere_rerank import CohereRerank
                return CohereRerank(
                    api_key=retrieval_config.cohere_api_key,
                    top_n=retrieval_config.reranker_top_n
                )
            
            elif reranker_type == "sentence-transformer":
                from llama_index.postprocessors.sentence_transformer_rerank import SentenceTransformerRerank
                return SentenceTransformerRerank(
                    model=retrieval_config.reranker_model,
                    top_n=retrieval_config.reranker_top_n
                )
            
            elif reranker_type == "flag-embedding":
                from llama_index.postprocessors.flag_embedding_reranker import FlagEmbeddingReranker
                return FlagEmbeddingReranker(
                    top_n=retrieval_config.reranker_top_n,
                    model="BAAI/bge-reranker-large"  # 中文优化
                )
        
        except ImportError as e:
            logger.warning(f"Reranker插件未安装: {e}")
            return None
    
    def create_query_engine(
        self,
        index: VectorStoreIndex,
        mode: Optional[str] = None,
        top_k: Optional[int] = None,
        metadata_filters: Optional[Dict] = None
    ):
        """创建查询引擎（使用LlamaIndex组件）"""
        retrieval_mode = mode or self.config.retrieval.mode
        similarity_top_k = top_k or self.config.retrieval.top_k
        
        # 创建后处理器
        postprocessors = self._create_postprocessors()
        
        # 创建元数据过滤器
        filters = None
        if metadata_filters and self.config.retrieval.enable_metadata_filters:
            filters = self._create_metadata_filters(metadata_filters)
        
        if retrieval_mode == "vector":
            return index.as_query_engine(
                similarity_top_k=similarity_top_k,
                filters=filters,
                node_postprocessors=postprocessors
            )
        
        elif retrieval_mode == "bm25":
            bm25_retriever = self.bm25_store_manager.get_bm25_retriever()
            from llama_index.core.query_engine import RetrieverQueryEngine
            return RetrieverQueryEngine(
                retriever=bm25_retriever,
                node_postprocessors=postprocessors
            )
        
        elif retrieval_mode == "hybrid":
            return self._create_hybrid_query_engine(
                index, 
                similarity_top_k, 
                filters, 
                postprocessors
            )
    
    def _create_metadata_filters(self, metadata_filters: Dict):
        """创建元数据过滤器"""
        from llama_index.core.vector_stores import (
            MetadataFilters,
            MetadataFilter,
            FilterOperator
        )
        
        filter_list = []
        for key, filter_def in metadata_filters.items():
            operator_str = filter_def.get("operator", "EQ").upper()
            operator = FilterOperator[operator_str]
            value = filter_def.get("value")
            
            filter_list.append(
                MetadataFilter(key=key, value=value, operator=operator)
            )
        
        return MetadataFilters(filters=filter_list)
    
    def _create_hybrid_query_engine(
        self, 
        index: VectorStoreIndex, 
        similarity_top_k: int,
        filters,
        postprocessors: List
    ):
        """创建混合查询引擎"""
        from llama_index.core.retrievers import QueryFusionRetriever
        from llama_index.core.query_engine import RetrieverQueryEngine
        
        bm25_retriever = self.bm25_store_manager.get_bm25_retriever()
        
        # 混合检索器
        hybrid_retriever = QueryFusionRetriever(
            retrievers=[
                index.as_retriever(similarity_top_k=similarity_top_k, filters=filters),
                bm25_retriever
            ],
            num_queries=1,
            use_async=not self.config.vector_store.use_qdrant
        )
        
        return RetrieverQueryEngine(
            retriever=hybrid_retriever,
            node_postprocessors=postprocessors
        )
```

---

## 📦 依赖安装清单

### requirements.txt 更新

```txt
# 现有依赖
llama-index>=0.11.0
llama-index-llms-openai-like>=0.2.0
llama-index-retrievers-bm25>=0.4.0
# ... 其他现有依赖 ...

# 新增：Postprocessor插件
llama-index-postprocessors-cohere-rerank>=0.2.0
llama-index-postprocessors-sentence-transformer-rerank>=0.2.0
llama-index-postprocessors-flag-embedding-reranker>=0.2.0

# 新增：支持库
sentence-transformers>=2.2.0
```

### 可选插件（按需安装）

```bash
# ColBERT重排序（高级）
pip install llama-index-postprocessors-colbert-rerank

# 文档摘要检索
pip install llama-index-retrievers-document-summary

# 评估工具
pip install llama-index-evaluation
```

---

## 🎯 MCP工具定义更新

### 增强现有工具

**retrieve_documents** - 增加参数：
```json
{
    "name": "retrieve_documents",
    "description": "检索相关文档，支持高级过滤和重排序",
    "inputSchema": {
        "type": "object",
        "properties": {
            "question": {"type": "string"},
            "mode": {
                "type": "string",
                "enum": ["vector", "bm25", "hybrid"],
                "default": "hybrid"
            },
            "top_k": {"type": "integer", "default": 5},
            
            "similarity_cutoff": {
                "type": "number",
                "description": "相似度阈值（0-1），使用SimilarityPostprocessor",
                "minimum": 0.0,
                "maximum": 1.0
            },
            
            "use_reranker": {
                "type": "boolean",
                "description": "是否使用重排序",
                "default": false
            },
            
            "reranker_type": {
                "type": "string",
                "enum": ["cohere", "sentence-transformer", "flag-embedding"],
                "description": "重排序器类型"
            },
            
            "metadata_filters": {
                "type": "object",
                "description": "元数据过滤条件",
                "additionalProperties": {
                    "type": "object",
                    "properties": {
                        "operator": {
                            "type": "string",
                            "enum": ["EQ", "NE", "GT", "LT", "GTE", "LTE", "IN", "CONTAINS"]
                        },
                        "value": {}
                    }
                }
            }
        },
        "required": ["question"]
    }
}
```

---

## 🚀 实施优势

### 相比自定义实现的优势

| 方面 | 自定义实现 | 基于LlamaIndex | 优势 |
|-----|----------|---------------|------|
| **开发成本** | 高（需从零实现） | 低（配置和组合） | ⭐⭐⭐⭐⭐ |
| **维护成本** | 高（自行维护） | 低（官方维护） | ⭐⭐⭐⭐⭐ |
| **稳定性** | 需要测试验证 | 生产级稳定 | ⭐⭐⭐⭐⭐ |
| **性能** | 需要优化 | 已优化 | ⭐⭐⭐⭐ |
| **扩展性** | 有限 | 丰富的插件生态 | ⭐⭐⭐⭐⭐ |
| **社区支持** | 无 | 活跃社区 | ⭐⭐⭐⭐⭐ |
| **文档** | 需自行编写 | 官方文档完善 | ⭐⭐⭐⭐⭐ |

---

## 📋 实施计划（基于LlamaIndex）

### Phase 1: 后处理器集成（3-5天）

- [ ] 集成`SimilarityPostprocessor`
- [ ] 集成`SentenceEmbeddingOptimizer`
- [ ] 集成`LongContextReorder`
- [ ] 更新配置系统
- [ ] 更新查询引擎管理器

### Phase 2: Reranker集成（3-5天）

- [ ] 安装Reranker插件
- [ ] 集成Cohere Rerank
- [ ] 集成SentenceTransformer Rerank
- [ ] 集成Flag Embedding Reranker（中文优化）
- [ ] 配置选择逻辑

### Phase 3: 元数据过滤（2-3天）

- [ ] 集成`MetadataFilters`
- [ ] 更新检索器创建逻辑
- [ ] 支持过滤器组合

### Phase 4: 索引管理（2-3天）

- [ ] 使用`insert_nodes`实现增量添加
- [ ] 使用`refresh_ref_docs`实现更新
- [ ] 使用`delete_ref_doc`实现删除
- [ ] BM25索引同步

### Phase 5: 异步批量查询（2天）

- [ ] 实现`aquery`批量查询
- [ ] 添加进度显示

### Phase 6: MCP工具和CLI更新（3-5天）

- [ ] 更新MCP工具参数
- [ ] 更新CLI命令
- [ ] 更新文档

**总计：15-23天（2-3周）**

---

## 📚 参考文档

### LlamaIndex官方文档
- [Postprocessors](https://docs.llamaindex.ai/en/stable/module_guides/querying/node_postprocessors/)
- [Metadata Filters](https://docs.llamaindex.ai/en/stable/module_guides/querying/retriever/metadata_filters/)
- [Reranking](https://docs.llamaindex.ai/en/stable/examples/node_postprocessor/rerank/)
- [Async Query](https://docs.llamaindex.ai/en/stable/module_guides/deploying/query_engine/usage_pattern.html#async-query)

### 插件文档
- [Cohere Rerank](https://github.com/run-llama/llama_index/tree/main/llama-index-integrations/postprocessor/llama-index-postprocessors-cohere-rerank)
- [SentenceTransformer Rerank](https://github.com/run-llama/llama_index/tree/main/llama-index-integrations/postprocessor/llama-index-postprocessors-sentence-transformer-rerank)
- [Flag Embedding Reranker](https://github.com/run-llama/llama_index/tree/main/llama-index-integrations/postprocessor/llama-index-postprocessors-flag-embedding-reranker)

---

## ✅ 关键优势总结

1. **标准化**：使用LlamaIndex标准组件，符合业界最佳实践
2. **可维护性**：官方维护，自动获得更新和bug修复
3. **易扩展**：丰富的插件生态，可随时添加新功能
4. **低成本**：最少的自定义代码，快速实现功能
5. **高质量**：生产级组件，经过充分测试
6. **灵活组合**：通过配置和组合实现复杂功能
7. **社区支持**：活跃的社区，丰富的示例和教程

---

**方案版本**: v2.0 (基于LlamaIndex生态)  
**创建日期**: 2026-01-09  
**优势**: 最小化自定义代码，最大化利用成熟组件
