fix(mcp): P1 修復 - DI 一致性 + 測試補充 + 配置優化

首席架構師審查 P1 修復清單:

P1-1 RAG Provider DI 模式一致性:
- 支援 rag_service 參數注入
- 新增 close() 方法
- TYPE_CHECKING 延遲導入

P1-3 RAG 測試補充:
- test_rag_provider.py (9 tests)
- DI 注入/Lazy Load/Tool Schema/驗證/Close

P1-4 Grafana Config 快取優化:
- URL/Key 首次查詢後快取
- 減少重複 settings 存取

P1-5 Embedding 維度配置化:
- MODEL_DIMENSIONS 字典 (qwen/llama/nomic)
- default_dimension 參數
- 支援更多模型

測試: 9/9 PASSED

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
OG T
2026-03-29 16:23:30 +08:00
parent fc3d4a6b3a
commit 8724ed7dcf
4 changed files with 238 additions and 23 deletions

View File

@@ -7,9 +7,11 @@ Embedding Service - Ollama BGE-M3 替代方案
Phase 13.2 #84 - RAG Tool 基礎設施
版本: v1.0
版本: v1.1
建立日期: 2026-03-26 20:30 (台北時區)
更新日期: 2026-03-29 20:50 (台北時區)
建立者: Claude Code
更新者: Claude Code (P1 修復: 維度配置化)
"""
import asyncio
@@ -62,11 +64,21 @@ class OllamaEmbeddingService:
vector = await service.embed_text("維運手冊")
"""
# 已知模型維度 (P1 修復: 避免硬編碼)
MODEL_DIMENSIONS: dict[str, int] = {
"qwen2.5:7b-instruct": 3584,
"qwen2.5:3b-instruct": 2048,
"llama3.2:3b": 3072,
"nomic-embed-text": 768,
}
DEFAULT_DIMENSION = 3584 # 未知模型的預設值
def __init__(
self,
model: str = "qwen2.5:7b-instruct",
ollama_url: str | None = None,
timeout: float = 30.0,
default_dimension: int | None = None,
) -> None:
"""
初始化 Embedding Service
@@ -75,10 +87,16 @@ class OllamaEmbeddingService:
model: Ollama 模型名稱 (必須支援 embedding)
ollama_url: Ollama API URL (預設從 config 讀取)
timeout: 請求超時 (秒)
default_dimension: 預設向量維度 (可選,未提供則從 MODEL_DIMENSIONS 查詢)
P1 修復 (2026-03-29): 維度配置化,支援更多模型
"""
self._model = model
self._ollama_url = ollama_url or settings.OLLAMA_URL
self._timeout = timeout
self._default_dimension = default_dimension or self.MODEL_DIMENSIONS.get(
model, self.DEFAULT_DIMENSION
)
self._dimension: int | None = None
self._client: httpx.AsyncClient | None = None
@@ -87,12 +105,11 @@ class OllamaEmbeddingService:
"""
向量維度
首次呼叫會自動偵測,之後快取。
qwen2.5:7b-instruct = 3584 維
首次 embed 呼叫會自動偵測實際維度並快取。
偵測前返回 MODEL_DIMENSIONS 中的預設值。
"""
if self._dimension is None:
# 預設值,實際會在第一次 embed 時更新
return 3584
return self._default_dimension
return self._dimension
async def _get_client(self) -> httpx.AsyncClient: