您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

572 行
22KB

  1. <%
  2. '=======================================================================================================================
  3. ' Semantic retrieval: embeddings (Ollama) + vector index (Qdrant) + hybrid ranking (spec FR-008, FR-009, section 10).
  4. '
  5. ' SQLite is the source of truth. Table embedding_index records, per memory/chunk, what the vector store should hold
  6. ' (status pending | indexed | failed | delete, model, dimensions, revision). Write paths only mark rows inside their
  7. ' transaction (Emb_MarkPending / Emb_MarkDelete*); after commit they call Emb_AfterWrite, which indexes a bounded batch
  8. ' and never fails the request. scripts\embed.cmd processes everything left over or rebuilds the index.
  9. '
  10. ' Vectors are never parsed in VBScript: Ollama's JSON array text is passed straight into the Qdrant request body.
  11. ' Qdrant points use the memory/chunk id as point id and carry tenant_id, namespace_id, kind and revision as payload.
  12. ' Search filters by tenant, kind and the caller's readable namespaces in Qdrant, and callers then re-check every hit
  13. ' against the canonical tables (namespace, lifecycle, validity, current revision), as for lexical hits.
  14. '
  15. ' Settings (web.config appSettings):
  16. ' EmbeddingProvider ollama | none (default none: lexical only, with a warning)
  17. ' EmbeddingUrl http://ollama:11434
  18. ' EmbeddingModel nomic-embed-text
  19. ' EmbeddingDimensions 768
  20. ' EmbeddingDocumentPrefix "search_document: " (model-specific task prefixes; empty for models without them)
  21. ' EmbeddingQueryPrefix "search_query: "
  22. ' EmbeddingMinScore cosine similarity below which a semantic hit is ignored (default 0.6; model-specific: for
  23. ' nomic-embed-text relevant pairs scored 0.61-0.67, unrelated ones up to 0.58)
  24. ' VectorStoreUrl http://qdrant:6333
  25. ' The Qdrant collection is amk_<model>_<dimensions>, so changing the model starts a new collection (run embed reindex).
  26. ' No native object is held across calls: each HTTP call creates and releases its own MSXML2.ServerXMLHTTP.
  27. '=======================================================================================================================
  28. Const EMB_RRF_K = 60
  29. Const EMB_BATCH = 16
  30. Const EMB_MAX_ATTEMPTS = 5
  31. Const EMB_MAX_TEXT = 8000
  32. Dim Emb_LastError
  33. Emb_LastError = ""
  34. Function Emb_Setting(key, dflt)
  35. Dim v
  36. v = "" & GetAppSetting(key)
  37. If Len(v) = 0 Then
  38. v = dflt
  39. End If
  40. Emb_Setting = v
  41. End Function
  42. Function Emb_Enabled()
  43. Emb_Enabled = (LCase(Emb_Setting("EmbeddingProvider", "none")) = "ollama")
  44. End Function
  45. Function Emb_Model()
  46. Emb_Model = Emb_Setting("EmbeddingModel", "nomic-embed-text")
  47. End Function
  48. Function Emb_Dims()
  49. Emb_Dims = CLng(Emb_Setting("EmbeddingDimensions", "768"))
  50. End Function
  51. Function Emb_MinScore()
  52. Emb_MinScore = CDbl(Replace(Emb_Setting("EmbeddingMinScore", "0.6"), ".", Mid(CStr(1.5), 2, 1)))
  53. End Function
  54. Function Emb_Collection()
  55. Dim m, i, c, out
  56. m = LCase(Emb_Model())
  57. out = ""
  58. For i = 1 To Len(m)
  59. c = Mid(m, i, 1)
  60. If (c >= "a" And c <= "z") Or (c >= "0" And c <= "9") Then
  61. out = out & c
  62. Else
  63. out = out & "_"
  64. End If
  65. Next
  66. Emb_Collection = "amk_" & out & "_" & Emb_Dims()
  67. End Function
  68. ' One HTTP call. Returns the response text; status 0 and Emb_LastError on a transport failure.
  69. Function Emb_Http(method, url, body, ByRef status)
  70. Dim http, text
  71. Emb_Http = ""
  72. status = 0
  73. On Error Resume Next
  74. Set http = Server.CreateObject("MSXML2.ServerXMLHTTP")
  75. http.SetTimeouts 2000, 2000, 10000, 60000
  76. http.Open method, url, False
  77. If Len(body) > 0 Then
  78. http.SetRequestHeader "Content-Type", "application/json"
  79. http.Send body
  80. Else
  81. http.Send
  82. End If
  83. If Err.Number <> 0 Then
  84. Emb_LastError = method & " " & url & ": " & Err.Description
  85. Err.Clear
  86. Set http = Nothing
  87. Exit Function
  88. End If
  89. status = http.Status
  90. text = "" & http.ResponseText
  91. Set http = Nothing
  92. On Error GoTo 0
  93. If status < 200 Or status > 299 Then
  94. Emb_LastError = method & " " & url & ": HTTP " & status & " " & Left(text, 200)
  95. End If
  96. Emb_Http = text
  97. End Function
  98. ' Embeds texts (array of strings) with the given task prefix. Returns an array of raw JSON vectors ("[0.1,...]"),
  99. ' one per text, or Empty on failure (Emb_LastError says why).
  100. Function Emb_EmbedTexts(texts, prefix)
  101. Dim body, i, resp, status, p, q, inner, vecs, marker
  102. Emb_EmbedTexts = Empty
  103. body = ""
  104. For i = 0 To UBound(texts)
  105. If i > 0 Then
  106. body = body & ","
  107. End If
  108. body = body & JsonLite_Quote(prefix & Left("" & texts(i), EMB_MAX_TEXT))
  109. Next
  110. body = "{""model"":" & JsonLite_Quote(Emb_Model()) & ",""truncate"":true,""input"":[" & body & "]}"
  111. resp = Emb_Http("POST", Emb_Setting("EmbeddingUrl", "http://ollama:11434") & "/api/embed", body, status)
  112. If status <> 200 Then
  113. Exit Function
  114. End If
  115. ' {"model":"...","embeddings":[[...],[...]],...}: vectors hold only numbers, so "]]" ends the list
  116. marker = """embeddings"":[["
  117. p = InStr(resp, marker)
  118. If p = 0 Then
  119. Emb_LastError = "embedding response without embeddings"
  120. Exit Function
  121. End If
  122. p = p + Len(marker)
  123. q = InStr(p, resp, "]]")
  124. If q = 0 Then
  125. Emb_LastError = "embedding response is truncated"
  126. Exit Function
  127. End If
  128. inner = Replace(Replace(Mid(resp, p, q - p), " ", ""), vbLf, "")
  129. vecs = Split(inner, "],[")
  130. If UBound(vecs) <> UBound(texts) Then
  131. Emb_LastError = "embedding count mismatch (" & (UBound(vecs) + 1) & " for " & (UBound(texts) + 1) & " texts)"
  132. Exit Function
  133. End If
  134. For i = 0 To UBound(vecs)
  135. If UBound(Split(vecs(i), ",")) + 1 <> Emb_Dims() Then
  136. Emb_LastError = "model returned " & (UBound(Split(vecs(i), ",")) + 1) & " dimensions, EmbeddingDimensions is " & Emb_Dims()
  137. Exit Function
  138. End If
  139. vecs(i) = "[" & vecs(i) & "]"
  140. Next
  141. Emb_EmbedTexts = vecs
  142. End Function
  143. ' Creates the collection (cosine, configured size) and keyword payload indexes once per process.
  144. Function Emb_EnsureCollection()
  145. Dim name, base, status, resp, f
  146. name = Emb_Collection()
  147. Emb_EnsureCollection = False
  148. If Application("emb_ok_" & name) = True Then
  149. Emb_EnsureCollection = True
  150. Exit Function
  151. End If
  152. base = Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & name
  153. resp = Emb_Http("GET", base, "", status)
  154. If status = 404 Then
  155. resp = Emb_Http("PUT", base, "{""vectors"":{""size"":" & Emb_Dims() & ",""distance"":""Cosine""}}", status)
  156. If status <> 200 Then
  157. Exit Function
  158. End If
  159. For Each f In Array("tenant_id", "namespace_id", "kind")
  160. resp = Emb_Http("PUT", base & "/index?wait=true", "{""field_name"":""" & f & """,""field_schema"":""keyword""}", status)
  161. Next
  162. ElseIf status <> 200 Then
  163. Exit Function
  164. End If
  165. Application.Lock
  166. Application("emb_ok_" & name) = True
  167. Application.Unlock
  168. Emb_EnsureCollection = True
  169. End Function
  170. '-----------------------------------------------------------------------------------------------------------------------
  171. ' Bookkeeping (call inside the write transaction)
  172. '-----------------------------------------------------------------------------------------------------------------------
  173. Sub Emb_MarkPending(kind, targetId, tenantId, namespaceId, revision)
  174. DAL().Execute "INSERT INTO embedding_index (target_kind, target_id, tenant_id, namespace_id, revision, status, attempts, updated_at) " & _
  175. "VALUES (?, ?, ?, ?, ?, 'pending', 0, ?) ON CONFLICT(target_kind, target_id) DO UPDATE SET status = 'pending', " & _
  176. "revision = excluded.revision, namespace_id = excluded.namespace_id, attempts = 0, error = NULL, updated_at = excluded.updated_at", _
  177. Array(kind, targetId, tenantId, namespaceId, CLng(revision), Api_Now())
  178. End Sub
  179. Sub Emb_MarkDelete(kind, targetId)
  180. DAL().Execute "UPDATE embedding_index SET status = 'delete', updated_at = ? WHERE target_kind = ? AND target_id = ?", Array(Api_Now(), kind, targetId)
  181. End Sub
  182. ' Old revision's chunks of a document leave the vector index
  183. Sub Emb_MarkDeleteChunks(documentId, revision)
  184. DAL().Execute "UPDATE embedding_index SET status = 'delete', updated_at = ? WHERE target_kind = 'chunk' AND target_id IN " & _
  185. "(SELECT id FROM chunks WHERE document_id = ? AND document_revision = ?)", Array(Api_Now(), documentId, CLng(revision))
  186. End Sub
  187. ' After commit: index a bounded batch for this tenant. Never raises; a failure leaves rows pending/failed for later.
  188. Sub Emb_AfterWrite(tenantId, maxItems)
  189. Dim n
  190. If Not Emb_Enabled() Then
  191. Exit Sub
  192. End If
  193. On Error Resume Next
  194. n = Emb_ProcessPending(tenantId, maxItems)
  195. If Err.Number <> 0 Then
  196. Emb_LastError = "process: " & Err.Description
  197. Err.Clear
  198. End If
  199. On Error GoTo 0
  200. End Sub
  201. ' Processes deletions and up to maxItems pending/failed rows (tenantId "" = all tenants). Returns rows indexed.
  202. Function Emb_ProcessPending(tenantId, maxItems)
  203. Dim rs, sql, ids, n, idList, status, resp, rows, i, j, k, cnt, texts(), kinds(), tids(), tens(), nss(), revs(), text, rev, ok
  204. Dim batchStart, batchEnd, bt(), vecs, body, done, ts
  205. Emb_ProcessPending = 0
  206. If Not Emb_Enabled() Then
  207. Exit Function
  208. End If
  209. If Not Emb_EnsureCollection() Then
  210. Exit Function
  211. End If
  212. '--- deletions ------------------------------------------------------------------------------------------------
  213. sql = "SELECT target_id FROM embedding_index WHERE status = 'delete'"
  214. If Len(tenantId) > 0 Then
  215. sql = sql & " AND tenant_id = ?"
  216. Set rs = DAL().Query(sql & " LIMIT 256", tenantId)
  217. Else
  218. Set rs = DAL().Query(sql & " LIMIT 256", Empty)
  219. End If
  220. idList = ""
  221. ids = ""
  222. Do While Not rs.EOF
  223. If Api_IsId("" & rs(0)) Then
  224. If Len(idList) > 0 Then
  225. idList = idList & ","
  226. ids = ids & ","
  227. End If
  228. idList = idList & "'" & rs(0) & "'"
  229. ids = ids & """" & rs(0) & """"
  230. End If
  231. rs.MoveNext
  232. Loop
  233. rs.Close
  234. If Len(idList) > 0 Then
  235. resp = Emb_Http("POST", Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & Emb_Collection() & "/points/delete?wait=true", _
  236. "{""points"":[" & ids & "]}", status)
  237. If status = 200 Then
  238. DAL().Execute "DELETE FROM embedding_index WHERE status = 'delete' AND target_id IN (" & idList & ")", Empty
  239. Else
  240. Exit Function
  241. End If
  242. End If
  243. '--- pending and retryable failures ---------------------------------------------------------------------------
  244. sql = "SELECT target_kind, target_id, tenant_id, namespace_id, revision FROM embedding_index WHERE (status = 'pending' OR (status = 'failed' AND attempts < " & EMB_MAX_ATTEMPTS & "))"
  245. If Len(tenantId) > 0 Then
  246. Set rs = DAL().Query(sql & " AND tenant_id = ? ORDER BY updated_at LIMIT " & CLng(maxItems), tenantId)
  247. Else
  248. Set rs = DAL().Query(sql & " ORDER BY updated_at LIMIT " & CLng(maxItems), Empty)
  249. End If
  250. rows = Empty
  251. If Not rs.EOF Then
  252. rows = rs.GetRows()
  253. End If
  254. rs.Close
  255. If IsEmpty(rows) Then
  256. Exit Function
  257. End If
  258. ' Load the text to embed for every row (each query closed before the next)
  259. cnt = UBound(rows, 2) + 1
  260. ReDim texts(cnt - 1)
  261. ReDim kinds(cnt - 1)
  262. ReDim tids(cnt - 1)
  263. ReDim tens(cnt - 1)
  264. ReDim nss(cnt - 1)
  265. ReDim revs(cnt - 1)
  266. k = 0
  267. For i = 0 To cnt - 1
  268. text = ""
  269. rev = 0
  270. If "" & rows(0, i) = "memory" Then
  271. Set rs = DAL().Query("SELECT r.title, r.content, m.current_revision, m.namespace_id FROM memories m JOIN memory_revisions r " & _
  272. "ON r.memory_id = m.id AND r.revision = m.current_revision WHERE m.id = ?", "" & rows(1, i))
  273. If Not rs.EOF Then
  274. text = "" & rs(0) & vbLf & rs(1)
  275. rev = CLng(rs(2))
  276. rows(3, i) = "" & rs(3)
  277. End If
  278. rs.Close
  279. Else
  280. Set rs = DAL().Query("SELECT content, document_revision FROM chunks WHERE id = ?", "" & rows(1, i))
  281. If Not rs.EOF Then
  282. text = "" & rs(0)
  283. rev = CLng(rs(1))
  284. End If
  285. rs.Close
  286. End If
  287. If Len(text) = 0 Then
  288. ' the source is gone: drop the row (and any point)
  289. DAL().Execute "UPDATE embedding_index SET status = 'delete', updated_at = ? WHERE target_kind = ? AND target_id = ?", Array(Api_Now(), "" & rows(0, i), "" & rows(1, i))
  290. Else
  291. texts(k) = text
  292. kinds(k) = "" & rows(0, i)
  293. tids(k) = "" & rows(1, i)
  294. tens(k) = "" & rows(2, i)
  295. nss(k) = "" & rows(3, i)
  296. revs(k) = rev
  297. k = k + 1
  298. End If
  299. Next
  300. done = 0
  301. batchStart = 0
  302. Do While batchStart < k
  303. batchEnd = batchStart + EMB_BATCH - 1
  304. If batchEnd > k - 1 Then
  305. batchEnd = k - 1
  306. End If
  307. ReDim bt(batchEnd - batchStart)
  308. For j = batchStart To batchEnd
  309. bt(j - batchStart) = texts(j)
  310. Next
  311. vecs = Emb_EmbedTexts(bt, Emb_Setting("EmbeddingDocumentPrefix", ""))
  312. ok = Not IsEmpty(vecs)
  313. If ok Then
  314. body = ""
  315. For j = batchStart To batchEnd
  316. If j > batchStart Then
  317. body = body & ","
  318. End If
  319. body = body & "{""id"":""" & tids(j) & """,""vector"":" & vecs(j - batchStart) & ",""payload"":{""tenant_id"":""" & tens(j) & _
  320. """,""namespace_id"":""" & nss(j) & """,""kind"":""" & kinds(j) & """,""revision"":" & revs(j) & "}}"
  321. Next
  322. resp = Emb_Http("PUT", Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & Emb_Collection() & "/points?wait=true", _
  323. "{""points"":[" & body & "]}", status)
  324. ok = (status = 200)
  325. End If
  326. ts = Api_Now()
  327. For j = batchStart To batchEnd
  328. If ok Then
  329. DAL().Execute "UPDATE embedding_index SET status = 'indexed', model = ?, dimensions = ?, revision = ?, attempts = 0, error = NULL, updated_at = ? " & _
  330. "WHERE target_kind = ? AND target_id = ? AND status <> 'delete'", Array(Emb_Model(), Emb_Dims(), revs(j), ts, kinds(j), tids(j))
  331. done = done + 1
  332. Else
  333. DAL().Execute "UPDATE embedding_index SET status = 'failed', attempts = attempts + 1, error = ?, updated_at = ? WHERE target_kind = ? AND target_id = ?", _
  334. Array(Left(Emb_LastError, 500), ts, kinds(j), tids(j))
  335. End If
  336. Next
  337. If Not ok Then
  338. Exit Do ' provider or store down: leave the rest for later
  339. End If
  340. batchStart = batchEnd + 1
  341. Loop
  342. Emb_ProcessPending = done
  343. End Function
  344. ' Removes a whole tenant from the vector store and the bookkeeping (provision purge). Best effort for the store.
  345. Sub Emb_DeleteTenant(tenantId)
  346. Dim status, resp
  347. If Emb_Enabled() Then
  348. If Emb_EnsureCollection() Then
  349. resp = Emb_Http("POST", Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & Emb_Collection() & "/points/delete?wait=true", _
  350. "{""filter"":{""must"":[{""key"":""tenant_id"",""match"":{""value"":" & JsonLite_Quote(tenantId) & "}}]}}", status)
  351. End If
  352. End If
  353. DAL().Execute "DELETE FROM embedding_index WHERE tenant_id = ?", tenantId
  354. End Sub
  355. '-----------------------------------------------------------------------------------------------------------------------
  356. ' Hybrid ranking. Lexical (FTS5/bm25) and, when configured, semantic (Qdrant cosine) candidate lists are merged with
  357. ' reciprocal rank fusion (raw scores of the two engines are not comparable). Without semantic retrieval the order and
  358. ' scores are the lexical ones (negated bm25). Callers still apply the canonical filters to every id.
  359. ' Set r = New Ranker_Class : r.Run "memory"|"chunk", ftsQuery, queryText, tenantId, allowedSqlList
  360. ' r.Count, r.IdAt(i), r.ScoreAt(i), r.Strategy ("lexical"|"hybrid"), r.Warning ("" or a sentence)
  361. '-----------------------------------------------------------------------------------------------------------------------
  362. Class Ranker_Class
  363. Private m_ids(), m_scores(), m_n, m_strategy, m_warning
  364. Private m_lex(), m_lexScore(), m_lexN, m_sem(), m_semN
  365. Private Sub Class_Initialize()
  366. m_n = 0
  367. ReDim m_ids(0)
  368. ReDim m_scores(0)
  369. m_strategy = "lexical"
  370. m_warning = ""
  371. End Sub
  372. Public Property Get Count()
  373. Count = m_n
  374. End Property
  375. Public Function IdAt(i)
  376. IdAt = m_ids(i)
  377. End Function
  378. Public Function ScoreAt(i)
  379. ScoreAt = m_scores(i)
  380. End Function
  381. Public Property Get Strategy()
  382. Strategy = m_strategy
  383. End Property
  384. Public Property Get Warning()
  385. Warning = m_warning
  386. End Property
  387. Public Sub Run(kind, fts, queryText, tenantId, allowed)
  388. Dim rs, tbl, col, i
  389. If kind = "memory" Then
  390. tbl = "memories_fts"
  391. col = "memory_id"
  392. Else
  393. tbl = "chunks_fts"
  394. col = "chunk_id"
  395. End If
  396. m_lexN = 0
  397. ReDim m_lex(63)
  398. ReDim m_lexScore(63)
  399. If Len(fts) > 0 Then
  400. Set rs = DAL().Query("SELECT " & col & ", bm25(" & tbl & ") FROM " & tbl & " WHERE " & tbl & " MATCH ? AND tenant_id = ? ORDER BY bm25(" & tbl & ") LIMIT 300", Array(fts, tenantId))
  401. Do While Not rs.EOF
  402. If m_lexN > UBound(m_lex) Then
  403. ReDim Preserve m_lex(m_lexN * 2)
  404. ReDim Preserve m_lexScore(m_lexN * 2)
  405. End If
  406. m_lex(m_lexN) = "" & rs(0)
  407. m_lexScore(m_lexN) = -CDbl(rs(1))
  408. m_lexN = m_lexN + 1
  409. rs.MoveNext
  410. Loop
  411. rs.Close
  412. End If
  413. m_semN = 0
  414. ReDim m_sem(0)
  415. If Not Emb_Enabled() Then
  416. m_warning = "semantic retrieval is not configured; results are lexical only"
  417. ElseIf Len(allowed) = 0 Then
  418. m_strategy = "hybrid"
  419. ElseIf SemanticSearch(kind, queryText, tenantId, allowed) Then
  420. m_strategy = "hybrid"
  421. Else
  422. m_warning = "semantic retrieval is unavailable; results are lexical only"
  423. End If
  424. If m_strategy = "hybrid" Then
  425. Fuse
  426. Else
  427. m_n = m_lexN
  428. ReDim m_ids(m_n)
  429. ReDim m_scores(m_n)
  430. For i = 0 To m_lexN - 1
  431. m_ids(i) = m_lex(i)
  432. m_scores(i) = m_lexScore(i)
  433. Next
  434. End If
  435. End Sub
  436. ' Embeds the query and asks Qdrant for the closest points of this kind in the tenant's allowed namespaces.
  437. Private Function SemanticSearch(kind, queryText, tenantId, allowed)
  438. Dim vecs, body, resp, status, p, q, id, sc, minScore
  439. SemanticSearch = False
  440. If Not Emb_EnsureCollection() Then
  441. Exit Function
  442. End If
  443. vecs = Emb_EmbedTexts(Array(queryText), Emb_Setting("EmbeddingQueryPrefix", ""))
  444. If IsEmpty(vecs) Then
  445. Exit Function
  446. End If
  447. body = "{""query"":" & vecs(0) & ",""limit"":100,""with_payload"":false,""filter"":{""must"":[" & _
  448. "{""key"":""tenant_id"",""match"":{""value"":" & JsonLite_Quote(tenantId) & "}}," & _
  449. "{""key"":""kind"",""match"":{""value"":""" & kind & """}}," & _
  450. "{""key"":""namespace_id"",""match"":{""any"":[" & Replace(allowed, "'", """") & "]}}]}}"
  451. resp = Emb_Http("POST", Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & Emb_Collection() & "/points/query", body, status)
  452. If status <> 200 Then
  453. Exit Function
  454. End If
  455. minScore = Emb_MinScore()
  456. ' {"result":{"points":[{"id":"...","version":n,"score":0.8},...]},...}: scan id/score pairs in order
  457. p = InStr(resp, """id"":""")
  458. Do While p > 0
  459. p = p + 6
  460. q = InStr(p, resp, """")
  461. id = Mid(resp, p, q - p)
  462. p = InStr(q, resp, """score"":")
  463. If p = 0 Then
  464. Exit Do
  465. End If
  466. p = p + 8
  467. q = p
  468. Do While q <= Len(resp)
  469. If InStr("0123456789.-+eE", Mid(resp, q, 1)) = 0 Then
  470. Exit Do
  471. End If
  472. q = q + 1
  473. Loop
  474. sc = CDbl(Replace(Mid(resp, p, q - p), ".", Mid(CStr(1.5), 2, 1)))
  475. If sc >= minScore Then
  476. If m_semN > UBound(m_sem) Then
  477. ReDim Preserve m_sem(m_semN * 2 + 1)
  478. End If
  479. m_sem(m_semN) = id
  480. m_semN = m_semN + 1
  481. End If
  482. p = InStr(q, resp, """id"":""")
  483. Loop
  484. SemanticSearch = True
  485. End Function
  486. ' Reciprocal rank fusion over the top 100 of each list, sorted by fused score (descending)
  487. Private Sub Fuse()
  488. Dim i, j, lim, found, t, ts
  489. m_n = 0
  490. ReDim m_ids(200)
  491. ReDim m_scores(200)
  492. lim = m_lexN
  493. If lim > 100 Then
  494. lim = 100
  495. End If
  496. For i = 0 To lim - 1
  497. m_ids(m_n) = m_lex(i)
  498. m_scores(m_n) = 1 / (EMB_RRF_K + i + 1)
  499. m_n = m_n + 1
  500. Next
  501. lim = m_semN
  502. If lim > 100 Then
  503. lim = 100
  504. End If
  505. For i = 0 To lim - 1
  506. found = -1
  507. For j = 0 To m_n - 1
  508. If m_ids(j) = m_sem(i) Then
  509. found = j
  510. Exit For
  511. End If
  512. Next
  513. If found >= 0 Then
  514. m_scores(found) = m_scores(found) + 1 / (EMB_RRF_K + i + 1)
  515. Else
  516. m_ids(m_n) = m_sem(i)
  517. m_scores(m_n) = 1 / (EMB_RRF_K + i + 1)
  518. m_n = m_n + 1
  519. End If
  520. Next
  521. ' insertion sort, stable for equal scores (lexical order first)
  522. For i = 1 To m_n - 1
  523. t = m_ids(i)
  524. ts = m_scores(i)
  525. j = i - 1
  526. Do While j >= 0
  527. If m_scores(j) >= ts Then
  528. Exit Do
  529. End If
  530. m_ids(j + 1) = m_ids(j)
  531. m_scores(j + 1) = m_scores(j)
  532. j = j - 1
  533. Loop
  534. m_ids(j + 1) = t
  535. m_scores(j + 1) = ts
  536. Next
  537. End Sub
  538. End Class
  539. %>

Powered by TurnKey Linux.