Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Semantic search using AI embeddings https://github.com/siyuan-note/siyuan/issues/17788

Daniel5a02e7b28fc0
diff --git a/kernel/model/embedding.go b/kernel/model/embedding.go
index 3bc3b15ee5..7d5782c4b2 100644
--- a/kernel/model/embedding.go
+++ b/kernel/model/embedding.go
@@ -17,14 +17,14 @@
package model
import (
- "encoding/json"
+ "encoding/binary"
"math"
"os"
+ "runtime"
"sort"
- "strconv"
- "strings"
"sync"
"time"
+ "unsafe"
"github.com/siyuan-note/eventbus"
"github.com/siyuan-note/logging"
@@ -33,10 +33,12 @@ import (
)
const (
- embeddingBatchSize = 10
- embeddingFetchSize = 30
- embeddingMinTextLen = 7
- embeddingMaxContentLen = 12000
+ embeddingBatchSize = 10
+ embeddingFetchSize = 100
+ embeddingMaxConcurrency = 8
+ embeddingMinTextLen = 7
+ embeddingMaxContentLen = 12000
+ embeddingVectorDim = 4 // float32 = 4 bytes
)
var (
@@ -79,68 +81,94 @@ func StartEmbeddingIndexer() {
}
}
+type embeddingJob struct {
+ texts []string
+ blocks []map[string]any
+}
+
func processPendingEmbeddings() {
if !isEmbeddingEnabled() {
return
}
- for {
- results, err := sql.QueryNoLimit(stmtPendingBlocks)
- if err != nil {
- logging.LogErrorf("query pending embedding blocks failed: %s", err)
- return
- }
+ workCh := make(chan embeddingJob, embeddingMaxConcurrency*2)
- if 1 > len(results) {
- return
- }
+ var workersWg sync.WaitGroup
+ for i := 0; i < embeddingMaxConcurrency; i++ {
+ workersWg.Add(1)
+ go func() {
+ defer workersWg.Done()
+ for job := range workCh {
+ doEmbedAndStore(job.texts, job.blocks)
+ }
+ }()
+ }
- var batches [][]map[string]any
- var batch []map[string]any
- for _, row := range results {
- id, _ := row["id"].(string)
- rootID, _ := row["root_id"].(string)
- box, _ := row["box"].(string)
- path, _ := row["path"].(string)
- updated, _ := row["updated"].(string)
- content, _ := row["content"].(string)
- if len(content) < embeddingMinTextLen || len(content) > embeddingMaxContentLen {
- sql.Exec("INSERT OR IGNORE INTO block_embeddings (id, root_id, box, path, embedding, model, content_len, updated) VALUES ('" +
- id + "','" + rootID + "','" + box + "','" + path + "','','" + Conf.AI.OpenAI.EmbeddingModel + "',0,'" + updated + "')")
- continue
+ go func() {
+ defer close(workCh)
+ for {
+ results, err := sql.QueryNoLimit(stmtPendingBlocks)
+ if err != nil {
+ logging.LogErrorf("query pending embedding blocks failed: %s", err)
+ return
}
- row["plain_text"] = content
- batch = append(batch, row)
- if len(batch) >= embeddingBatchSize {
- batches = append(batches, batch)
- batch = nil
+ if 1 > len(results) {
+ return
}
- }
- if len(batch) > 0 {
- batches = append(batches, batch)
- }
- var wg sync.WaitGroup
- for _, bt := range batches {
- wg.Add(1)
- go func(blocks []map[string]any) {
- defer wg.Done()
- var texts []string
- for _, row := range blocks {
- texts = append(texts, row["plain_text"].(string))
+ var texts []string
+ var blocks []map[string]any
+ for _, row := range results {
+ id, _ := row["id"].(string)
+ rootID, _ := row["root_id"].(string)
+ box, _ := row["box"].(string)
+ path, _ := row["path"].(string)
+ updated, _ := row["updated"].(string)
+ content, _ := row["content"].(string)
+ if len(content) < embeddingMinTextLen || len(content) > embeddingMaxContentLen {
+ sql.Exec("INSERT OR IGNORE INTO block_embeddings (id, root_id, box, path, embedding, model, content_len, updated) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
+ id, rootID, box, path, []byte{}, Conf.AI.OpenAI.EmbeddingModel, 0, updated)
+ continue
+ }
+ row["plain_text"] = content
+ texts = append(texts, content)
+ blocks = append(blocks, row)
+
+ if len(texts) >= embeddingBatchSize {
+ workCh <- embeddingJob{texts: texts, blocks: blocks}
+ texts = nil
+ blocks = nil
}
- doEmbedAndStore(texts, blocks)
- }(bt)
+ }
+ if len(texts) > 0 {
+ workCh <- embeddingJob{texts: texts, blocks: blocks}
+ }
}
- wg.Wait()
- }
+ }()
+
+ workersWg.Wait()
}
const stmtPendingBlocks = "SELECT b.id, b.root_id, b.box, b.path, b.content, b.updated FROM blocks b " +
"LEFT JOIN block_embeddings e ON b.id = e.id " +
"WHERE e.id IS NULL " +
- "ORDER BY b.updated DESC LIMIT 30"
+ "ORDER BY b.updated DESC LIMIT 100"
+
+func encodeVector(vec []float32) []byte {
+ buf := make([]byte, len(vec)*embeddingVectorDim)
+ for i, v := range vec {
+ binary.LittleEndian.PutUint32(buf[i*embeddingVectorDim:], math.Float32bits(v))
+ }
+ return buf
+}
+
+func decodeVector(b []byte) []float32 {
+ if len(b) == 0 {
+ return nil
+ }
+ return unsafe.Slice((*float32)(unsafe.Pointer(&b[0])), len(b)/embeddingVectorDim)
+}
func doEmbedAndStore(texts []string, blocks []map[string]any) {
vectors, err := util.BatchGetEmbeddings(texts, embeddingKey(), embeddingBaseURL(), Conf.AI.OpenAI.EmbeddingModel, Conf.AI.OpenAI.APITimeout)
@@ -156,20 +184,10 @@ func doEmbedAndStore(texts []string, blocks []map[string]any) {
updated, _ := row["updated"].(string)
plainText, _ := row["plain_text"].(string)
- embeddingJSON, err := json.Marshal(vectors[i])
- if err != nil {
- logging.LogErrorf("marshal embedding failed for block [%s]: %s", id, err)
- continue
- }
+ buf := encodeVector(vectors[i])
- escaped := func(s string) string { return strings.ReplaceAll(s, "'", "''") }
-
- stmt := "INSERT OR REPLACE INTO block_embeddings (id, root_id, box, path, embedding, model, content_len, updated) VALUES ('" +
- escaped(id) + "', '" + escaped(rootID) + "', '" + escaped(box) + "', '" + escaped(path) + "', '" +
- escaped(string(embeddingJSON)) + "', '" + escaped(Conf.AI.OpenAI.EmbeddingModel) + "', " +
- strconv.Itoa(len(plainText)) + ", '" + escaped(updated) + "')"
-
- err = sql.Exec(stmt)
+ err = sql.Exec("INSERT OR REPLACE INTO block_embeddings (id, root_id, box, path, embedding, model, content_len, updated) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
+ id, rootID, box, path, buf, Conf.AI.OpenAI.EmbeddingModel, len(plainText), updated)
if err != nil {
logging.LogErrorf("store embedding failed for block [%s]: %s", id, err)
}
@@ -195,6 +213,11 @@ func cosineSimilarity(a, b []float32) float32 {
return float32(dotProduct / (math.Sqrt(normA) * math.Sqrt(normB)))
}
+type embeddingEntry struct {
+ id string
+ vec []float32
+}
+
func SemanticSearchBlock(query string, boxes, paths []string, types, subTypes map[string]bool, page, pageSize int) (blocks []*Block, matchedBlockCount, matchedRootCount, pageCount int) {
blocks = []*Block{}
@@ -209,34 +232,65 @@ func SemanticSearchBlock(query string, boxes, paths []string, types, subTypes ma
}
queryVec := vectors[0]
- results, err := sql.QueryNoLimit("SELECT id, embedding FROM block_embeddings")
+ results, err := sql.QueryNoLimit("SELECT id, embedding FROM block_embeddings WHERE embedding IS NOT NULL AND length(embedding) > 0")
if err != nil {
logging.LogErrorf("query embeddings for search failed: %s", err)
return
}
+ var entries []embeddingEntry
+ for _, row := range results {
+ embRaw := row["embedding"].([]byte)
+ if len(embRaw) == 0 {
+ continue
+ }
+ id, _ := row["id"].(string)
+ buf := make([]byte, len(embRaw))
+ copy(buf, embRaw)
+ entries = append(entries, embeddingEntry{id: id, vec: decodeVector(buf)})
+ }
+
type scoredBlock struct {
id string
score float32
}
- var scored []scoredBlock
- for _, row := range results {
- embStr, _ := row["embedding"].([]byte)
- if embStr == nil {
- if s, ok := row["embedding"].(string); ok {
- embStr = []byte(s)
- } else {
- continue
- }
+ numWorkers := runtime.GOMAXPROCS(0)
+ if numWorkers < 1 {
+ numWorkers = 1
+ }
+ chunkSize := (len(entries) + numWorkers - 1) / numWorkers
+
+ scoredCh := make(chan []scoredBlock, numWorkers)
+ var wg sync.WaitGroup
+
+ for w := 0; w < numWorkers; w++ {
+ start := w * chunkSize
+ end := start + chunkSize
+ if end > len(entries) {
+ end = len(entries)
}
- var vec []float32
- if err := json.Unmarshal(embStr, &vec); err != nil {
+ if start >= end {
continue
}
- score := cosineSimilarity(queryVec, vec)
- id, _ := row["id"].(string)
- scored = append(scored, scoredBlock{id: id, score: score})
+
+ wg.Add(1)
+ go func(chunk []embeddingEntry) {
+ defer wg.Done()
+ local := make([]scoredBlock, len(chunk))
+ for i, e := range chunk {
+ local[i] = scoredBlock{id: e.id, score: cosineSimilarity(queryVec, e.vec)}
+ }
+ scoredCh <- local
+ }(entries[start:end])
+ }
+
+ wg.Wait()
+ close(scoredCh)
+
+ var scored []scoredBlock
+ for ch := range scoredCh {
+ scored = append(scored, ch...)
}
sort.Slice(scored, func(i, j int) bool {
diff --git a/kernel/sql/database.go b/kernel/sql/database.go
index 3138454eb1..f441306074 100644
--- a/kernel/sql/database.go
+++ b/kernel/sql/database.go
@@ -1438,7 +1438,7 @@ func query(query string, args ...any) (*sql.Rows, error) {
return db.Query(query, args...)
}
-func Exec(stmt string) error {
+func Exec(stmt string, args ...any) error {
stmt = strings.TrimSpace(stmt)
if "" == stmt {
return errors.New("statement is empty")
@@ -1447,7 +1447,7 @@ func Exec(stmt string) error {
if nil == db {
return errors.New("database is nil")
}
- _, err := db.Exec(stmt)
+ _, err := db.Exec(stmt, args...)
return err
}