Spaces:
Runtime error
Runtime error
Update agent/retrieval.py
Browse files- agent/retrieval.py +12 -6
agent/retrieval.py
CHANGED
|
@@ -58,14 +58,20 @@ async def semantic_retrieve(query: str, top_k: int = 3) -> list:
|
|
| 58 |
# 2. 将返回的向量转为 NumPy 数组
|
| 59 |
query_vector = np.array([embedding], dtype=np.float32)
|
| 60 |
|
| 61 |
-
# 3. 在 FAISS 中进行相似度计算
|
| 62 |
-
|
|
|
|
| 63 |
|
| 64 |
-
# 4. 组装结果切片
|
| 65 |
results = []
|
| 66 |
-
for idx in indices[0]:
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
results.append(_CHUNKS[idx])
|
| 70 |
|
| 71 |
return results
|
|
|
|
| 58 |
# 2. 将返回的向量转为 NumPy 数组
|
| 59 |
query_vector = np.array([embedding], dtype=np.float32)
|
| 60 |
|
| 61 |
+
# 3. 在 FAISS 中进行相似度计算 (将 top_k 压低,比如改为 2,召回少但精)
|
| 62 |
+
strict_top_k = min(top_k, 2)
|
| 63 |
+
distances, indices = _FAISS_INDEX.search(query_vector, strict_top_k)
|
| 64 |
|
| 65 |
+
# 4. 组装结果切片 (加入高精度阈值锁)
|
| 66 |
results = []
|
| 67 |
+
for i, idx in enumerate(indices[0]):
|
| 68 |
+
distance = distances[0][i]
|
| 69 |
+
|
| 70 |
+
# 【核心物理锁:精度绝对高】
|
| 71 |
+
# FAISS 默认是 L2 距离(越小越相似)。如果库里没相关知识,距离会很大。
|
| 72 |
+
# 这里的 0.8 是一个经验截断阀值(数字越小要求越严苛)。
|
| 73 |
+
# 如果距离大于 0.8,说明是强行凑数的垃圾文本,直接抛弃!
|
| 74 |
+
if 0 <= idx < len(_CHUNKS) and distance < 0.6:
|
| 75 |
results.append(_CHUNKS[idx])
|
| 76 |
|
| 77 |
return results
|