LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。
TypeScript
feat: accelerate embedding indexing
nash_suc583d919d4ed
diff --git a/src-tauri/src/commands/search.rs b/src-tauri/src/commands/search.rsindex 658b6d06..654bf3b0 100644--- a/src-tauri/src/commands/search.rs+++ b/src-tauri/src/commands/search.rs@@ -136,6 +136,17 @@ pub async fn embedding_fetch(.await}+#[tauri::command]+pub async fn embedding_fetch_batch(+ texts: Vec<String>,+ cfg: SearchEmbeddingConfig,+) -> Result<Vec<Vec<f32>>, String> {+ run_guarded_async("embedding_fetch_batch", async move {+ fetch_embedding_batch(&texts, &cfg).await+ })+ .await+}+#[tauri::command]pub async fn get_page_links(project_path: String,@@ -1082,6 +1093,123 @@ async fn fetch_embedding_with_retry(}}+async fn fetch_embedding_batch(+ texts: &[String],+ cfg: &SearchEmbeddingConfig,+) -> Result<Vec<Vec<f32>>, String> {+ if texts.is_empty() || texts.len() > 64 {+ return Err("Embedding batch must contain between 1 and 64 inputs".to_string());+ }+ if is_google_embedding_config(cfg) || is_doubao_multimodal_embedding_config(cfg) {+ return Err(+ "This embedding provider does not use the OpenAI-compatible batch format".to_string(),+ );+ }++ let endpoint = volcengine_embedding_endpoint(cfg);+ let mut req = reqwest::Client::builder()+ .timeout(std::time::Duration::from_secs(+ SEARCH_EMBEDDING_TIMEOUT_SECS,+ ))+ .build()+ .map_err(|e| format!("Embedding HTTP client error: {e}"))?+ .post(&endpoint)+ .header("Content-Type", "application/json");+ if is_local_or_private_http_endpoint(&endpoint) {+ req = req.header("Origin", "http://localhost");+ }+ if !cfg.api_key.trim().is_empty() {+ req = req.bearer_auth(cfg.api_key.trim());+ }+ if let Some(extra) = cfg.extra_headers.as_ref() {+ for (name, value) in extra {+ let name = name.trim();+ let value = value.trim();+ if !name.is_empty()+ && !value.is_empty()+ && is_safe_extra_header_name(name)+ && !is_reserved_extra_header_name(name)+ {+ req = req.header(name, value);+ }+ }+ }+ let response = req+ .json(&json!({ "model": cfg.model, "input": texts }))+ .send()+ .await+ .map_err(|e| format!("Embedding batch request failed: {e}"))?;+ let status = response.status();+ let response_text = response+ .text()+ .await+ .map_err(|e| format!("Embedding batch response read failed: {e}"))?;+ if !status.is_success() {+ return Err(format!(+ "Embedding batch API HTTP {status}: {}",+ response_text.chars().take(200).collect::<String>()+ ));+ }+ let data: Value = serde_json::from_str(&response_text).map_err(|e| {+ format!(+ "Embedding batch response parse failed: {e}: {}",+ response_text.chars().take(200).collect::<String>()+ )+ })?;+ parse_embedding_batch_values(&data, texts.len())+}++fn parse_embedding_batch_values(data: &Value, expected: usize) -> Result<Vec<Vec<f32>>, String> {+ let entries = data+ .get("data")+ .and_then(Value::as_array)+ .ok_or_else(|| "Embedding batch response missing data array".to_string())?;+ if entries.len() != expected {+ return Err(format!(+ "Embedding batch returned {} vectors for {expected} inputs",+ entries.len()+ ));+ }+ let mut indexed = Vec::with_capacity(entries.len());+ for (position, entry) in entries.iter().enumerate() {+ let index = entry+ .get("index")+ .and_then(Value::as_u64)+ .map(|value| value as usize)+ .unwrap_or(position);+ if index >= expected {+ return Err("Embedding batch response contains an out-of-range index".to_string());+ }+ let values = entry+ .get("embedding")+ .and_then(Value::as_array)+ .ok_or_else(|| "Embedding batch response missing vector".to_string())?;+ let mut vector = Vec::with_capacity(values.len());+ for value in values {+ let number = value+ .as_f64()+ .ok_or_else(|| "Embedding batch response contains non-number values".to_string())?;+ if !number.is_finite() {+ return Err("Embedding batch response contains non-finite values".to_string());+ }+ vector.push(number as f32);+ }+ if vector.is_empty() {+ return Err("Embedding batch response vector is empty".to_string());+ }+ indexed.push((index, vector));+ }+ indexed.sort_by_key(|(index, _)| *index);+ if indexed.windows(2).any(|pair| pair[0].0 == pair[1].0) {+ return Err("Embedding batch response contains duplicate indexes".to_string());+ }+ let dimension = indexed.first().map(|(_, vector)| vector.len()).unwrap_or(0);+ if indexed.iter().any(|(_, vector)| vector.len() != dimension) {+ return Err("Embedding batch response contains inconsistent vector dimensions".to_string());+ }+ Ok(indexed.into_iter().map(|(_, vector)| vector).collect())+}+fn halve_text_on_char_boundary(text: &mut String) -> bool {let char_count = text.chars().count();if char_count <= 1 {@@ -2090,4 +2218,28 @@ mod tests {assert_eq!(out.results[0].title, "Phrase");let _ = fs::remove_dir_all(root);}+ #[test]+ fn parses_openai_batch_vectors_in_input_order() {+ let response = json!({+ "data": [+ { "index": 1, "embedding": [2.0, 2.5] },+ { "index": 0, "embedding": [1.0, 1.5] }+ ]+ });+ let vectors = parse_embedding_batch_values(&response, 2).unwrap();+ assert_eq!(vectors, vec![vec![1.0, 1.5], vec![2.0, 2.5]]);+ }++ #[test]+ fn rejects_duplicate_openai_batch_indexes() {+ let response = json!({+ "data": [+ { "index": 0, "embedding": [1.0] },+ { "index": 0, "embedding": [2.0] }+ ]+ });+ assert!(parse_embedding_batch_values(&response, 2)+ .unwrap_err()+ .contains("duplicate"));+ }}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 1ca9af50..ab2d11e3 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -647,6 +647,7 @@ pub fn run() {commands::project_maintenance::rebuild_wiki_index,commands::search::search_project,commands::search::embedding_fetch,+ commands::search::embedding_fetch_batch,commands::search::get_page_links,commands::external_search::web_search,commands::external_search::anytxt_search,diff --git a/src/components/settings/sections/embedding-section.tsx b/src/components/settings/sections/embedding-section.tsxindex c9a15499..db8e9cf4 100644--- a/src/components/settings/sections/embedding-section.tsx+++ b/src/components/settings/sections/embedding-section.tsx@@ -147,6 +147,8 @@ export function EmbeddingSection({ draft, setDraft }: Props) {outputDimensionality: draft.embeddingOutputDimensionality,maxChunkChars: draft.embeddingMaxChunkChars,overlapChunkChars: draft.embeddingOverlapChunkChars,+ concurrency: draft.embeddingConcurrency,+ batchSize: draft.embeddingBatchSize,extraHeaders: draft.embeddingExtraHeaders,}@@ -321,6 +323,43 @@ export function EmbeddingSection({ draft, setDraft }: Props) {{t("settings.sections.embedding.overlapChunkCharsHint")}</p></div>++ <div className="grid gap-3 sm:grid-cols-2">+ <div className="space-y-2">+ <Label>{t("settings.sections.embedding.concurrency")}</Label>+ <Input+ type="number"+ min={1}+ max={32}+ step={1}+ value={draft.embeddingConcurrency}+ onChange={(e) => setDraft(+ "embeddingConcurrency",+ Math.max(1, Math.min(32, Number(e.target.value) || 1)),+ )}+ />+ <p className="text-xs text-muted-foreground">+ {t("settings.sections.embedding.concurrencyHint")}+ </p>+ </div>+ <div className="space-y-2">+ <Label>{t("settings.sections.embedding.batchSize")}</Label>+ <Input+ type="number"+ min={1}+ max={64}+ step={1}+ value={draft.embeddingBatchSize}+ onChange={(e) => setDraft(+ "embeddingBatchSize",+ Math.max(1, Math.min(64, Number(e.target.value) || 1)),+ )}+ />+ <p className="text-xs text-muted-foreground">+ {t("settings.sections.embedding.batchSizeHint")}+ </p>+ </div>+ </div></div><div className="space-y-3 rounded-md border p-3">diff --git a/src/components/settings/settings-types.ts b/src/components/settings/settings-types.tsindex 67f42d28..1c07fb80 100644--- a/src/components/settings/settings-types.ts+++ b/src/components/settings/settings-types.ts@@ -32,6 +32,10 @@ export interface SettingsDraft {embeddingMaxChunkChars: number | undefined/** Overlap characters between adjacent chunks. Empty = default (200). */embeddingOverlapChunkChars: number | undefined+ /** Maximum number of embedding requests in flight. */+ embeddingConcurrency: number+ /** Inputs per request for OpenAI-compatible batch endpoints. */+ embeddingBatchSize: number/** Extra HTTP headers to send on every embedding request. Empty = none. */embeddingExtraHeaders: Record<string, string>diff --git a/src/components/settings/settings-view.tsx b/src/components/settings/settings-view.tsxindex 2d323995..8df7bf90 100644--- a/src/components/settings/settings-view.tsx+++ b/src/components/settings/settings-view.tsx@@ -136,6 +136,8 @@ function initialDraft(embeddingOutputDimensionality: embed.outputDimensionality,embeddingMaxChunkChars: embed.maxChunkChars,embeddingOverlapChunkChars: embed.overlapChunkChars,+ embeddingConcurrency: embed.concurrency ?? 1,+ embeddingBatchSize: embed.batchSize ?? 1,embeddingExtraHeaders: embed.extraHeaders ?? {},multimodalEnabled: multimodal.enabled,multimodalUseMainLlm: multimodal.useMainLlm,@@ -370,6 +372,8 @@ export function SettingsView() {outputDimensionality: draft.embeddingOutputDimensionality,maxChunkChars: draft.embeddingMaxChunkChars,overlapChunkChars: draft.embeddingOverlapChunkChars,+ concurrency: Math.max(1, Math.min(32, Math.floor(draft.embeddingConcurrency || 1))),+ batchSize: Math.max(1, Math.min(64, Math.floor(draft.embeddingBatchSize || 1))),extraHeaders: draft.embeddingExtraHeaders,}const newMultimodal = {diff --git a/src/i18n/en.json b/src/i18n/en.jsonindex 9e66d9e1..2b0259a0 100644--- a/src/i18n/en.json+++ b/src/i18n/en.json@@ -574,6 +574,10 @@"maxChunkCharsHint": "Target size of each chunk. Lower this (e.g. 500) when your endpoint's context is small (llama.cpp n_ctx=512, mxbai-embed-large, etc.).","overlapChunkChars": "Overlap (characters)","overlapChunkCharsHint": "Characters of overlap between adjacent chunks so ideas aren't severed at boundaries.",+ "concurrency": "Concurrent requests",+ "concurrencyHint": "Maximum embedding requests in flight (1–32). Increase gradually according to your endpoint's capacity.",+ "batchSize": "Inputs per request",+ "batchSizeHint": "OpenAI-compatible endpoints only (1–64). Unsupported providers automatically use single-input requests.","providerTests": "Provider tests","providerTestsHint": "Connection test sends one short embedding request. Functional test verifies stable finite vectors and reports the returned dimension.","testConnection": "Test connection",diff --git a/src/i18n/zh.json b/src/i18n/zh.jsonindex bc5f8d91..ad43189c 100644--- a/src/i18n/zh.json+++ b/src/i18n/zh.json@@ -574,6 +574,10 @@"maxChunkCharsHint": "单个 chunk 的目标长度。endpoint 上下文较小时(llama.cpp n_ctx=512、mxbai-embed-large 等)调低(如 500)。","overlapChunkChars": "重叠字符数","overlapChunkCharsHint": "相邻 chunk 之间的重叠字符数,避免语义在边界被切断。",+ "concurrency": "并发请求数",+ "concurrencyHint": "同时进行的 embedding 请求上限(1–32)。请根据 endpoint 承载能力逐步调高。",+ "batchSize": "单次请求输入数",+ "batchSizeHint": "仅 OpenAI 兼容 endpoint 支持(1–64);不支持的 Provider 会自动使用单条请求。","providerTests": "Provider 测试","providerTestsHint": "连接测试会发送一次短 embedding 请求;功能测试会验证返回的是稳定、有限的向量,并显示维度。","testConnection": "测试连接",diff --git a/src/lib/embedding.test.ts b/src/lib/embedding.test.tsindex da078c10..71ed414e 100644--- a/src/lib/embedding.test.ts+++ b/src/lib/embedding.test.ts@@ -1482,6 +1482,84 @@ describe("embedAllPages", () => {},]+ it("bounds embedding requests by the configured global concurrency", async () => {+ listDirectoryMock.mockResolvedValueOnce(Array.from({ length: 6 }, (_, index) => ({+ name: `page-${index}.md`,+ path: `/proj/wiki/page-${index}.md`,+ is_dir: false,+ })))+ readFileMock.mockResolvedValue("# Title\n\nBody.")+ let active = 0+ let peak = 0+ mockEmbeddingFetchInvoke.mockImplementation(async () => {+ active+++ peak = Math.max(peak, active)+ await new Promise((resolve) => setTimeout(resolve, 10))+ active--+ return [0.5]+ })++ await expect(embedAllPages("/proj", { ...cfg, concurrency: 3 })).resolves.toBe(6)+ expect(peak).toBe(3)+ })++ it("uses OpenAI-compatible batch requests and preserves chunk order", async () => {+ listDirectoryMock.mockResolvedValueOnce([])+ const batchCalls: Array<{ texts: string[] }> = []+ mockInvoke.mockImplementation(async (command, args) => {+ if (command === "embedding_fetch_batch") {+ const input = args as { texts: string[] }+ batchCalls.push(input)+ return input.texts.map((_, index) => [index + 0.25])+ }+ return undefined+ })+ const content = Array.from(+ { length: 8 },+ (_, index) => `## Section ${index}\n\n${`content-${index} `.repeat(40)}`,+ ).join("\n\n")++ await expect(embedPage("/proj", "batched", "Batched", content, {+ ...cfg,+ maxChunkChars: 240,+ overlapChunkChars: 0,+ batchSize: 4,+ concurrency: 2,+ })).resolves.toBe(true)+ expect(batchCalls.length).toBeGreaterThan(0)+ expect(batchCalls.every((call) => call.texts.length <= 4)).toBe(true)+ const upsert = mockInvoke.mock.calls.find((call) => call[0] === "vector_upsert_chunks")+ const chunks = (upsert?.[1] as { chunks: Array<{ chunk_index: number }> }).chunks+ expect(chunks.map((chunk) => chunk.chunk_index)).toEqual(+ [...chunks].map((chunk) => chunk.chunk_index).sort((a, b) => a - b),+ )+ })++ it("embeds chunks from one page concurrently without exceeding the limit", async () => {+ let active = 0+ let peak = 0+ mockEmbeddingFetchInvoke.mockImplementation(async () => {+ active+++ peak = Math.max(peak, active)+ await new Promise((resolve) => setTimeout(resolve, 10))+ active--+ return [0.5]+ })+ const content = Array.from(+ { length: 8 },+ (_, index) => `## Section ${index}\n\n${`content-${index} `.repeat(40)}`,+ ).join("\n\n")++ await expect(embedPage("/proj", "concurrent", "Concurrent", content, {+ ...cfg,+ maxChunkChars: 240,+ overlapChunkChars: 0,+ concurrency: 3,+ batchSize: 1,+ })).resolves.toBe(true)+ expect(peak).toBe(3)+ })+it("indexes every non-structural .md file, recursing into subdirs", async () => {listDirectoryMock.mockResolvedValueOnce(makeTree())readFileMock.mockResolvedValue("# Title\n\nBody.")diff --git a/src/lib/embedding.ts b/src/lib/embedding.tsindex 8c7fdf5d..258253d3 100644--- a/src/lib/embedding.ts+++ b/src/lib/embedding.ts@@ -105,6 +105,51 @@ export async function fetchEmbedding(}}+async function fetchBatchEmbeddings(+ texts: string[],+ cfg: EmbeddingConfig,+): Promise<number[][] | null> {+ if (texts.length === 0) return []+ try {+ const embeddings = await invoke<number[][]>("embedding_fetch_batch", { texts, cfg })+ if (embeddings.length !== texts.length) {+ throw new Error(`Embedding batch returned ${embeddings.length} vectors for ${texts.length} inputs`)+ }+ lastEmbeddingError = null+ return embeddings+ } catch (err) {+ lastEmbeddingError = err instanceof Error ? err.message : String(err)+ console.warn(`[Embedding] Batch request failed; retrying inputs individually: ${lastEmbeddingError}`)+ return null+ }+}++function supportsOpenAiCompatibleBatch(cfg: EmbeddingConfig): boolean {+ const endpoint = cfg.endpoint.toLowerCase()+ const model = cfg.model.toLowerCase()+ return !endpoint.includes("generativelanguage.googleapis.com")+ && !endpoint.includes(":embedcontent")+ && !model.includes("doubao-embedding-vision")+}++type AsyncLimiter = <T>(task: () => Promise<T>) => Promise<T>++function createAsyncLimiter(rawLimit: number | undefined): AsyncLimiter {+ const limit = Math.max(1, Math.min(32, Math.floor(rawLimit ?? 1)))+ let active = 0+ const waiters: Array<() => void> = []+ return async <T>(task: () => Promise<T>): Promise<T> => {+ if (active >= limit) await new Promise<void>((resolve) => waiters.push(resolve))+ active+++ try {+ return await task()+ } finally {+ active--+ waiters.shift()?.()+ }+ }+}+// ── LanceDB v2 operations (via Rust Tauri commands) ──────────────────────interface ChunkUpsertInput {@@ -271,6 +316,7 @@ async function preparePageEmbeddingRows(title: string,content: string,cfg: EmbeddingConfig,+ schedule: AsyncLimiter = createAsyncLimiter(cfg.concurrency),): Promise<PageEmbeddingPreparation> {if (!cfg.enabled || !cfg.model) return { status: "empty" }@@ -280,22 +326,33 @@ async function preparePageEmbeddingRows(})if (chunks.length === 0) return { status: "empty" }- const rows: ChunkUpsertInput[] = []- let failedChunks = 0- for (const chunk of chunks) {- const embedText = enrichChunkForEmbedding(title, chunk)- const vec = await fetchEmbedding(embedText, cfg)- if (vec) {- rows.push({- chunkIndex: chunk.index,- chunkText: chunk.text,- headingPath: chunk.headingPath,- embedding: vec,+ const batchSize = Math.max(1, Math.min(64, Math.floor(cfg.batchSize ?? 1)))+ const tasks: Array<Promise<ChunkUpsertInput[]>> = []+ for (let offset = 0; offset < chunks.length; offset += batchSize) {+ const batch = chunks.slice(offset, offset + batchSize)+ const texts = batch.map((chunk) => enrichChunkForEmbedding(title, chunk))+ tasks.push((async () => {+ const vectors = batch.length > 1 && supportsOpenAiCompatibleBatch(cfg)+ ? await schedule(() => fetchBatchEmbeddings(texts, cfg))+ : null+ const resolved = vectors ?? await Promise.all(+ texts.map((text) => schedule(() => fetchEmbedding(text, cfg))),+ )+ return resolved.flatMap((embedding, index) => {+ if (!embedding) return []+ const chunk = batch[index]+ return [{+ chunkIndex: chunk.index,+ chunkText: chunk.text,+ headingPath: chunk.headingPath,+ embedding,+ }]})- } else {- failedChunks++- }+ })())}+ const rows = (await Promise.all(tasks)).flat()+ rows.sort((a, b) => a.chunkIndex - b.chunkIndex)+ const failedChunks = chunks.length - rows.lengthif (rows.length === 0) {return {@@ -382,19 +439,38 @@ function throwEmbeddingReindexError(projectPath: string, message: string): neverthrow new Error(message)}+async function parallelForEach<T>(+ items: T[],+ rawLimit: number | undefined,+ visit: (item: T) => Promise<void>,+): Promise<void> {+ const workerCount = Math.min(+ items.length,+ Math.max(1, Math.min(32, Math.floor(rawLimit ?? 1))),+ )+ let next = 0+ await Promise.all(Array.from({ length: workerCount }, async () => {+ while (next < items.length) {+ const index = next+++ await visit(items[index])+ }+ }))+}+async function preparePageEmbeddingRowsWithRetry(pageId: string,title: string,content: string,cfg: EmbeddingConfig,attempts = 3,+ schedule: AsyncLimiter = createAsyncLimiter(cfg.concurrency),): Promise<PageEmbeddingPreparation> {- let best = await preparePageEmbeddingRows(pageId, title, content, cfg)+ let best = await preparePageEmbeddingRows(pageId, title, content, cfg, schedule)for (let attempt = 1; attempt < attempts; attempt += 1) {if (best.status === "empty") return bestif (best.status === "ready" && best.page.failedChunks === 0) return bestawait new Promise((resolve) => setTimeout(resolve, attempt * 250))- const candidate = await preparePageEmbeddingRows(pageId, title, content, cfg)+ const candidate = await preparePageEmbeddingRows(pageId, title, content, cfg, schedule)if (candidate.status === "ready"&& (best.status !== "ready" || candidate.page.failedChunks < best.page.failedChunks)@@ -450,6 +526,10 @@ export async function embedAllPages(}}walk(tree)+ const scheduleEmbedding = createAsyncLimiter(cfg.concurrency)+ // LanceDB page replacement is intentionally serialized. The configured+ // concurrency applies to outbound embedding HTTP, not database writers.+ const scheduleVectorWrite = createAsyncLimiter(1)if (options?.clearExisting) {if (mdFiles.length === 0) {@@ -469,11 +549,18 @@ export async function embedAllPages(const preparedPages: PreparedPageEmbedding[] = []const failures: string[] = []let attempted = 0- for (const file of mdFiles) {+ await parallelForEach(mdFiles, cfg.concurrency, async (file) => {try {const content = await readFile(file.path)const title = extractEmbeddingTitle(content, file.id)- const prepared = await preparePageEmbeddingRowsWithRetry(file.id, title, content, cfg)+ const prepared = await preparePageEmbeddingRowsWithRetry(+ file.id,+ title,+ content,+ cfg,+ 3,+ scheduleEmbedding,+ )if (prepared.status === "ready") {if (prepared.page.failedChunks > 0) {const reason = getLastEmbeddingError()@@ -497,7 +584,7 @@ export async function embedAllPages(total: mdFiles.length,})if (onProgress) onProgress(attempted, mdFiles.length)- }+ })if (failures.length > 0) {let updated = 0@@ -560,11 +647,13 @@ export async function embedAllPages(let done = 0let indexed = 0- for (const file of mdFiles) {+ await parallelForEach(mdFiles, cfg.concurrency, async (file) => {try {const content = await readFile(file.path)const title = extractEmbeddingTitle(content, file.id)- if (await embedPage(pp, file.id, title, content, cfg, { deferOptimization: true })) {+ const prepared = await preparePageEmbeddingRows(file.id, title, content, cfg, scheduleEmbedding)+ if (prepared.status === "ready") {+ await scheduleVectorWrite(() => vectorUpsertChunks(pp, file.id, prepared.page.rows))indexed++}} catch {@@ -573,7 +662,7 @@ export async function embedAllPages(done++setEmbeddingReindexState({ kind: "running", projectPath: pp, done, total: mdFiles.length })if (onProgress) onProgress(done, mdFiles.length)- }+ })if (indexed > 0) {await optimizeChunkVectorTableBestEffort(pp)diff --git a/src/stores/wiki-store.ts b/src/stores/wiki-store.tsindex ac705489..5743679f 100644--- a/src/stores/wiki-store.ts+++ b/src/stores/wiki-store.ts@@ -133,6 +133,10 @@ interface EmbeddingConfig {*/maxChunkChars?: numberoverlapChunkChars?: number+ /** Maximum embedding HTTP requests in flight. Defaults to 1 for compatibility. */+ concurrency?: number+ /** Texts per OpenAI-compatible embedding request. Defaults to 1. */+ batchSize?: number/*** Extra HTTP headers to send with every embedding request, e.g.* { "X-Model-Provider-Id": "siliconflow" }