Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

669 Zeilen
26KB

  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. ' Feedback (POST /feedback) on the CURRENT revision of a result then scales its score: x(1 + 0.1 per useful, max 5),
  362. ' x0.9 per not_useful (max 5), x0.5 per incorrect/harmful (max 3), and the list is re-sorted.
  363. ' r.FeedbackAt(i) ("" or a JSON object of counts), r.Demoted (results with more negative than useful ratings)
  364. '-----------------------------------------------------------------------------------------------------------------------
  365. Class Ranker_Class
  366. Private m_ids(), m_scores(), m_n, m_strategy, m_warning, m_fb(), m_demoted
  367. Private m_lex(), m_lexScore(), m_lexN, m_sem(), m_semN
  368. Private Sub Class_Initialize()
  369. m_n = 0
  370. ReDim m_ids(0)
  371. ReDim m_scores(0)
  372. m_strategy = "lexical"
  373. m_warning = ""
  374. m_demoted = 0
  375. ReDim m_fb(0)
  376. End Sub
  377. Public Function FeedbackAt(i)
  378. FeedbackAt = "" & m_fb(i)
  379. End Function
  380. Public Property Get Demoted()
  381. Demoted = m_demoted
  382. End Property
  383. Public Property Get Count()
  384. Count = m_n
  385. End Property
  386. Public Function IdAt(i)
  387. IdAt = m_ids(i)
  388. End Function
  389. Public Function ScoreAt(i)
  390. ScoreAt = m_scores(i)
  391. End Function
  392. Public Property Get Strategy()
  393. Strategy = m_strategy
  394. End Property
  395. Public Property Get Warning()
  396. Warning = m_warning
  397. End Property
  398. Public Sub Run(kind, fts, queryText, tenantId, allowed)
  399. Dim rs, tbl, col, i
  400. If kind = "memory" Then
  401. tbl = "memories_fts"
  402. col = "memory_id"
  403. Else
  404. tbl = "chunks_fts"
  405. col = "chunk_id"
  406. End If
  407. m_lexN = 0
  408. ReDim m_lex(63)
  409. ReDim m_lexScore(63)
  410. If Len(fts) > 0 Then
  411. 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))
  412. Do While Not rs.EOF
  413. If m_lexN > UBound(m_lex) Then
  414. ReDim Preserve m_lex(m_lexN * 2)
  415. ReDim Preserve m_lexScore(m_lexN * 2)
  416. End If
  417. m_lex(m_lexN) = "" & rs(0)
  418. m_lexScore(m_lexN) = -CDbl(rs(1))
  419. m_lexN = m_lexN + 1
  420. rs.MoveNext
  421. Loop
  422. rs.Close
  423. End If
  424. m_semN = 0
  425. ReDim m_sem(0)
  426. If Not Emb_Enabled() Then
  427. m_warning = "semantic retrieval is not configured; results are lexical only"
  428. ElseIf Len(allowed) = 0 Then
  429. m_strategy = "hybrid"
  430. ElseIf SemanticSearch(kind, queryText, tenantId, allowed) Then
  431. m_strategy = "hybrid"
  432. Else
  433. m_warning = "semantic retrieval is unavailable; results are lexical only"
  434. End If
  435. If m_strategy = "hybrid" Then
  436. Fuse
  437. Else
  438. m_n = m_lexN
  439. ReDim m_ids(m_n)
  440. ReDim m_scores(m_n)
  441. For i = 0 To m_lexN - 1
  442. m_ids(i) = m_lex(i)
  443. m_scores(i) = m_lexScore(i)
  444. Next
  445. End If
  446. ApplyFeedback kind, tenantId
  447. End Sub
  448. ' Usefulness feedback of the tenant on the current revision of each candidate (top 300) adjusts its score.
  449. Private Sub ApplyFeedback(kind, tenantId)
  450. Dim i, j, idList, lim, sql, rs, rows, u, nu, neg, f, t, ts, tf
  451. ReDim m_fb(m_n)
  452. If m_n = 0 Then
  453. Exit Sub
  454. End If
  455. lim = m_n
  456. If lim > 300 Then
  457. lim = 300
  458. End If
  459. idList = ""
  460. For i = 0 To lim - 1
  461. If Api_IsId(m_ids(i)) Then
  462. If Len(idList) > 0 Then
  463. idList = idList & ","
  464. End If
  465. idList = idList & "'" & m_ids(i) & "'"
  466. End If
  467. Next
  468. If Len(idList) = 0 Then
  469. Exit Sub
  470. End If
  471. sql = "SELECT f.target_id, SUM(CASE WHEN f.usefulness = 'useful' THEN 1 ELSE 0 END), SUM(CASE WHEN f.usefulness = 'not_useful' THEN 1 ELSE 0 END), " & _
  472. "SUM(CASE WHEN f.usefulness IN ('incorrect','harmful') THEN 1 ELSE 0 END) FROM feedback f "
  473. If kind = "memory" Then
  474. sql = sql & "JOIN memories m ON m.id = f.target_id AND m.current_revision = f.target_revision "
  475. End If
  476. sql = sql & "WHERE f.tenant_id = ? AND f.target_kind = '" & kind & "' AND f.target_id IN (" & idList & ") GROUP BY f.target_id"
  477. Set rs = DAL().Query(sql, tenantId)
  478. rows = Empty
  479. If Not rs.EOF Then
  480. rows = rs.GetRows()
  481. End If
  482. rs.Close
  483. If IsEmpty(rows) Then
  484. Exit Sub
  485. End If
  486. For j = 0 To UBound(rows, 2)
  487. u = CLng(rows(1, j))
  488. nu = CLng(rows(2, j))
  489. neg = CLng(rows(3, j))
  490. For i = 0 To lim - 1
  491. If m_ids(i) = "" & rows(0, j) Then
  492. f = (1 + 0.1 * Min_(u, 5)) * (0.9 ^ Min_(nu, 5)) * (0.5 ^ Min_(neg, 3))
  493. m_scores(i) = m_scores(i) * f
  494. m_fb(i) = "{""useful"":" & u & ",""not_useful"":" & nu & ",""incorrect_or_harmful"":" & neg & "}"
  495. If neg > u Then
  496. m_demoted = m_demoted + 1
  497. End If
  498. Exit For
  499. End If
  500. Next
  501. Next
  502. ' re-sort (stable insertion sort, descending)
  503. For i = 1 To m_n - 1
  504. t = m_ids(i)
  505. ts = m_scores(i)
  506. tf = m_fb(i)
  507. j = i - 1
  508. Do While j >= 0
  509. If m_scores(j) >= ts Then
  510. Exit Do
  511. End If
  512. m_ids(j + 1) = m_ids(j)
  513. m_scores(j + 1) = m_scores(j)
  514. m_fb(j + 1) = m_fb(j)
  515. j = j - 1
  516. Loop
  517. m_ids(j + 1) = t
  518. m_scores(j + 1) = ts
  519. m_fb(j + 1) = tf
  520. Next
  521. End Sub
  522. Private Function Min_(a, b)
  523. If a < b Then
  524. Min_ = a
  525. Else
  526. Min_ = b
  527. End If
  528. End Function
  529. ' Embeds the query and asks Qdrant for the closest points of this kind in the tenant's allowed namespaces.
  530. Private Function SemanticSearch(kind, queryText, tenantId, allowed)
  531. Dim vecs, body, resp, status, p, q, id, sc, minScore
  532. SemanticSearch = False
  533. If Not Emb_EnsureCollection() Then
  534. Exit Function
  535. End If
  536. vecs = Emb_EmbedTexts(Array(queryText), Emb_Setting("EmbeddingQueryPrefix", ""))
  537. If IsEmpty(vecs) Then
  538. Exit Function
  539. End If
  540. body = "{""query"":" & vecs(0) & ",""limit"":100,""with_payload"":false,""filter"":{""must"":[" & _
  541. "{""key"":""tenant_id"",""match"":{""value"":" & JsonLite_Quote(tenantId) & "}}," & _
  542. "{""key"":""kind"",""match"":{""value"":""" & kind & """}}," & _
  543. "{""key"":""namespace_id"",""match"":{""any"":[" & Replace(allowed, "'", """") & "]}}]}}"
  544. resp = Emb_Http("POST", Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & Emb_Collection() & "/points/query", body, status)
  545. If status <> 200 Then
  546. Exit Function
  547. End If
  548. minScore = Emb_MinScore()
  549. ' {"result":{"points":[{"id":"...","version":n,"score":0.8},...]},...}: scan id/score pairs in order
  550. p = InStr(resp, """id"":""")
  551. Do While p > 0
  552. p = p + 6
  553. q = InStr(p, resp, """")
  554. id = Mid(resp, p, q - p)
  555. p = InStr(q, resp, """score"":")
  556. If p = 0 Then
  557. Exit Do
  558. End If
  559. p = p + 8
  560. q = p
  561. Do While q <= Len(resp)
  562. If InStr("0123456789.-+eE", Mid(resp, q, 1)) = 0 Then
  563. Exit Do
  564. End If
  565. q = q + 1
  566. Loop
  567. sc = CDbl(Replace(Mid(resp, p, q - p), ".", Mid(CStr(1.5), 2, 1)))
  568. If sc >= minScore Then
  569. If m_semN > UBound(m_sem) Then
  570. ReDim Preserve m_sem(m_semN * 2 + 1)
  571. End If
  572. m_sem(m_semN) = id
  573. m_semN = m_semN + 1
  574. End If
  575. p = InStr(q, resp, """id"":""")
  576. Loop
  577. SemanticSearch = True
  578. End Function
  579. ' Reciprocal rank fusion over the top 100 of each list, sorted by fused score (descending)
  580. Private Sub Fuse()
  581. Dim i, j, lim, found, t, ts
  582. m_n = 0
  583. ReDim m_ids(200)
  584. ReDim m_scores(200)
  585. lim = m_lexN
  586. If lim > 100 Then
  587. lim = 100
  588. End If
  589. For i = 0 To lim - 1
  590. m_ids(m_n) = m_lex(i)
  591. m_scores(m_n) = 1 / (EMB_RRF_K + i + 1)
  592. m_n = m_n + 1
  593. Next
  594. lim = m_semN
  595. If lim > 100 Then
  596. lim = 100
  597. End If
  598. For i = 0 To lim - 1
  599. found = -1
  600. For j = 0 To m_n - 1
  601. If m_ids(j) = m_sem(i) Then
  602. found = j
  603. Exit For
  604. End If
  605. Next
  606. If found >= 0 Then
  607. m_scores(found) = m_scores(found) + 1 / (EMB_RRF_K + i + 1)
  608. Else
  609. m_ids(m_n) = m_sem(i)
  610. m_scores(m_n) = 1 / (EMB_RRF_K + i + 1)
  611. m_n = m_n + 1
  612. End If
  613. Next
  614. ' insertion sort, stable for equal scores (lexical order first)
  615. For i = 1 To m_n - 1
  616. t = m_ids(i)
  617. ts = m_scores(i)
  618. j = i - 1
  619. Do While j >= 0
  620. If m_scores(j) >= ts Then
  621. Exit Do
  622. End If
  623. m_ids(j + 1) = m_ids(j)
  624. m_scores(j + 1) = m_scores(j)
  625. j = j - 1
  626. Loop
  627. m_ids(j + 1) = t
  628. m_scores(j + 1) = ts
  629. Next
  630. End Sub
  631. End Class
  632. %>

Powered by TurnKey Linux.