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

Danielb128f6d68ce7
diff --git a/app/src/config/tabs/aiUi.ts b/app/src/config/tabs/aiUi.ts
index 87c3c0a047..1573e70996 100644
--- a/app/src/config/tabs/aiUi.ts
+++ b/app/src/config/tabs/aiUi.ts
@@ -69,8 +69,14 @@ export const mountEmbeddingStatsBlock = (root: HTMLElement) => {
const stat = response.data as {
total: number, indexed: number, pending: number, failed: number, ignoredByLen: number, ignoredByConfig: number, enabled: boolean,
};
- const contentEl = block.querySelector("#aiEmbeddingStatsContent") as HTMLElement;
- const disabledEl = block.querySelector("#aiEmbeddingStatsDisabled") as HTMLElement;
+ if (!stat) {
+ return;
+ }
+ const contentEl = block.querySelector("#aiEmbeddingStatsContent");
+ const disabledEl = block.querySelector("#aiEmbeddingStatsDisabled");
+ if (!contentEl || !disabledEl) {
+ return;
+ }
if (!stat.enabled) {
// 未启用:隐藏进度区,显示提示
contentEl.classList.add("fn__none");
@@ -88,6 +94,9 @@ export const mountEmbeddingStatsBlock = (root: HTMLElement) => {
const effectiveTotal = Math.max(0, total - ignored);
const percent = effectiveTotal > 0 ? Math.min(100, indexed / effectiveTotal * 100) : 0;
const fillEl = block.querySelector("#aiEmbeddingProgressFill") as HTMLElement;
+ if (!fillEl) {
+ return;
+ }
fillEl.style.width = `${percent}%`;
const done = indexed >= effectiveTotal && pending === 0;
@@ -103,6 +112,9 @@ export const mountEmbeddingStatsBlock = (root: HTMLElement) => {
}
const numEl = block.querySelector("#aiEmbeddingStatsNum");
+ if (!numEl) {
+ return;
+ }
// 每个统计项独立一行,避免单行过长被截断
numEl.innerHTML = `<div>${window.siyuan.languages.embeddingIndexed}<b>${indexed}</b> / ${total}</div>
<div>${window.siyuan.languages.embeddingPending}<b>${pending}</b></div>
diff --git a/kernel/model/embedding.go b/kernel/model/embedding.go
index b0371b2223..b59eaf6519 100644
--- a/kernel/model/embedding.go
+++ b/kernel/model/embedding.go
@@ -300,31 +300,42 @@ func decodeVector(b []byte) []float32 {
return unsafe.Slice((*float32)(unsafe.Pointer(&b[0])), len(b)/embeddingVectorDim)
}
+// recordFailedEmbedding 把一批块标记为失败(fail_count+1,写空 embedding),并熔断本轮 + 提示用户。
+// 用于 API 调用出错或返回向量数与输入不匹配时的统一失败处理。
+func recordFailedEmbedding(blocks []map[string]any, reason string) {
+ embeddingStop.Store(true)
+ logging.LogErrorf("create embeddings failed (%s), stop this round", reason)
+ // 多个 worker 可能并发失败,用 CAS 保证本轮只向用户提示一次
+ if embeddingErrNotified.CompareAndSwap(false, true) {
+ util.PushErrMsg("Embedding request failed, indexing paused. Please check AI embedding config.", 5000)
+ }
+
+ now := time.Now().Unix()
+ for _, row := range blocks {
+ id, _ := row["id"].(string)
+ rootID, _ := row["root_id"].(string)
+ box, _ := row["box"].(string)
+ path, _ := row["path"].(string)
+ updated, _ := row["updated"].(string)
+ // 先确保占位行存在(INSERT OR IGNORE 不覆盖已有行),再累加失败计数
+ sql.Exec("INSERT OR IGNORE INTO block_embeddings (id, root_id, box, path, embedding, model, content_len, updated, fail_count, last_tried, ignored_type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 0, 0)",
+ id, rootID, box, path, []byte{}, embeddingModel(), 0, updated)
+ sql.Exec("UPDATE block_embeddings SET fail_count = fail_count + 1, last_tried = ?, embedding = ?, model = ?, content_len = 0, ignored_type = 0 WHERE id = ?",
+ now, []byte{}, embeddingModel(), id)
+ }
+}
+
func doEmbedAndStore(texts []string, blocks []map[string]any) {
vectors, err := util.BatchGetEmbeddings(texts, embeddingKey(), embeddingBaseURL(), embeddingModel(), embeddingTimeout())
if err != nil {
// 任何 API 错误(含模型不存在/鉴权失败/限流/网络异常)都熔断本轮,避免连接风暴
- embeddingStop.Store(true)
- logging.LogErrorf("create embeddings failed, stop this round: %s", err)
- // 多个 worker 可能并发失败,用 CAS 保证本轮只向用户提示一次
- if embeddingErrNotified.CompareAndSwap(false, true) {
- util.PushErrMsg("Embedding request failed, indexing paused. Please check AI embedding config.", 5000)
- }
+ recordFailedEmbedding(blocks, err.Error())
+ return
+ }
- // 失败块记录 fail_count/last_tried,使其进入按各自退避节奏的重试队列,而非被反复无界重试
- now := time.Now().Unix()
- for _, row := range blocks {
- id, _ := row["id"].(string)
- rootID, _ := row["root_id"].(string)
- box, _ := row["box"].(string)
- path, _ := row["path"].(string)
- updated, _ := row["updated"].(string)
- // 先确保占位行存在(INSERT OR IGNORE 不覆盖已有行),再累加失败计数
- sql.Exec("INSERT OR IGNORE INTO block_embeddings (id, root_id, box, path, embedding, model, content_len, updated, fail_count, last_tried, ignored_type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 0, 0)",
- id, rootID, box, path, []byte{}, embeddingModel(), 0, updated)
- sql.Exec("UPDATE block_embeddings SET fail_count = fail_count + 1, last_tried = ?, embedding = ?, model = ?, content_len = 0, ignored_type = 0 WHERE id = ?",
- now, []byte{}, embeddingModel(), id)
- }
+ // 部分 OpenAI 兼容 API 会对重复输入去重,返回少于输入数量的向量。此时无法对齐,整批按失败处理,避免越界 panic
+ if len(vectors) != len(blocks) {
+ recordFailedEmbedding(blocks, fmt.Sprintf("count mismatch: requested %d but got %d", len(blocks), len(vectors)))
return
}
@@ -359,16 +370,15 @@ func getEmbeddingIgnoreMatcher() *ignore.GitIgnore {
return embeddingIgnoreMatcher
}
- embeddingIgnoreLoaded = true
embeddingIgnorePath := filepath.Join(util.DataDir, ".siyuan", "embeddingignore")
if !gulu.File.IsExist(embeddingIgnorePath) {
- return nil
+ return nil // 文件不存在时不置 loaded 标志,允许用户后续创建后重新加载
}
data, err := os.ReadFile(embeddingIgnorePath)
if err != nil {
logging.LogErrorf("read embeddingignore [%s] failed: %s", embeddingIgnorePath, err)
- return nil
+ return nil // 读取失败时也不置标志,下次调用会重试
}
dataStr := string(data)
@@ -376,6 +386,7 @@ func getEmbeddingIgnoreMatcher() *ignore.GitIgnore {
lines := strings.Split(dataStr, "\n")
embeddingIgnoreMatcher = ignore.CompileIgnoreLines(lines...)
+ embeddingIgnoreLoaded = true // 成功加载后才置标志,避免文件后建却永不加载
return embeddingIgnoreMatcher
}