<% '======================================================================================================================= ' Semantic retrieval: embeddings (Ollama) + vector index (Qdrant) + hybrid ranking (spec FR-008, FR-009, section 10). ' ' SQLite is the source of truth. Table embedding_index records, per memory/chunk, what the vector store should hold ' (status pending | indexed | failed | delete, model, dimensions, revision). Write paths only mark rows inside their ' transaction (Emb_MarkPending / Emb_MarkDelete*); after commit they call Emb_AfterWrite, which indexes a bounded batch ' and never fails the request. scripts\embed.cmd processes everything left over or rebuilds the index. ' ' Vectors are never parsed in VBScript: Ollama's JSON array text is passed straight into the Qdrant request body. ' Qdrant points use the memory/chunk id as point id and carry tenant_id, namespace_id, kind and revision as payload. ' Search filters by tenant, kind and the caller's readable namespaces in Qdrant, and callers then re-check every hit ' against the canonical tables (namespace, lifecycle, validity, current revision), as for lexical hits. ' ' Settings (web.config appSettings): ' EmbeddingProvider ollama | none (default none: lexical only, with a warning) ' EmbeddingUrl http://ollama:11434 ' EmbeddingModel nomic-embed-text ' EmbeddingDimensions 768 ' EmbeddingDocumentPrefix "search_document: " (model-specific task prefixes; empty for models without them) ' EmbeddingQueryPrefix "search_query: " ' EmbeddingMinScore cosine similarity below which a semantic hit is ignored (default 0.6; model-specific: for ' nomic-embed-text relevant pairs scored 0.61-0.67, unrelated ones up to 0.58) ' VectorStoreUrl http://qdrant:6333 ' The Qdrant collection is amk__, so changing the model starts a new collection (run embed reindex). ' No native object is held across calls: each HTTP call creates and releases its own MSXML2.ServerXMLHTTP. '======================================================================================================================= Const EMB_RRF_K = 60 Const EMB_BATCH = 16 Const EMB_MAX_ATTEMPTS = 5 Const EMB_MAX_TEXT = 8000 Dim Emb_LastError Emb_LastError = "" Function Emb_Setting(key, dflt) Dim v v = "" & GetAppSetting(key) If Len(v) = 0 Then v = dflt End If Emb_Setting = v End Function Function Emb_Enabled() Emb_Enabled = (LCase(Emb_Setting("EmbeddingProvider", "none")) = "ollama") End Function Function Emb_Model() Emb_Model = Emb_Setting("EmbeddingModel", "nomic-embed-text") End Function Function Emb_Dims() Emb_Dims = CLng(Emb_Setting("EmbeddingDimensions", "768")) End Function Function Emb_MinScore() Emb_MinScore = CDbl(Replace(Emb_Setting("EmbeddingMinScore", "0.6"), ".", Mid(CStr(1.5), 2, 1))) End Function Function Emb_Collection() Dim m, i, c, out m = LCase(Emb_Model()) out = "" For i = 1 To Len(m) c = Mid(m, i, 1) If (c >= "a" And c <= "z") Or (c >= "0" And c <= "9") Then out = out & c Else out = out & "_" End If Next Emb_Collection = "amk_" & out & "_" & Emb_Dims() End Function ' One HTTP call. Returns the response text; status 0 and Emb_LastError on a transport failure. Function Emb_Http(method, url, body, ByRef status) Dim http, text Emb_Http = "" status = 0 On Error Resume Next Set http = Server.CreateObject("MSXML2.ServerXMLHTTP") http.SetTimeouts 2000, 2000, 10000, 60000 http.Open method, url, False If Len(body) > 0 Then http.SetRequestHeader "Content-Type", "application/json" http.Send body Else http.Send End If If Err.Number <> 0 Then Emb_LastError = method & " " & url & ": " & Err.Description Err.Clear Set http = Nothing Exit Function End If status = http.Status text = "" & http.ResponseText Set http = Nothing On Error GoTo 0 If status < 200 Or status > 299 Then Emb_LastError = method & " " & url & ": HTTP " & status & " " & Left(text, 200) End If Emb_Http = text End Function ' Embeds texts (array of strings) with the given task prefix. Returns an array of raw JSON vectors ("[0.1,...]"), ' one per text, or Empty on failure (Emb_LastError says why). Function Emb_EmbedTexts(texts, prefix) Dim body, i, resp, status, p, q, inner, vecs, marker Emb_EmbedTexts = Empty body = "" For i = 0 To UBound(texts) If i > 0 Then body = body & "," End If body = body & JsonLite_Quote(prefix & Left("" & texts(i), EMB_MAX_TEXT)) Next body = "{""model"":" & JsonLite_Quote(Emb_Model()) & ",""truncate"":true,""input"":[" & body & "]}" resp = Emb_Http("POST", Emb_Setting("EmbeddingUrl", "http://ollama:11434") & "/api/embed", body, status) If status <> 200 Then Exit Function End If ' {"model":"...","embeddings":[[...],[...]],...}: vectors hold only numbers, so "]]" ends the list marker = """embeddings"":[[" p = InStr(resp, marker) If p = 0 Then Emb_LastError = "embedding response without embeddings" Exit Function End If p = p + Len(marker) q = InStr(p, resp, "]]") If q = 0 Then Emb_LastError = "embedding response is truncated" Exit Function End If inner = Replace(Replace(Mid(resp, p, q - p), " ", ""), vbLf, "") vecs = Split(inner, "],[") If UBound(vecs) <> UBound(texts) Then Emb_LastError = "embedding count mismatch (" & (UBound(vecs) + 1) & " for " & (UBound(texts) + 1) & " texts)" Exit Function End If For i = 0 To UBound(vecs) If UBound(Split(vecs(i), ",")) + 1 <> Emb_Dims() Then Emb_LastError = "model returned " & (UBound(Split(vecs(i), ",")) + 1) & " dimensions, EmbeddingDimensions is " & Emb_Dims() Exit Function End If vecs(i) = "[" & vecs(i) & "]" Next Emb_EmbedTexts = vecs End Function ' Creates the collection (cosine, configured size) and keyword payload indexes once per process. Function Emb_EnsureCollection() Dim name, base, status, resp, f name = Emb_Collection() Emb_EnsureCollection = False If Application("emb_ok_" & name) = True Then Emb_EnsureCollection = True Exit Function End If base = Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & name resp = Emb_Http("GET", base, "", status) If status = 404 Then resp = Emb_Http("PUT", base, "{""vectors"":{""size"":" & Emb_Dims() & ",""distance"":""Cosine""}}", status) If status <> 200 Then Exit Function End If For Each f In Array("tenant_id", "namespace_id", "kind") resp = Emb_Http("PUT", base & "/index?wait=true", "{""field_name"":""" & f & """,""field_schema"":""keyword""}", status) Next ElseIf status <> 200 Then Exit Function End If Application.Lock Application("emb_ok_" & name) = True Application.Unlock Emb_EnsureCollection = True End Function '----------------------------------------------------------------------------------------------------------------------- ' Bookkeeping (call inside the write transaction) '----------------------------------------------------------------------------------------------------------------------- Sub Emb_MarkPending(kind, targetId, tenantId, namespaceId, revision) DAL().Execute "INSERT INTO embedding_index (target_kind, target_id, tenant_id, namespace_id, revision, status, attempts, updated_at) " & _ "VALUES (?, ?, ?, ?, ?, 'pending', 0, ?) ON CONFLICT(target_kind, target_id) DO UPDATE SET status = 'pending', " & _ "revision = excluded.revision, namespace_id = excluded.namespace_id, attempts = 0, error = NULL, updated_at = excluded.updated_at", _ Array(kind, targetId, tenantId, namespaceId, CLng(revision), Api_Now()) End Sub Sub Emb_MarkDelete(kind, targetId) DAL().Execute "UPDATE embedding_index SET status = 'delete', updated_at = ? WHERE target_kind = ? AND target_id = ?", Array(Api_Now(), kind, targetId) End Sub ' Old revision's chunks of a document leave the vector index Sub Emb_MarkDeleteChunks(documentId, revision) DAL().Execute "UPDATE embedding_index SET status = 'delete', updated_at = ? WHERE target_kind = 'chunk' AND target_id IN " & _ "(SELECT id FROM chunks WHERE document_id = ? AND document_revision = ?)", Array(Api_Now(), documentId, CLng(revision)) End Sub ' After commit: index a bounded batch for this tenant. Never raises; a failure leaves rows pending/failed for later. Sub Emb_AfterWrite(tenantId, maxItems) Dim n If Not Emb_Enabled() Then Exit Sub End If On Error Resume Next n = Emb_ProcessPending(tenantId, maxItems) If Err.Number <> 0 Then Emb_LastError = "process: " & Err.Description Err.Clear End If On Error GoTo 0 End Sub ' Processes deletions and up to maxItems pending/failed rows (tenantId "" = all tenants). Returns rows indexed. Function Emb_ProcessPending(tenantId, maxItems) Dim rs, sql, ids, n, idList, status, resp, rows, i, j, k, cnt, texts(), kinds(), tids(), tens(), nss(), revs(), text, rev, ok Dim batchStart, batchEnd, bt(), vecs, body, done, ts Emb_ProcessPending = 0 If Not Emb_Enabled() Then Exit Function End If If Not Emb_EnsureCollection() Then Exit Function End If '--- deletions ------------------------------------------------------------------------------------------------ sql = "SELECT target_id FROM embedding_index WHERE status = 'delete'" If Len(tenantId) > 0 Then sql = sql & " AND tenant_id = ?" Set rs = DAL().Query(sql & " LIMIT 256", tenantId) Else Set rs = DAL().Query(sql & " LIMIT 256", Empty) End If idList = "" ids = "" Do While Not rs.EOF If Api_IsId("" & rs(0)) Then If Len(idList) > 0 Then idList = idList & "," ids = ids & "," End If idList = idList & "'" & rs(0) & "'" ids = ids & """" & rs(0) & """" End If rs.MoveNext Loop rs.Close If Len(idList) > 0 Then resp = Emb_Http("POST", Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & Emb_Collection() & "/points/delete?wait=true", _ "{""points"":[" & ids & "]}", status) If status = 200 Then DAL().Execute "DELETE FROM embedding_index WHERE status = 'delete' AND target_id IN (" & idList & ")", Empty Else Exit Function End If End If '--- pending and retryable failures --------------------------------------------------------------------------- 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 & "))" If Len(tenantId) > 0 Then Set rs = DAL().Query(sql & " AND tenant_id = ? ORDER BY updated_at LIMIT " & CLng(maxItems), tenantId) Else Set rs = DAL().Query(sql & " ORDER BY updated_at LIMIT " & CLng(maxItems), Empty) End If rows = Empty If Not rs.EOF Then rows = rs.GetRows() End If rs.Close If IsEmpty(rows) Then Exit Function End If ' Load the text to embed for every row (each query closed before the next) cnt = UBound(rows, 2) + 1 ReDim texts(cnt - 1) ReDim kinds(cnt - 1) ReDim tids(cnt - 1) ReDim tens(cnt - 1) ReDim nss(cnt - 1) ReDim revs(cnt - 1) k = 0 For i = 0 To cnt - 1 text = "" rev = 0 If "" & rows(0, i) = "memory" Then Set rs = DAL().Query("SELECT r.title, r.content, m.current_revision, m.namespace_id FROM memories m JOIN memory_revisions r " & _ "ON r.memory_id = m.id AND r.revision = m.current_revision WHERE m.id = ?", "" & rows(1, i)) If Not rs.EOF Then text = "" & rs(0) & vbLf & rs(1) rev = CLng(rs(2)) rows(3, i) = "" & rs(3) End If rs.Close Else Set rs = DAL().Query("SELECT content, document_revision FROM chunks WHERE id = ?", "" & rows(1, i)) If Not rs.EOF Then text = "" & rs(0) rev = CLng(rs(1)) End If rs.Close End If If Len(text) = 0 Then ' the source is gone: drop the row (and any point) 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)) Else texts(k) = text kinds(k) = "" & rows(0, i) tids(k) = "" & rows(1, i) tens(k) = "" & rows(2, i) nss(k) = "" & rows(3, i) revs(k) = rev k = k + 1 End If Next done = 0 batchStart = 0 Do While batchStart < k batchEnd = batchStart + EMB_BATCH - 1 If batchEnd > k - 1 Then batchEnd = k - 1 End If ReDim bt(batchEnd - batchStart) For j = batchStart To batchEnd bt(j - batchStart) = texts(j) Next vecs = Emb_EmbedTexts(bt, Emb_Setting("EmbeddingDocumentPrefix", "")) ok = Not IsEmpty(vecs) If ok Then body = "" For j = batchStart To batchEnd If j > batchStart Then body = body & "," End If body = body & "{""id"":""" & tids(j) & """,""vector"":" & vecs(j - batchStart) & ",""payload"":{""tenant_id"":""" & tens(j) & _ """,""namespace_id"":""" & nss(j) & """,""kind"":""" & kinds(j) & """,""revision"":" & revs(j) & "}}" Next resp = Emb_Http("PUT", Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & Emb_Collection() & "/points?wait=true", _ "{""points"":[" & body & "]}", status) ok = (status = 200) End If ts = Api_Now() For j = batchStart To batchEnd If ok Then DAL().Execute "UPDATE embedding_index SET status = 'indexed', model = ?, dimensions = ?, revision = ?, attempts = 0, error = NULL, updated_at = ? " & _ "WHERE target_kind = ? AND target_id = ? AND status <> 'delete'", Array(Emb_Model(), Emb_Dims(), revs(j), ts, kinds(j), tids(j)) done = done + 1 Else DAL().Execute "UPDATE embedding_index SET status = 'failed', attempts = attempts + 1, error = ?, updated_at = ? WHERE target_kind = ? AND target_id = ?", _ Array(Left(Emb_LastError, 500), ts, kinds(j), tids(j)) End If Next If Not ok Then Exit Do ' provider or store down: leave the rest for later End If batchStart = batchEnd + 1 Loop Emb_ProcessPending = done End Function ' Removes a whole tenant from the vector store and the bookkeeping (provision purge). Best effort for the store. Sub Emb_DeleteTenant(tenantId) Dim status, resp If Emb_Enabled() Then If Emb_EnsureCollection() Then resp = Emb_Http("POST", Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & Emb_Collection() & "/points/delete?wait=true", _ "{""filter"":{""must"":[{""key"":""tenant_id"",""match"":{""value"":" & JsonLite_Quote(tenantId) & "}}]}}", status) End If End If DAL().Execute "DELETE FROM embedding_index WHERE tenant_id = ?", tenantId End Sub '----------------------------------------------------------------------------------------------------------------------- ' Hybrid ranking. Lexical (FTS5/bm25) and, when configured, semantic (Qdrant cosine) candidate lists are merged with ' reciprocal rank fusion (raw scores of the two engines are not comparable). Without semantic retrieval the order and ' scores are the lexical ones (negated bm25). Callers still apply the canonical filters to every id. ' Set r = New Ranker_Class : r.Run "memory"|"chunk", ftsQuery, queryText, tenantId, allowedSqlList ' r.Count, r.IdAt(i), r.ScoreAt(i), r.Strategy ("lexical"|"hybrid"), r.Warning ("" or a sentence) '----------------------------------------------------------------------------------------------------------------------- Class Ranker_Class Private m_ids(), m_scores(), m_n, m_strategy, m_warning Private m_lex(), m_lexScore(), m_lexN, m_sem(), m_semN Private Sub Class_Initialize() m_n = 0 ReDim m_ids(0) ReDim m_scores(0) m_strategy = "lexical" m_warning = "" End Sub Public Property Get Count() Count = m_n End Property Public Function IdAt(i) IdAt = m_ids(i) End Function Public Function ScoreAt(i) ScoreAt = m_scores(i) End Function Public Property Get Strategy() Strategy = m_strategy End Property Public Property Get Warning() Warning = m_warning End Property Public Sub Run(kind, fts, queryText, tenantId, allowed) Dim rs, tbl, col, i If kind = "memory" Then tbl = "memories_fts" col = "memory_id" Else tbl = "chunks_fts" col = "chunk_id" End If m_lexN = 0 ReDim m_lex(63) ReDim m_lexScore(63) If Len(fts) > 0 Then 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)) Do While Not rs.EOF If m_lexN > UBound(m_lex) Then ReDim Preserve m_lex(m_lexN * 2) ReDim Preserve m_lexScore(m_lexN * 2) End If m_lex(m_lexN) = "" & rs(0) m_lexScore(m_lexN) = -CDbl(rs(1)) m_lexN = m_lexN + 1 rs.MoveNext Loop rs.Close End If m_semN = 0 ReDim m_sem(0) If Not Emb_Enabled() Then m_warning = "semantic retrieval is not configured; results are lexical only" ElseIf Len(allowed) = 0 Then m_strategy = "hybrid" ElseIf SemanticSearch(kind, queryText, tenantId, allowed) Then m_strategy = "hybrid" Else m_warning = "semantic retrieval is unavailable; results are lexical only" End If If m_strategy = "hybrid" Then Fuse Else m_n = m_lexN ReDim m_ids(m_n) ReDim m_scores(m_n) For i = 0 To m_lexN - 1 m_ids(i) = m_lex(i) m_scores(i) = m_lexScore(i) Next End If End Sub ' Embeds the query and asks Qdrant for the closest points of this kind in the tenant's allowed namespaces. Private Function SemanticSearch(kind, queryText, tenantId, allowed) Dim vecs, body, resp, status, p, q, id, sc, minScore SemanticSearch = False If Not Emb_EnsureCollection() Then Exit Function End If vecs = Emb_EmbedTexts(Array(queryText), Emb_Setting("EmbeddingQueryPrefix", "")) If IsEmpty(vecs) Then Exit Function End If body = "{""query"":" & vecs(0) & ",""limit"":100,""with_payload"":false,""filter"":{""must"":[" & _ "{""key"":""tenant_id"",""match"":{""value"":" & JsonLite_Quote(tenantId) & "}}," & _ "{""key"":""kind"",""match"":{""value"":""" & kind & """}}," & _ "{""key"":""namespace_id"",""match"":{""any"":[" & Replace(allowed, "'", """") & "]}}]}}" resp = Emb_Http("POST", Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & Emb_Collection() & "/points/query", body, status) If status <> 200 Then Exit Function End If minScore = Emb_MinScore() ' {"result":{"points":[{"id":"...","version":n,"score":0.8},...]},...}: scan id/score pairs in order p = InStr(resp, """id"":""") Do While p > 0 p = p + 6 q = InStr(p, resp, """") id = Mid(resp, p, q - p) p = InStr(q, resp, """score"":") If p = 0 Then Exit Do End If p = p + 8 q = p Do While q <= Len(resp) If InStr("0123456789.-+eE", Mid(resp, q, 1)) = 0 Then Exit Do End If q = q + 1 Loop sc = CDbl(Replace(Mid(resp, p, q - p), ".", Mid(CStr(1.5), 2, 1))) If sc >= minScore Then If m_semN > UBound(m_sem) Then ReDim Preserve m_sem(m_semN * 2 + 1) End If m_sem(m_semN) = id m_semN = m_semN + 1 End If p = InStr(q, resp, """id"":""") Loop SemanticSearch = True End Function ' Reciprocal rank fusion over the top 100 of each list, sorted by fused score (descending) Private Sub Fuse() Dim i, j, lim, found, t, ts m_n = 0 ReDim m_ids(200) ReDim m_scores(200) lim = m_lexN If lim > 100 Then lim = 100 End If For i = 0 To lim - 1 m_ids(m_n) = m_lex(i) m_scores(m_n) = 1 / (EMB_RRF_K + i + 1) m_n = m_n + 1 Next lim = m_semN If lim > 100 Then lim = 100 End If For i = 0 To lim - 1 found = -1 For j = 0 To m_n - 1 If m_ids(j) = m_sem(i) Then found = j Exit For End If Next If found >= 0 Then m_scores(found) = m_scores(found) + 1 / (EMB_RRF_K + i + 1) Else m_ids(m_n) = m_sem(i) m_scores(m_n) = 1 / (EMB_RRF_K + i + 1) m_n = m_n + 1 End If Next ' insertion sort, stable for equal scores (lexical order first) For i = 1 To m_n - 1 t = m_ids(i) ts = m_scores(i) j = i - 1 Do While j >= 0 If m_scores(j) >= ts Then Exit Do End If m_ids(j + 1) = m_ids(j) m_scores(j + 1) = m_scores(j) j = j - 1 Loop m_ids(j + 1) = t m_scores(j + 1) = ts Next End Sub End Class %>