You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

717 lines
28KB

  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. ' EmbeddingTimeoutMs receive timeout per provider/store call inside a web request (default 10000), so a busy
  26. ' provider makes recall/search/context fall back to lexical instead of stalling the request.
  27. ' scripts/embed.asp (CLI, worker) uses 60000.
  28. ' EmbeddingWriteBudgetMs time Emb_AfterWrite may spend indexing after a commit (default 8000): no new batch starts
  29. ' after it, and rows it could not index stay pending for the worker (no attempt is used up).
  30. ' The Qdrant collection is amk_<model>_<dimensions>, so changing the model starts a new collection (run embed reindex).
  31. ' No native object is held across calls: each HTTP call creates and releases its own MSXML2.ServerXMLHTTP.
  32. '=======================================================================================================================
  33. Const EMB_RRF_K = 60
  34. Const EMB_BATCH = 16
  35. Const EMB_MAX_ATTEMPTS = 5
  36. Const EMB_MAX_TEXT = 8000
  37. Dim Emb_LastError, Emb_TimeoutMs, Emb_BudgetMs, Emb_BudgetStart
  38. Emb_LastError = ""
  39. Emb_TimeoutMs = 0 ' 0: EmbeddingTimeoutMs setting; scripts/embed.asp sets 60000
  40. Emb_BudgetMs = 0 ' > 0 only while Emb_AfterWrite runs
  41. Function Emb_CallTimeoutMs()
  42. Dim v
  43. If Emb_TimeoutMs > 0 Then
  44. Emb_CallTimeoutMs = Emb_TimeoutMs
  45. Exit Function
  46. End If
  47. v = Emb_Setting("EmbeddingTimeoutMs", "10000")
  48. If Not IsNumeric(v) Then
  49. v = "10000"
  50. End If
  51. Emb_CallTimeoutMs = CLng(v)
  52. End Function
  53. ' True when Emb_AfterWrite's time budget is spent (Timer wraps at midnight).
  54. Function Emb_OverBudget()
  55. Dim d
  56. Emb_OverBudget = False
  57. If Emb_BudgetMs <= 0 Then
  58. Exit Function
  59. End If
  60. d = Timer - Emb_BudgetStart
  61. If d < 0 Then
  62. d = d + 86400
  63. End If
  64. Emb_OverBudget = (d * 1000 >= Emb_BudgetMs)
  65. End Function
  66. Function Emb_Setting(key, dflt)
  67. Dim v
  68. v = "" & GetAppSetting(key)
  69. If Len(v) = 0 Then
  70. v = dflt
  71. End If
  72. Emb_Setting = v
  73. End Function
  74. Function Emb_Enabled()
  75. Emb_Enabled = (LCase(Emb_Setting("EmbeddingProvider", "none")) = "ollama")
  76. End Function
  77. Function Emb_Model()
  78. Emb_Model = Emb_Setting("EmbeddingModel", "nomic-embed-text")
  79. End Function
  80. Function Emb_Dims()
  81. Emb_Dims = CLng(Emb_Setting("EmbeddingDimensions", "768"))
  82. End Function
  83. Function Emb_MinScore()
  84. Emb_MinScore = CDbl(Replace(Emb_Setting("EmbeddingMinScore", "0.6"), ".", Mid(CStr(1.5), 2, 1)))
  85. End Function
  86. Function Emb_Collection()
  87. Dim m, i, c, out
  88. m = LCase(Emb_Model())
  89. out = ""
  90. For i = 1 To Len(m)
  91. c = Mid(m, i, 1)
  92. If (c >= "a" And c <= "z") Or (c >= "0" And c <= "9") Then
  93. out = out & c
  94. Else
  95. out = out & "_"
  96. End If
  97. Next
  98. Emb_Collection = "amk_" & out & "_" & Emb_Dims()
  99. End Function
  100. ' One HTTP call. Returns the response text; status 0 and Emb_LastError on a transport failure.
  101. Function Emb_Http(method, url, body, ByRef status)
  102. Dim http, text
  103. Emb_Http = ""
  104. status = 0
  105. On Error Resume Next
  106. Set http = Server.CreateObject("MSXML2.ServerXMLHTTP")
  107. http.SetTimeouts 2000, 2000, 10000, Emb_CallTimeoutMs()
  108. http.Open method, url, False
  109. If Len(body) > 0 Then
  110. http.SetRequestHeader "Content-Type", "application/json"
  111. http.Send body
  112. Else
  113. http.Send
  114. End If
  115. If Err.Number <> 0 Then
  116. Emb_LastError = method & " " & url & ": " & Err.Description
  117. Err.Clear
  118. Set http = Nothing
  119. Exit Function
  120. End If
  121. status = http.Status
  122. text = "" & http.ResponseText
  123. Set http = Nothing
  124. On Error GoTo 0
  125. If status < 200 Or status > 299 Then
  126. Emb_LastError = method & " " & url & ": HTTP " & status & " " & Left(text, 200)
  127. End If
  128. Emb_Http = text
  129. End Function
  130. ' Embeds texts (array of strings) with the given task prefix. Returns an array of raw JSON vectors ("[0.1,...]"),
  131. ' one per text, or Empty on failure (Emb_LastError says why).
  132. Function Emb_EmbedTexts(texts, prefix)
  133. Dim body, i, resp, status, p, q, inner, vecs, marker
  134. Emb_EmbedTexts = Empty
  135. body = ""
  136. For i = 0 To UBound(texts)
  137. If i > 0 Then
  138. body = body & ","
  139. End If
  140. body = body & JsonLite_Quote(prefix & Left("" & texts(i), EMB_MAX_TEXT))
  141. Next
  142. body = "{""model"":" & JsonLite_Quote(Emb_Model()) & ",""truncate"":true,""input"":[" & body & "]}"
  143. resp = Emb_Http("POST", Emb_Setting("EmbeddingUrl", "http://ollama:11434") & "/api/embed", body, status)
  144. If status <> 200 Then
  145. Exit Function
  146. End If
  147. ' {"model":"...","embeddings":[[...],[...]],...}: vectors hold only numbers, so "]]" ends the list
  148. marker = """embeddings"":[["
  149. p = InStr(resp, marker)
  150. If p = 0 Then
  151. Emb_LastError = "embedding response without embeddings"
  152. Exit Function
  153. End If
  154. p = p + Len(marker)
  155. q = InStr(p, resp, "]]")
  156. If q = 0 Then
  157. Emb_LastError = "embedding response is truncated"
  158. Exit Function
  159. End If
  160. inner = Replace(Replace(Mid(resp, p, q - p), " ", ""), vbLf, "")
  161. vecs = Split(inner, "],[")
  162. If UBound(vecs) <> UBound(texts) Then
  163. Emb_LastError = "embedding count mismatch (" & (UBound(vecs) + 1) & " for " & (UBound(texts) + 1) & " texts)"
  164. Exit Function
  165. End If
  166. For i = 0 To UBound(vecs)
  167. If UBound(Split(vecs(i), ",")) + 1 <> Emb_Dims() Then
  168. Emb_LastError = "model returned " & (UBound(Split(vecs(i), ",")) + 1) & " dimensions, EmbeddingDimensions is " & Emb_Dims()
  169. Exit Function
  170. End If
  171. vecs(i) = "[" & vecs(i) & "]"
  172. Next
  173. Emb_EmbedTexts = vecs
  174. End Function
  175. ' Creates the collection (cosine, configured size) and keyword payload indexes once per process.
  176. Function Emb_EnsureCollection()
  177. Dim name, base, status, resp, f
  178. name = Emb_Collection()
  179. Emb_EnsureCollection = False
  180. If Application("emb_ok_" & name) = True Then
  181. Emb_EnsureCollection = True
  182. Exit Function
  183. End If
  184. base = Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & name
  185. resp = Emb_Http("GET", base, "", status)
  186. If status = 404 Then
  187. resp = Emb_Http("PUT", base, "{""vectors"":{""size"":" & Emb_Dims() & ",""distance"":""Cosine""}}", status)
  188. If status <> 200 Then
  189. Exit Function
  190. End If
  191. For Each f In Array("tenant_id", "namespace_id", "kind")
  192. resp = Emb_Http("PUT", base & "/index?wait=true", "{""field_name"":""" & f & """,""field_schema"":""keyword""}", status)
  193. Next
  194. ElseIf status <> 200 Then
  195. Exit Function
  196. End If
  197. Application.Lock
  198. Application("emb_ok_" & name) = True
  199. Application.Unlock
  200. Emb_EnsureCollection = True
  201. End Function
  202. '-----------------------------------------------------------------------------------------------------------------------
  203. ' Bookkeeping (call inside the write transaction)
  204. '-----------------------------------------------------------------------------------------------------------------------
  205. Sub Emb_MarkPending(kind, targetId, tenantId, namespaceId, revision)
  206. DAL().Execute "INSERT INTO embedding_index (target_kind, target_id, tenant_id, namespace_id, revision, status, attempts, updated_at) " & _
  207. "VALUES (?, ?, ?, ?, ?, 'pending', 0, ?) ON CONFLICT(target_kind, target_id) DO UPDATE SET status = 'pending', " & _
  208. "revision = excluded.revision, namespace_id = excluded.namespace_id, attempts = 0, error = NULL, updated_at = excluded.updated_at", _
  209. Array(kind, targetId, tenantId, namespaceId, CLng(revision), Api_Now())
  210. End Sub
  211. Sub Emb_MarkDelete(kind, targetId)
  212. DAL().Execute "UPDATE embedding_index SET status = 'delete', updated_at = ? WHERE target_kind = ? AND target_id = ?", Array(Api_Now(), kind, targetId)
  213. End Sub
  214. ' Old revision's chunks of a document leave the vector index
  215. Sub Emb_MarkDeleteChunks(documentId, revision)
  216. DAL().Execute "UPDATE embedding_index SET status = 'delete', updated_at = ? WHERE target_kind = 'chunk' AND target_id IN " & _
  217. "(SELECT id FROM chunks WHERE document_id = ? AND document_revision = ?)", Array(Api_Now(), documentId, CLng(revision))
  218. End Sub
  219. ' After commit: index a bounded batch for this tenant. Never raises; a failure leaves rows pending/failed for later.
  220. Sub Emb_AfterWrite(tenantId, maxItems)
  221. Dim n
  222. If Not Emb_Enabled() Then
  223. Exit Sub
  224. End If
  225. Dim b
  226. b = Emb_Setting("EmbeddingWriteBudgetMs", "8000")
  227. If Not IsNumeric(b) Then
  228. b = "8000"
  229. End If
  230. Emb_BudgetStart = Timer
  231. Emb_BudgetMs = CLng(b)
  232. On Error Resume Next
  233. n = Emb_ProcessPending(tenantId, maxItems)
  234. If Err.Number <> 0 Then
  235. Emb_LastError = "process: " & Err.Description
  236. Err.Clear
  237. End If
  238. On Error GoTo 0
  239. Emb_BudgetMs = 0
  240. End Sub
  241. ' Processes deletions and up to maxItems pending/failed rows (tenantId "" = all tenants). Returns rows indexed.
  242. Function Emb_ProcessPending(tenantId, maxItems)
  243. Dim rs, sql, ids, n, idList, status, resp, rows, i, j, k, cnt, texts(), kinds(), tids(), tens(), nss(), revs(), text, rev, ok
  244. Dim batchStart, batchEnd, bt(), vecs, body, done, ts
  245. Emb_ProcessPending = 0
  246. If Not Emb_Enabled() Then
  247. Exit Function
  248. End If
  249. If Not Emb_EnsureCollection() Then
  250. Exit Function
  251. End If
  252. '--- deletions ------------------------------------------------------------------------------------------------
  253. sql = "SELECT target_id FROM embedding_index WHERE status = 'delete'"
  254. If Len(tenantId) > 0 Then
  255. sql = sql & " AND tenant_id = ?"
  256. Set rs = DAL().Query(sql & " LIMIT 256", tenantId)
  257. Else
  258. Set rs = DAL().Query(sql & " LIMIT 256", Empty)
  259. End If
  260. idList = ""
  261. ids = ""
  262. Do While Not rs.EOF
  263. If Api_IsId("" & rs(0)) Then
  264. If Len(idList) > 0 Then
  265. idList = idList & ","
  266. ids = ids & ","
  267. End If
  268. idList = idList & "'" & rs(0) & "'"
  269. ids = ids & """" & rs(0) & """"
  270. End If
  271. rs.MoveNext
  272. Loop
  273. rs.Close
  274. If Len(idList) > 0 Then
  275. resp = Emb_Http("POST", Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & Emb_Collection() & "/points/delete?wait=true", _
  276. "{""points"":[" & ids & "]}", status)
  277. If status = 200 Then
  278. DAL().Execute "DELETE FROM embedding_index WHERE status = 'delete' AND target_id IN (" & idList & ")", Empty
  279. Else
  280. Exit Function
  281. End If
  282. End If
  283. '--- pending and retryable failures ---------------------------------------------------------------------------
  284. 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 & "))"
  285. If Len(tenantId) > 0 Then
  286. Set rs = DAL().Query(sql & " AND tenant_id = ? ORDER BY updated_at LIMIT " & CLng(maxItems), tenantId)
  287. Else
  288. Set rs = DAL().Query(sql & " ORDER BY updated_at LIMIT " & CLng(maxItems), Empty)
  289. End If
  290. rows = Empty
  291. If Not rs.EOF Then
  292. rows = rs.GetRows()
  293. End If
  294. rs.Close
  295. If IsEmpty(rows) Then
  296. Exit Function
  297. End If
  298. ' Load the text to embed for every row (each query closed before the next)
  299. cnt = UBound(rows, 2) + 1
  300. ReDim texts(cnt - 1)
  301. ReDim kinds(cnt - 1)
  302. ReDim tids(cnt - 1)
  303. ReDim tens(cnt - 1)
  304. ReDim nss(cnt - 1)
  305. ReDim revs(cnt - 1)
  306. k = 0
  307. For i = 0 To cnt - 1
  308. text = ""
  309. rev = 0
  310. If "" & rows(0, i) = "memory" Then
  311. Set rs = DAL().Query("SELECT r.title, r.content, m.current_revision, m.namespace_id FROM memories m JOIN memory_revisions r " & _
  312. "ON r.memory_id = m.id AND r.revision = m.current_revision WHERE m.id = ?", "" & rows(1, i))
  313. If Not rs.EOF Then
  314. text = "" & rs(0) & vbLf & rs(1)
  315. rev = CLng(rs(2))
  316. rows(3, i) = "" & rs(3)
  317. End If
  318. rs.Close
  319. Else
  320. Set rs = DAL().Query("SELECT content, document_revision FROM chunks WHERE id = ?", "" & rows(1, i))
  321. If Not rs.EOF Then
  322. text = "" & rs(0)
  323. rev = CLng(rs(1))
  324. End If
  325. rs.Close
  326. End If
  327. If Len(text) = 0 Then
  328. ' the source is gone: drop the row (and any point)
  329. 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))
  330. Else
  331. texts(k) = text
  332. kinds(k) = "" & rows(0, i)
  333. tids(k) = "" & rows(1, i)
  334. tens(k) = "" & rows(2, i)
  335. nss(k) = "" & rows(3, i)
  336. revs(k) = rev
  337. k = k + 1
  338. End If
  339. Next
  340. done = 0
  341. batchStart = 0
  342. Do While batchStart < k
  343. If batchStart > 0 And Emb_OverBudget() Then
  344. Exit Do ' request time budget spent: the worker indexes the rest
  345. End If
  346. batchEnd = batchStart + EMB_BATCH - 1
  347. If batchEnd > k - 1 Then
  348. batchEnd = k - 1
  349. End If
  350. ReDim bt(batchEnd - batchStart)
  351. For j = batchStart To batchEnd
  352. bt(j - batchStart) = texts(j)
  353. Next
  354. vecs = Emb_EmbedTexts(bt, Emb_Setting("EmbeddingDocumentPrefix", ""))
  355. ok = Not IsEmpty(vecs)
  356. If ok Then
  357. body = ""
  358. For j = batchStart To batchEnd
  359. If j > batchStart Then
  360. body = body & ","
  361. End If
  362. body = body & "{""id"":""" & tids(j) & """,""vector"":" & vecs(j - batchStart) & ",""payload"":{""tenant_id"":""" & tens(j) & _
  363. """,""namespace_id"":""" & nss(j) & """,""kind"":""" & kinds(j) & """,""revision"":" & revs(j) & "}}"
  364. Next
  365. resp = Emb_Http("PUT", Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & Emb_Collection() & "/points?wait=true", _
  366. "{""points"":[" & body & "]}", status)
  367. ok = (status = 200)
  368. End If
  369. If Not ok And Emb_BudgetMs > 0 Then
  370. Exit Do ' inside a request: leave the rows pending for the worker, do not use up their attempts
  371. End If
  372. ts = Api_Now()
  373. For j = batchStart To batchEnd
  374. If ok Then
  375. DAL().Execute "UPDATE embedding_index SET status = 'indexed', model = ?, dimensions = ?, revision = ?, attempts = 0, error = NULL, updated_at = ? " & _
  376. "WHERE target_kind = ? AND target_id = ? AND status <> 'delete'", Array(Emb_Model(), Emb_Dims(), revs(j), ts, kinds(j), tids(j))
  377. done = done + 1
  378. Else
  379. DAL().Execute "UPDATE embedding_index SET status = 'failed', attempts = attempts + 1, error = ?, updated_at = ? WHERE target_kind = ? AND target_id = ?", _
  380. Array(Left(Emb_LastError, 500), ts, kinds(j), tids(j))
  381. End If
  382. Next
  383. If Not ok Then
  384. Exit Do ' provider or store down: leave the rest for later
  385. End If
  386. batchStart = batchEnd + 1
  387. Loop
  388. Emb_ProcessPending = done
  389. End Function
  390. ' Removes a whole tenant from the vector store and the bookkeeping (provision purge). Best effort for the store.
  391. Sub Emb_DeleteTenant(tenantId)
  392. Dim status, resp
  393. If Emb_Enabled() Then
  394. If Emb_EnsureCollection() Then
  395. resp = Emb_Http("POST", Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & Emb_Collection() & "/points/delete?wait=true", _
  396. "{""filter"":{""must"":[{""key"":""tenant_id"",""match"":{""value"":" & JsonLite_Quote(tenantId) & "}}]}}", status)
  397. End If
  398. End If
  399. DAL().Execute "DELETE FROM embedding_index WHERE tenant_id = ?", tenantId
  400. End Sub
  401. '-----------------------------------------------------------------------------------------------------------------------
  402. ' Hybrid ranking. Lexical (FTS5/bm25) and, when configured, semantic (Qdrant cosine) candidate lists are merged with
  403. ' reciprocal rank fusion (raw scores of the two engines are not comparable). Without semantic retrieval the order and
  404. ' scores are the lexical ones (negated bm25). Callers still apply the canonical filters to every id.
  405. ' Set r = New Ranker_Class : r.Run "memory"|"chunk", ftsQuery, queryText, tenantId, allowedSqlList
  406. ' r.Count, r.IdAt(i), r.ScoreAt(i), r.Strategy ("lexical"|"hybrid"), r.Warning ("" or a sentence)
  407. ' Feedback (POST /feedback) on the CURRENT revision of a result then scales its score: x(1 + 0.1 per useful, max 5),
  408. ' x0.9 per not_useful (max 5), x0.5 per incorrect/harmful (max 3), and the list is re-sorted.
  409. ' r.FeedbackAt(i) ("" or a JSON object of counts), r.Demoted (results with more negative than useful ratings)
  410. '-----------------------------------------------------------------------------------------------------------------------
  411. Class Ranker_Class
  412. Private m_ids(), m_scores(), m_n, m_strategy, m_warning, m_fb(), m_demoted
  413. Private m_lex(), m_lexScore(), m_lexN, m_sem(), m_semN
  414. Private Sub Class_Initialize()
  415. m_n = 0
  416. ReDim m_ids(0)
  417. ReDim m_scores(0)
  418. m_strategy = "lexical"
  419. m_warning = ""
  420. m_demoted = 0
  421. ReDim m_fb(0)
  422. End Sub
  423. Public Function FeedbackAt(i)
  424. FeedbackAt = "" & m_fb(i)
  425. End Function
  426. Public Property Get Demoted()
  427. Demoted = m_demoted
  428. End Property
  429. Public Property Get Count()
  430. Count = m_n
  431. End Property
  432. Public Function IdAt(i)
  433. IdAt = m_ids(i)
  434. End Function
  435. Public Function ScoreAt(i)
  436. ScoreAt = m_scores(i)
  437. End Function
  438. Public Property Get Strategy()
  439. Strategy = m_strategy
  440. End Property
  441. Public Property Get Warning()
  442. Warning = m_warning
  443. End Property
  444. Public Sub Run(kind, fts, queryText, tenantId, allowed)
  445. Dim rs, tbl, col, i
  446. If kind = "memory" Then
  447. tbl = "memories_fts"
  448. col = "memory_id"
  449. Else
  450. tbl = "chunks_fts"
  451. col = "chunk_id"
  452. End If
  453. m_lexN = 0
  454. ReDim m_lex(63)
  455. ReDim m_lexScore(63)
  456. If Len(fts) > 0 Then
  457. 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))
  458. Do While Not rs.EOF
  459. If m_lexN > UBound(m_lex) Then
  460. ReDim Preserve m_lex(m_lexN * 2)
  461. ReDim Preserve m_lexScore(m_lexN * 2)
  462. End If
  463. m_lex(m_lexN) = "" & rs(0)
  464. m_lexScore(m_lexN) = -CDbl(rs(1))
  465. m_lexN = m_lexN + 1
  466. rs.MoveNext
  467. Loop
  468. rs.Close
  469. End If
  470. m_semN = 0
  471. ReDim m_sem(0)
  472. If Not Emb_Enabled() Then
  473. m_warning = "semantic retrieval is not configured; results are lexical only"
  474. ElseIf Len(allowed) = 0 Then
  475. m_strategy = "hybrid"
  476. ElseIf SemanticSearch(kind, queryText, tenantId, allowed) Then
  477. m_strategy = "hybrid"
  478. Else
  479. m_warning = "semantic retrieval is unavailable; results are lexical only"
  480. End If
  481. If m_strategy = "hybrid" Then
  482. Fuse
  483. Else
  484. m_n = m_lexN
  485. ReDim m_ids(m_n)
  486. ReDim m_scores(m_n)
  487. For i = 0 To m_lexN - 1
  488. m_ids(i) = m_lex(i)
  489. m_scores(i) = m_lexScore(i)
  490. Next
  491. End If
  492. ApplyFeedback kind, tenantId
  493. End Sub
  494. ' Usefulness feedback of the tenant on the current revision of each candidate (top 300) adjusts its score.
  495. Private Sub ApplyFeedback(kind, tenantId)
  496. Dim i, j, idList, lim, sql, rs, rows, u, nu, neg, f, t, ts, tf
  497. ReDim m_fb(m_n)
  498. If m_n = 0 Then
  499. Exit Sub
  500. End If
  501. lim = m_n
  502. If lim > 300 Then
  503. lim = 300
  504. End If
  505. idList = ""
  506. For i = 0 To lim - 1
  507. If Api_IsId(m_ids(i)) Then
  508. If Len(idList) > 0 Then
  509. idList = idList & ","
  510. End If
  511. idList = idList & "'" & m_ids(i) & "'"
  512. End If
  513. Next
  514. If Len(idList) = 0 Then
  515. Exit Sub
  516. End If
  517. 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), " & _
  518. "SUM(CASE WHEN f.usefulness IN ('incorrect','harmful') THEN 1 ELSE 0 END) FROM feedback f "
  519. If kind = "memory" Then
  520. sql = sql & "JOIN memories m ON m.id = f.target_id AND m.current_revision = f.target_revision "
  521. End If
  522. sql = sql & "WHERE f.tenant_id = ? AND f.target_kind = '" & kind & "' AND f.target_id IN (" & idList & ") GROUP BY f.target_id"
  523. Set rs = DAL().Query(sql, tenantId)
  524. rows = Empty
  525. If Not rs.EOF Then
  526. rows = rs.GetRows()
  527. End If
  528. rs.Close
  529. If IsEmpty(rows) Then
  530. Exit Sub
  531. End If
  532. For j = 0 To UBound(rows, 2)
  533. u = CLng(rows(1, j))
  534. nu = CLng(rows(2, j))
  535. neg = CLng(rows(3, j))
  536. For i = 0 To lim - 1
  537. If m_ids(i) = "" & rows(0, j) Then
  538. f = (1 + 0.1 * Min_(u, 5)) * (0.9 ^ Min_(nu, 5)) * (0.5 ^ Min_(neg, 3))
  539. m_scores(i) = m_scores(i) * f
  540. m_fb(i) = "{""useful"":" & u & ",""not_useful"":" & nu & ",""incorrect_or_harmful"":" & neg & "}"
  541. If neg > u Then
  542. m_demoted = m_demoted + 1
  543. End If
  544. Exit For
  545. End If
  546. Next
  547. Next
  548. ' re-sort (stable insertion sort, descending)
  549. For i = 1 To m_n - 1
  550. t = m_ids(i)
  551. ts = m_scores(i)
  552. tf = m_fb(i)
  553. j = i - 1
  554. Do While j >= 0
  555. If m_scores(j) >= ts Then
  556. Exit Do
  557. End If
  558. m_ids(j + 1) = m_ids(j)
  559. m_scores(j + 1) = m_scores(j)
  560. m_fb(j + 1) = m_fb(j)
  561. j = j - 1
  562. Loop
  563. m_ids(j + 1) = t
  564. m_scores(j + 1) = ts
  565. m_fb(j + 1) = tf
  566. Next
  567. End Sub
  568. Private Function Min_(a, b)
  569. If a < b Then
  570. Min_ = a
  571. Else
  572. Min_ = b
  573. End If
  574. End Function
  575. ' Embeds the query and asks Qdrant for the closest points of this kind in the tenant's allowed namespaces.
  576. Private Function SemanticSearch(kind, queryText, tenantId, allowed)
  577. Dim vecs, body, resp, status, p, q, id, sc, minScore
  578. SemanticSearch = False
  579. If Not Emb_EnsureCollection() Then
  580. Exit Function
  581. End If
  582. vecs = Emb_EmbedTexts(Array(queryText), Emb_Setting("EmbeddingQueryPrefix", ""))
  583. If IsEmpty(vecs) Then
  584. Exit Function
  585. End If
  586. body = "{""query"":" & vecs(0) & ",""limit"":100,""with_payload"":false,""filter"":{""must"":[" & _
  587. "{""key"":""tenant_id"",""match"":{""value"":" & JsonLite_Quote(tenantId) & "}}," & _
  588. "{""key"":""kind"",""match"":{""value"":""" & kind & """}}," & _
  589. "{""key"":""namespace_id"",""match"":{""any"":[" & Replace(allowed, "'", """") & "]}}]}}"
  590. resp = Emb_Http("POST", Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & Emb_Collection() & "/points/query", body, status)
  591. If status <> 200 Then
  592. Exit Function
  593. End If
  594. minScore = Emb_MinScore()
  595. ' {"result":{"points":[{"id":"...","version":n,"score":0.8},...]},...}: scan id/score pairs in order
  596. p = InStr(resp, """id"":""")
  597. Do While p > 0
  598. p = p + 6
  599. q = InStr(p, resp, """")
  600. id = Mid(resp, p, q - p)
  601. p = InStr(q, resp, """score"":")
  602. If p = 0 Then
  603. Exit Do
  604. End If
  605. p = p + 8
  606. q = p
  607. Do While q <= Len(resp)
  608. If InStr("0123456789.-+eE", Mid(resp, q, 1)) = 0 Then
  609. Exit Do
  610. End If
  611. q = q + 1
  612. Loop
  613. sc = CDbl(Replace(Mid(resp, p, q - p), ".", Mid(CStr(1.5), 2, 1)))
  614. If sc >= minScore Then
  615. If m_semN > UBound(m_sem) Then
  616. ReDim Preserve m_sem(m_semN * 2 + 1)
  617. End If
  618. m_sem(m_semN) = id
  619. m_semN = m_semN + 1
  620. End If
  621. p = InStr(q, resp, """id"":""")
  622. Loop
  623. SemanticSearch = True
  624. End Function
  625. ' Reciprocal rank fusion over the top 100 of each list, sorted by fused score (descending)
  626. Private Sub Fuse()
  627. Dim i, j, lim, found, t, ts
  628. m_n = 0
  629. ReDim m_ids(200)
  630. ReDim m_scores(200)
  631. lim = m_lexN
  632. If lim > 100 Then
  633. lim = 100
  634. End If
  635. For i = 0 To lim - 1
  636. m_ids(m_n) = m_lex(i)
  637. m_scores(m_n) = 1 / (EMB_RRF_K + i + 1)
  638. m_n = m_n + 1
  639. Next
  640. lim = m_semN
  641. If lim > 100 Then
  642. lim = 100
  643. End If
  644. For i = 0 To lim - 1
  645. found = -1
  646. For j = 0 To m_n - 1
  647. If m_ids(j) = m_sem(i) Then
  648. found = j
  649. Exit For
  650. End If
  651. Next
  652. If found >= 0 Then
  653. m_scores(found) = m_scores(found) + 1 / (EMB_RRF_K + i + 1)
  654. Else
  655. m_ids(m_n) = m_sem(i)
  656. m_scores(m_n) = 1 / (EMB_RRF_K + i + 1)
  657. m_n = m_n + 1
  658. End If
  659. Next
  660. ' insertion sort, stable for equal scores (lexical order first)
  661. For i = 1 To m_n - 1
  662. t = m_ids(i)
  663. ts = m_scores(i)
  664. j = i - 1
  665. Do While j >= 0
  666. If m_scores(j) >= ts Then
  667. Exit Do
  668. End If
  669. m_ids(j + 1) = m_ids(j)
  670. m_scores(j + 1) = m_scores(j)
  671. j = j - 1
  672. Loop
  673. m_ids(j + 1) = t
  674. m_scores(j + 1) = ts
  675. Next
  676. End Sub
  677. End Class
  678. %>

Powered by TurnKey Linux.