Skip to content

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

fix: switch to fetchEmbedding + cfg parameter (R4)

xiongfazhand963d0d648aa
diff --git a/src/lib/__tests__/dedup_embedding.test.ts b/src/lib/__tests__/dedup_embedding.test.ts
index ff38d08b..94b1b746 100644
--- a/src/lib/__tests__/dedup_embedding.test.ts
+++ b/src/lib/__tests__/dedup_embedding.test.ts
@@ -1,24 +1,29 @@
/**
- * dedup_embedding.test.ts — unit tests for #359 prefilter (R3)
+ * dedup_embedding.test.ts — unit tests for #359 prefilter (R4)
*/
import { describe, it, expect, vi } from 'vitest';
import {
candidatePairs,
clusterByPairs,
cosineSimilarity,
+ pageToEmbeddingText,
type Page,
} from '../dedup_embedding';
+import type { EmbeddingConfig } from '@/stores/wiki-store';
-// Mock embedPage to produce realistic, sparse vectors.
-// Strategy: numeric id → topic axis (mod dim). Pages with same numeric
-// suffix share a topic (e.g. p1 and q1 both on axis 1), but consecutive
-// ids (p0, p1, p2, ...) land on consecutive axes → low mutual similarity.
+// Mock fetchEmbedding to produce realistic, sparse vectors.
+// Strategy: numeric id suffix → topic axis (mod dim). Pages with same
+// numeric suffix share a topic (e.g. p1 and q1 both on axis 1), but
+// consecutive ids (p0, p1, p2, ...) land on consecutive axes → low mutual
+// similarity. This mirrors real-world embeddings where distinct topics
+// have distinct dominant axes.
vi.mock('../embedding', () => ({
- embedPage: vi.fn(async (page: Page) => {
+ fetchEmbedding: vi.fn(async (text: string) => {
const dim = 64;
const v = new Array(dim).fill(0);
- // Extract numeric portion of id (handles 'p123', 'q42', 'aa100' etc.)
- const numMatch = page.id.match(/\d+/);
+ // Extract numeric portion from the input text (pageId is first line)
+ const idLine = text.split('\n')[0] ?? '';
+ const numMatch = idLine.match(/\d+/);
const num = numMatch ? parseInt(numMatch[0], 10) : 0;
const topicAxis = num % dim;
v[topicAxis] = 1.0;
@@ -28,10 +33,37 @@ vi.mock('../embedding', () => ({
}),
}));
+const testCfg: EmbeddingConfig = {
+ enabled: true,
+ endpoint: 'http://localhost:0/v1/embeddings',
+ apiKey: 'mock-key',
+ model: 'mock-embedder',
+};
+
const page = (id: string, title: string, body = ''): Page => ({
id, title, body, tags: [],
});
+describe('pageToEmbeddingText', () => {
+ it('concatenates title + tags + body', () => {
+ const text = pageToEmbeddingText({
+ id: 'p1', title: 'Foo', body: 'bar baz', tags: ['a', 'b'],
+ });
+ expect(text).toBe('Foo\na b\nbar baz');
+ });
+
+ it('truncates body at budget', () => {
+ const longBody = 'x'.repeat(2000);
+ const text = pageToEmbeddingText({ id: 'p2', title: 'T', body: longBody }, 100);
+ expect(text.length).toBeLessThan(120);
+ expect(text).toContain('x'.repeat(100));
+ });
+
+ it('handles empty tags and body', () => {
+ expect(pageToEmbeddingText({ id: 'p3', title: 'Solo' })).toBe('Solo');
+ });
+});
+
describe('cosineSimilarity', () => {
it('returns 1 for identical vectors', () => {
expect(cosineSimilarity([1, 0, 0], [1, 0, 0])).toBeCloseTo(1.0, 5);
@@ -39,32 +71,36 @@ describe('cosineSimilarity', () => {
it('returns 0 for orthogonal vectors', () => {
expect(cosineSimilarity([1, 0, 0], [0, 1, 0])).toBeCloseTo(0.0, 5);
});
- it('returns 0 for zero vectors', () => {
- expect(cosineSimilarity([0, 0], [1, 1])).toBe(0);
+ it('returns 0 for null vectors', () => {
+ expect(cosineSimilarity(null, [1, 0])).toBe(0);
+ expect(cosineSimilarity([1, 0], null)).toBe(0);
});
- it('handles mismatched lengths', () => {
+ it('returns 0 for mismatched lengths', () => {
expect(cosineSimilarity([1, 0], [1, 0, 0])).toBe(0);
});
+ it('returns 0 for zero vectors', () => {
+ expect(cosineSimilarity([0, 0, 0], [1, 1, 1])).toBe(0);
+ });
});
describe('candidatePairs', () => {
it('returns empty array for empty input', async () => {
- expect(await candidatePairs([])).toEqual([]);
+ expect(await candidatePairs([], testCfg)).toEqual([]);
});
it('returns empty for single page (self-exclusion)', async () => {
- expect(await candidatePairs([page('a', 'Foo')])).toEqual([]);
+ expect(await candidatePairs([page('a', 'Foo')], testCfg)).toEqual([]);
});
it('generates symmetric, deduplicated pairs', async () => {
- // p11 and q11 share axis 11 → high similarity
+ // p11 and q11 share axis 11 → high sim
const pages = [
page('p11', 'Foo bar baz'),
page('q11', 'completely different topic'),
page('p12', 'yet another topic'),
page('q12', 'totally unrelated'),
];
- const pairs = await candidatePairs(pages, { threshold: 0.8 });
+ const pairs = await candidatePairs(pages, testCfg, { threshold: 0.8 });
expect(pairs.every(([x, y]) => x !== y)).toBe(true);
const keys = pairs.map(([x, y]) => x < y ? `${x}|${y}` : `${y}|${x}`);
expect(new Set(keys).size).toBe(keys.length);
@@ -72,37 +108,54 @@ describe('candidatePairs', () => {
it('respects threshold filter (higher threshold → fewer pairs)', async () => {
const pages = Array.from({ length: 30 }, (_, i) => page(`p${i}`, `t${i}`));
- const high = await candidatePairs(pages, { threshold: 0.99 });
- const low = await candidatePairs(pages, { threshold: 0.5 });
+ const high = await candidatePairs(pages, testCfg, { threshold: 0.99 });
+ const low = await candidatePairs(pages, testCfg, { threshold: 0.5 });
expect(low.length).toBeGreaterThanOrEqual(high.length);
});
it('respects topK (caps total pairs at topK * n)', async () => {
// With numeric-id mock: p0..p19 → distinct axes 0..19.
- // Threshold=0 means even unrelated neighbors count (low but non-zero).
- // topK=3 means each page iteration contributes AT MOST 3 NEW pairs to pairSet
- // (dedup prevents double-counting, but a pair (a,b) can be added by EITHER
- // a's iteration OR b's iteration, whichever has b/a in topK).
+ // topK=3 means each page iteration contributes AT MOST 3 NEW pairs to pairSet.
// Worst case: each iteration adds 3 NEW pairs → max = topK * n = 60.
const pages = Array.from({ length: 20 }, (_, i) => page(`p${i}`, `t${i}`));
- const pairs = await candidatePairs(pages, { threshold: 0.0, topK: 3 });
- // Strict upper bound: topK * n = 60
+ const pairs = await candidatePairs(pages, testCfg, { threshold: 0.0, topK: 3 });
expect(pairs.length).toBeLessThanOrEqual(60);
});
it('scales to 1000 pages with realistic output (acceptance for #359)', async () => {
// 1000 pages with ids p0..p999 → 64 distinct axes (15-16 pages per axis).
- // Realistic scenario: topK=3 + threshold=0.95 (semantic duplicates only).
- // Expected: ~ (3 pairs per page × 1000 pages) / 2 dedup = ~1500 pairs.
- // Acceptance: <3000 (vs R1 behavior which is N² = 1M LLM calls).
- // 300× reduction in candidates is the core value of issue #359.
+ // Acceptance: <3000 candidate pairs (300× reduction vs R1's N² baseline).
const pages = Array.from({ length: 1000 }, (_, i) => page(`p${i}`, `s${i}`));
const t0 = Date.now();
- const pairs = await candidatePairs(pages, { threshold: 0.95, topK: 3 });
+ const pairs = await candidatePairs(pages, testCfg, { threshold: 0.95, topK: 3 });
const elapsed = Date.now() - t0;
expect(elapsed).toBeLessThan(5000);
expect(pairs.length).toBeLessThan(3000);
- expect(pairs.length).toBeGreaterThan(0); // sanity: did we actually dedup?
+ expect(pairs.length).toBeGreaterThan(0); // sanity: dedup actually ran
+ });
+
+ it('skips pages whose embedding returns null', async () => {
+ // Override mock for this test only: make p1 and p2 fail embedding
+ const { fetchEmbedding } = await import('../embedding');
+ const origFetch = (fetchEmbedding as any).getMockImplementation();
+ (fetchEmbedding as any).mockImplementationOnce(async () => null); // p1
+ (fetchEmbedding as any).mockImplementationOnce(async () => null); // p2
+ (fetchEmbedding as any).mockImplementationOnce(async () => [1, 0]); // p3 axis 0
+ (fetchEmbedding as any).mockImplementationOnce(async () => [1, 0]); // p3 dup axis 0
+
+ const pages = [
+ page('p1', 'A'),
+ page('p2', 'B'),
+ page('p3', 'C'),
+ page('p4', 'D'),
+ ];
+ // p3 and p4 both have id-axes → high sim → should pair
+ const pairs = await candidatePairs(pages, testCfg, { threshold: 0.5 });
+ // null embeddings: p1 and p2 won't contribute as SOURCE; may still appear as TARGET
+ // but no pairs should reference them since no other page has a vector to compare
+ expect(pairs.every(([a, b]) => a !== 'p1' && b !== 'p1' && a !== 'p2' && b !== 'p2')).toBe(true);
+ // restore
+ (fetchEmbedding as any).mockImplementation(origFetch);
});
});
@@ -133,4 +186,4 @@ describe('clusterByPairs', () => {
const groups = clusterByPairs(ids, pairs);
expect(groups.length).toBe(1);
});
-});
+});
\ No newline at end of file
diff --git a/src/lib/dedup_embedding.ts b/src/lib/dedup_embedding.ts
index baee99ca..33c759e9 100644
--- a/src/lib/dedup_embedding.ts
+++ b/src/lib/dedup_embedding.ts
@@ -5,35 +5,38 @@
* Pre-filters pages by cosine similarity so the downstream LLM detector
* only sees a small candidate set (issue #359).
*
- * Uses real embedPage() from ./embedding (no batch API exposed).
+ * Uses real fetchEmbedding() from ./embedding (raw text → vector API).
*/
-import { embedPage } from './embedding';
+import { fetchEmbedding } from './embedding';
+import type { EmbeddingConfig } from '@/stores/wiki-store';
export interface Page {
id: string;
title: string;
- body: string;
+ body?: string;
tags?: string[];
}
-export interface PageEmbedding {
- pageId: string;
- vector: number[];
-}
-
export interface CandidateOptions {
topK?: number; // default 8
threshold?: number; // default 0.82 (cosine, 0..1)
maxPages?: number; // hard cap to avoid OOM, default 5000
+ /**
+ * Per-page character budget for the embedding input text.
+ * Real pages can be megabytes; we cap to stay within embedding context windows.
+ * Default 1500 chars (matches chunker default).
+ */
+ textBudgetChars?: number;
}
export type CandidatePair = readonly [string, string];
/**
- * Cosine similarity between two equal-length vectors. Returns 0 if either is zero.
+ * Cosine similarity between two equal-length vectors. Returns 0 if either is
+ * zero, vectors differ in length, or either is null/undefined (embedding failed).
*/
-export function cosineSimilarity(a: number[], b: number[]): number {
- if (a.length !== b.length) return 0;
+export function cosineSimilarity(a: number[] | null | undefined, b: number[] | null | undefined): number {
+ if (!a || !b || a.length !== b.length) return 0;
let dot = 0, na = 0, nb = 0;
for (let i = 0; i < a.length; i++) {
dot += a[i] * b[i];
@@ -45,14 +48,30 @@ export function cosineSimilarity(a: number[], b: number[]): number {
}
/**
- * Embed pages one-by-one using embedPage(). Sequential because batch API
- * is not exposed in current embedding.ts.
+ * Build the embedding input text from a page.
+ * Mirrors embedPage's chunker input but keeps it short for similarity comparison.
*/
-export async function embedPages(pages: Page[]): Promise<PageEmbedding[]> {
- const out: PageEmbedding[] = [];
+export function pageToEmbeddingText(page: Page, budget = 1500): string {
+ const tagPart = (page.tags ?? []).join(' ');
+ const parts = [page.title, tagPart, (page.body ?? '').slice(0, budget)];
+ return parts.filter(Boolean).join('\n');
+}
+
+/**
+ * Embed pages sequentially via fetchEmbedding.
+ * Returns pageId → vector (or null if embedding failed for that page).
+ */
+export async function embedPages(
+ pages: Page[],
+ cfg: EmbeddingConfig,
+ opts: { textBudgetChars?: number } = {},
+): Promise<Map<string, number[] | null>> {
+ const out = new Map<string, number[] | null>();
+ const budget = opts.textBudgetChars ?? 1500;
for (const p of pages) {
- const vector = await embedPage(p);
- out.push({ pageId: p.id, vector });
+ const text = pageToEmbeddingText(p, budget);
+ const vec = await fetchEmbedding(text, cfg);
+ out.set(p.id, vec);
}
return out;
}
@@ -60,9 +79,13 @@ export async function embedPages(pages: Page[]): Promise<PageEmbedding[]> {
/**
* Generate candidate duplicate pairs: each page's top-K nearest neighbors
* above threshold, self-excluded, symmetric deduplicated.
+ *
+ * Pages whose embedding failed (null) are silently skipped on the source
+ * side; they may still appear as the TARGET of a pair from another page.
*/
export async function candidatePairs(
pages: Page[],
+ cfg: EmbeddingConfig,
opts: CandidateOptions = {},
): Promise<CandidatePair[]> {
const topK = opts.topK ?? 8;
@@ -72,18 +95,20 @@ export async function candidatePairs(
if (pages.length === 0) return [];
const subset = pages.slice(0, maxPages);
- const embeddings = await embedPages(subset);
- const embMap = new Map(embeddings.map(e => [e.pageId, e.vector]));
+ const embeddings = await embedPages(subset, cfg, {
+ textBudgetChars: opts.textBudgetChars,
+ });
const pairSet = new Set<string>();
const pairs: CandidatePair[] = [];
for (let i = 0; i < subset.length; i++) {
- const vi = embMap.get(subset[i].id)!;
+ const vi = embeddings.get(subset[i].id);
+ if (!vi) continue;
const scored: Array<{ j: number; sim: number }> = [];
for (let j = 0; j < subset.length; j++) {
if (i === j) continue;
- const vj = embMap.get(subset[j].id)!;
+ const vj = embeddings.get(subset[j].id);
const sim = cosineSimilarity(vi, vj);
if (sim >= threshold) scored.push({ j, sim });
}
@@ -105,7 +130,7 @@ export async function candidatePairs(
/**
* Union-find clustering of candidate pairs into groups.
- * ITERATIVE find() to avoid stack overflow on large inputs (R1 Reviewer Major).
+ * ITERATIVE find() with path compression to avoid stack overflow on large inputs.
*/
export function clusterByPairs(
pageIds: string[],
@@ -140,4 +165,4 @@ export function clusterByPairs(
}
return [...groups.values()].filter(g => g.length > 1);
-}
+}
\ No newline at end of file