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

feat: optional vector search via embedding API

nash_su2460ac667088
diff --git a/src/App.tsx b/src/App.tsx
index 3b0eaee4..eb97bfaa 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -5,7 +5,7 @@ import { useWikiStore } from "@/stores/wiki-store"
import { useReviewStore } from "@/stores/review-store"
import { useChatStore } from "@/stores/chat-store"
import { listDirectory, openProject } from "@/commands/fs"
-import { getLastProject, getRecentProjects, saveLastProject, loadLlmConfig, loadLanguage, loadSearchApiConfig } from "@/lib/project-store"
+import { getLastProject, getRecentProjects, saveLastProject, loadLlmConfig, loadLanguage, loadSearchApiConfig, loadEmbeddingConfig } from "@/lib/project-store"
import { loadReviewItems, loadChatHistory } from "@/lib/persist"
import { setupAutoSave } from "@/lib/auto-save"
import { startClipWatcher } from "@/lib/clip-watcher"
@@ -41,6 +41,10 @@ function App() {
if (savedSearchConfig) {
useWikiStore.getState().setSearchApiConfig(savedSearchConfig)
}
+ const savedEmbeddingConfig = await loadEmbeddingConfig()
+ if (savedEmbeddingConfig) {
+ useWikiStore.getState().setEmbeddingConfig(savedEmbeddingConfig)
+ }
const savedLang = await loadLanguage()
if (savedLang) {
await i18n.changeLanguage(savedLang)
diff --git a/src/components/chat/chat-panel.tsx b/src/components/chat/chat-panel.tsx
index 461c9889..02855425 100644
--- a/src/components/chat/chat-panel.tsx
+++ b/src/components/chat/chat-panel.tsx
@@ -213,6 +213,59 @@ export function ChatPanel() {
}
}
+ // ── Phase 1.5: Vector search (if embedding enabled) ─────
+ const embCfg = useWikiStore.getState().embeddingConfig
+ if (embCfg.enabled && embCfg.model) {
+ try {
+ const { searchByEmbedding } = await import("@/lib/embedding")
+ const llmCfg = useWikiStore.getState().llmConfig
+ const vectorResults = await searchByEmbedding(pp, text, llmCfg, embCfg, 10)
+ // Merge vector results into search results (avoid duplicates)
+ const existingPaths = new Set(topSearchResults.map((r) => r.path))
+ for (const vr of vectorResults) {
+ const pagePath = `${pp}/wiki`
+ // Find matching file in search results by page ID
+ const matchingSearch = searchResults.find((r) => {
+ const fileName = getFileName(r.path).replace(/\.md$/, "")
+ return fileName === vr.id
+ })
+ if (matchingSearch && !existingPaths.has(matchingSearch.path)) {
+ topSearchResults.push(matchingSearch)
+ existingPaths.add(matchingSearch.path)
+ } else if (!matchingSearch) {
+ // Try to find the file path by scanning wiki directories
+ const possiblePaths = [
+ `${pp}/wiki/entities/${vr.id}.md`,
+ `${pp}/wiki/concepts/${vr.id}.md`,
+ `${pp}/wiki/sources/${vr.id}.md`,
+ `${pp}/wiki/synthesis/${vr.id}.md`,
+ `${pp}/wiki/comparison/${vr.id}.md`,
+ `${pp}/wiki/queries/${vr.id}.md`,
+ ]
+ for (const tryPath of possiblePaths) {
+ if (!existingPaths.has(tryPath)) {
+ try {
+ await readFile(tryPath)
+ topSearchResults.push({
+ path: tryPath,
+ title: vr.id.replace(/-/g, " "),
+ score: vr.score * 10,
+ titleMatch: false,
+ })
+ existingPaths.add(tryPath)
+ break
+ } catch {
+ // file doesn't exist at this path
+ }
+ }
+ }
+ }
+ }
+ } catch {
+ // Vector search failed, continue without it
+ }
+ }
+
// ── Phase 2: Graph 1-level expansion ───────────────────
const graph = await buildRetrievalGraph(pp, dataVersion)
const expandedIds = new Set<string>()
diff --git a/src/components/settings/settings-view.tsx b/src/components/settings/settings-view.tsx
index c40063cc..82c62db7 100644
--- a/src/components/settings/settings-view.tsx
+++ b/src/components/settings/settings-view.tsx
@@ -29,6 +29,8 @@ export function SettingsView() {
const setLlmConfig = useWikiStore((s) => s.setLlmConfig)
const searchApiConfig = useWikiStore((s) => s.searchApiConfig)
const setSearchApiConfig = useWikiStore((s) => s.setSearchApiConfig)
+ const embeddingConfig = useWikiStore((s) => s.embeddingConfig)
+ const setEmbeddingConfig = useWikiStore((s) => s.setEmbeddingConfig)
const maxHistoryMessages = useChatStore((s) => s.maxHistoryMessages)
const setMaxHistoryMessages = useChatStore((s) => s.setMaxHistoryMessages)
@@ -40,6 +42,8 @@ export function SettingsView() {
const [maxContextSize, setMaxContextSize] = useState(llmConfig.maxContextSize ?? 204800)
const [searchProvider, setSearchProvider] = useState(searchApiConfig.provider)
const [searchApiKey, setSearchApiKey] = useState(searchApiConfig.apiKey)
+ const [embeddingEnabled, setEmbeddingEnabled] = useState(embeddingConfig.enabled)
+ const [embeddingModel, setEmbeddingModel] = useState(embeddingConfig.model)
const [saved, setSaved] = useState(false)
const [currentLang, setCurrentLang] = useState(i18n.language)
@@ -59,11 +63,14 @@ export function SettingsView() {
const currentProvider = PROVIDERS.find((p) => p.value === provider)
async function handleSave() {
- const { saveLlmConfig, saveSearchApiConfig } = await import("@/lib/project-store")
+ const { saveLlmConfig, saveSearchApiConfig, saveEmbeddingConfig } = await import("@/lib/project-store")
const newConfig = { provider, apiKey, model, ollamaUrl, customEndpoint, maxContextSize }
const newSearchConfig = { provider: searchProvider, apiKey: searchApiKey }
+ const newEmbeddingConfig = { enabled: embeddingEnabled, model: embeddingModel }
setSearchApiConfig(newSearchConfig)
await saveSearchApiConfig(newSearchConfig)
+ setEmbeddingConfig(newEmbeddingConfig)
+ await saveEmbeddingConfig(newEmbeddingConfig)
setLlmConfig(newConfig)
await saveLlmConfig(newConfig)
setSaved(true)
@@ -264,6 +271,41 @@ export function SettingsView() {
)}
</div>
+ {/* Embedding Search section */}
+ <div className="space-y-4 rounded-lg border p-4">
+ <div className="flex items-center justify-between">
+ <h3 className="font-semibold">Vector Search (Embedding)</h3>
+ <button
+ onClick={() => setEmbeddingEnabled(!embeddingEnabled)}
+ className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${
+ embeddingEnabled ? "bg-primary" : "bg-muted"
+ }`}
+ >
+ <span
+ className={`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${
+ embeddingEnabled ? "translate-x-4.5" : "translate-x-0.5"
+ }`}
+ />
+ </button>
+ </div>
+ <p className="text-xs text-muted-foreground">
+ Enable semantic search using embeddings. Uses the same LLM provider endpoint. Improves search quality for synonym matching and cross-domain discovery.
+ </p>
+ {embeddingEnabled && (
+ <div className="space-y-2">
+ <Label>Embedding Model</Label>
+ <Input
+ value={embeddingModel}
+ onChange={(e) => setEmbeddingModel(e.target.value)}
+ placeholder="e.g. text-embedding-3-small, nomic-embed-text"
+ />
+ <p className="text-xs text-muted-foreground">
+ The embedding model name supported by your LLM provider.
+ </p>
+ </div>
+ )}
+ </div>
+
{/* Chat History section */}
<div className="space-y-4 rounded-lg border p-4">
<h3 className="font-semibold">Chat History</h3>
diff --git a/src/lib/embedding.ts b/src/lib/embedding.ts
new file mode 100644
index 00000000..427296ed
--- /dev/null
+++ b/src/lib/embedding.ts
@@ -0,0 +1,261 @@
+import { readFile, writeFile, listDirectory } from "@/commands/fs"
+import type { LlmConfig, EmbeddingConfig } from "@/stores/wiki-store"
+import type { FileNode } from "@/types/wiki"
+import { normalizePath } from "@/lib/path-utils"
+
+// ── Types ─────────────────────────────────────────────────────────────────
+
+interface EmbeddingCache {
+ model: string
+ embeddings: Record<string, number[]> // pageId -> vector
+}
+
+// ── Module cache ──────────────────────────────────────────────────────────
+
+let cache: EmbeddingCache | null = null
+let cacheProjectPath = ""
+
+// ── API ───────────────────────────────────────────────────────────────────
+
+function getEmbeddingEndpoint(llmConfig: LlmConfig): string {
+ switch (llmConfig.provider) {
+ case "openai":
+ return "https://api.openai.com/v1/embeddings"
+ case "ollama":
+ return `${llmConfig.ollamaUrl}/v1/embeddings`
+ case "custom":
+ // Assume custom endpoint supports /embeddings
+ return llmConfig.customEndpoint.replace(/\/chat\/completions\/?$/, "/embeddings")
+ default:
+ // For providers without native embedding, use custom endpoint if set
+ return llmConfig.customEndpoint
+ ? llmConfig.customEndpoint.replace(/\/chat\/completions\/?$/, "/embeddings")
+ : ""
+ }
+}
+
+function getAuthHeaders(llmConfig: LlmConfig): Record<string, string> {
+ const headers: Record<string, string> = { "Content-Type": "application/json" }
+ if (llmConfig.apiKey) {
+ headers["Authorization"] = `Bearer ${llmConfig.apiKey}`
+ }
+ return headers
+}
+
+async function fetchEmbedding(
+ text: string,
+ llmConfig: LlmConfig,
+ embeddingConfig: EmbeddingConfig,
+): Promise<number[] | null> {
+ const endpoint = getEmbeddingEndpoint(llmConfig)
+ if (!endpoint) return null
+
+ try {
+ const resp = await fetch(endpoint, {
+ method: "POST",
+ headers: getAuthHeaders(llmConfig),
+ body: JSON.stringify({
+ model: embeddingConfig.model,
+ input: text.slice(0, 2000), // truncate to avoid token limits
+ }),
+ })
+
+ if (!resp.ok) return null
+
+ const data = await resp.json()
+ return data?.data?.[0]?.embedding ?? null
+ } catch {
+ return null
+ }
+}
+
+// ── Cache management ──────────────────────────────────────────────────────
+
+function cachePath(projectPath: string): string {
+ return `${normalizePath(projectPath)}/.llm-wiki/embeddings.json`
+}
+
+async function loadCache(projectPath: string, model: string): Promise<EmbeddingCache> {
+ const pp = normalizePath(projectPath)
+ if (cache && cacheProjectPath === pp && cache.model === model) {
+ return cache
+ }
+
+ try {
+ const raw = await readFile(cachePath(pp))
+ const loaded = JSON.parse(raw) as EmbeddingCache
+ // Invalidate if model changed
+ if (loaded.model !== model) {
+ cache = { model, embeddings: {} }
+ } else {
+ cache = loaded
+ }
+ } catch {
+ cache = { model, embeddings: {} }
+ }
+
+ cacheProjectPath = pp
+ return cache
+}
+
+async function saveCache(projectPath: string): Promise<void> {
+ if (!cache) return
+ try {
+ await writeFile(cachePath(projectPath), JSON.stringify(cache))
+ } catch {
+ // non-critical
+ }
+}
+
+// ── Public API ────────────────────────────────────────────────────────────
+
+/**
+ * Embed a single page and cache the result.
+ * Called after ingest to keep embeddings up to date.
+ */
+export async function embedPage(
+ projectPath: string,
+ pageId: string,
+ title: string,
+ content: string,
+ llmConfig: LlmConfig,
+ embeddingConfig: EmbeddingConfig,
+): Promise<void> {
+ if (!embeddingConfig.enabled || !embeddingConfig.model) return
+
+ const c = await loadCache(projectPath, embeddingConfig.model)
+ const text = `${title}\n${content.slice(0, 1500)}`
+ const emb = await fetchEmbedding(text, llmConfig, embeddingConfig)
+
+ if (emb) {
+ c.embeddings[pageId] = emb
+ await saveCache(projectPath)
+ }
+}
+
+/**
+ * Embed all wiki pages that are not yet cached.
+ * Called on first enable or when model changes.
+ */
+export async function embedAllPages(
+ projectPath: string,
+ llmConfig: LlmConfig,
+ embeddingConfig: EmbeddingConfig,
+ onProgress?: (done: number, total: number) => void,
+): Promise<number> {
+ if (!embeddingConfig.enabled || !embeddingConfig.model) return 0
+
+ const pp = normalizePath(projectPath)
+ const c = await loadCache(pp, embeddingConfig.model)
+
+ // Find all wiki .md files
+ let tree: FileNode[]
+ try {
+ tree = await listDirectory(`${pp}/wiki`)
+ } catch {
+ return 0
+ }
+
+ const mdFiles: { id: string; path: string }[] = []
+ function walk(nodes: FileNode[]) {
+ for (const node of nodes) {
+ if (node.is_dir && node.children) {
+ walk(node.children)
+ } else if (!node.is_dir && node.name.endsWith(".md")) {
+ const id = node.name.replace(/\.md$/, "")
+ if (!["index", "log", "overview", "purpose", "schema"].includes(id)) {
+ mdFiles.push({ id, path: node.path })
+ }
+ }
+ }
+ }
+ walk(tree)
+
+ // Only embed pages not in cache
+ const toEmbed = mdFiles.filter((f) => !(f.id in c.embeddings))
+ let done = 0
+
+ for (const file of toEmbed) {
+ try {
+ const content = await readFile(file.path)
+ // Extract title from frontmatter
+ const titleMatch = content.match(/^---\n[\s\S]*?^title:\s*["']?(.+?)["']?\s*$/m)
+ const title = titleMatch ? titleMatch[1].trim() : file.id
+
+ const text = `${title}\n${content.slice(0, 1500)}`
+ const emb = await fetchEmbedding(text, llmConfig, embeddingConfig)
+ if (emb) {
+ c.embeddings[file.id] = emb
+ }
+ } catch {
+ // skip
+ }
+
+ done++
+ if (onProgress) onProgress(done, toEmbed.length)
+
+ // Save periodically
+ if (done % 20 === 0) {
+ await saveCache(pp)
+ }
+ }
+
+ await saveCache(pp)
+ return done
+}
+
+/**
+ * Search wiki pages by semantic similarity.
+ * Returns page IDs sorted by cosine similarity.
+ */
+export async function searchByEmbedding(
+ projectPath: string,
+ query: string,
+ llmConfig: LlmConfig,
+ embeddingConfig: EmbeddingConfig,
+ topK: number = 10,
+): Promise<Array<{ id: string; score: number }>> {
+ if (!embeddingConfig.enabled || !embeddingConfig.model) return []
+
+ const c = await loadCache(projectPath, embeddingConfig.model)
+ const queryEmb = await fetchEmbedding(query, llmConfig, embeddingConfig)
+ if (!queryEmb) return []
+
+ const scored: Array<{ id: string; score: number }> = []
+
+ for (const [pageId, pageEmb] of Object.entries(c.embeddings)) {
+ const sim = cosineSimilarity(queryEmb, pageEmb)
+ if (sim > 0) {
+ scored.push({ id: pageId, score: sim })
+ }
+ }
+
+ scored.sort((a, b) => b.score - a.score)
+ return scored.slice(0, topK)
+}
+
+/**
+ * Clear embedding cache (e.g., when model changes).
+ */
+export async function clearEmbeddingCache(projectPath: string): Promise<void> {
+ cache = null
+ cacheProjectPath = ""
+ try {
+ await writeFile(cachePath(projectPath), JSON.stringify({ model: "", embeddings: {} }))
+ } catch {
+ // non-critical
+ }
+}
+
+// ── Helpers ───────────────────────────────────────────────────────────────
+
+function cosineSimilarity(a: number[], b: number[]): number {
+ let dot = 0, normA = 0, normB = 0
+ for (let i = 0; i < a.length; i++) {
+ dot += a[i] * b[i]
+ normA += a[i] * a[i]
+ normB += b[i] * b[i]
+ }
+ const denom = Math.sqrt(normA) * Math.sqrt(normB)
+ return denom === 0 ? 0 : dot / denom
+}
diff --git a/src/lib/ingest.ts b/src/lib/ingest.ts
index c468b2bd..48053ee2 100644
--- a/src/lib/ingest.ts
+++ b/src/lib/ingest.ts
@@ -180,6 +180,29 @@ export async function autoIngest(
await saveIngestCache(pp, fileName, sourceContent, writtenPaths)
}
+ // ── Step 6: Generate embeddings (if enabled) ───────────────
+ const embCfg = useWikiStore.getState().embeddingConfig
+ if (embCfg.enabled && embCfg.model && writtenPaths.length > 0) {
+ try {
+ const { embedPage } = await import("@/lib/embedding")
+ const llmCfg = useWikiStore.getState().llmConfig
+ for (const wpath of writtenPaths) {
+ const pageId = wpath.split("/").pop()?.replace(/\.md$/, "") ?? ""
+ if (!pageId || ["index", "log", "overview"].includes(pageId)) continue
+ try {
+ const content = await readFile(`${pp}/${wpath}`)
+ const titleMatch = content.match(/^---\n[\s\S]*?^title:\s*["']?(.+?)["']?\s*$/m)
+ const title = titleMatch ? titleMatch[1].trim() : pageId
+ await embedPage(pp, pageId, title, content, llmCfg, embCfg)
+ } catch {
+ // non-critical
+ }
+ }
+ } catch {
+ // embedding module not available
+ }
+ }
+
const detail = writtenPaths.length > 0
? `${writtenPaths.length} files written${reviewItems.length > 0 ? `, ${reviewItems.length} review item(s)` : ""}`
: "No files generated"
diff --git a/src/lib/project-store.ts b/src/lib/project-store.ts
index 67f7f512..459d8afc 100644
--- a/src/lib/project-store.ts
+++ b/src/lib/project-store.ts
@@ -62,6 +62,18 @@ export async function loadSearchApiConfig(): Promise<SearchApiConfig | null> {
return (await store.get<SearchApiConfig>(SEARCH_API_KEY)) ?? null
}
+const EMBEDDING_KEY = "embeddingConfig"
+
+export async function saveEmbeddingConfig(config: import("@/stores/wiki-store").EmbeddingConfig): Promise<void> {
+ const store = await getStore()
+ await store.set(EMBEDDING_KEY, config)
+}
+
+export async function loadEmbeddingConfig(): Promise<import("@/stores/wiki-store").EmbeddingConfig | null> {
+ const store = await getStore()
+ return (await store.get<import("@/stores/wiki-store").EmbeddingConfig>(EMBEDDING_KEY)) ?? null
+}
+
export async function removeFromRecentProjects(
path: string
): Promise<void> {
diff --git a/src/stores/wiki-store.ts b/src/stores/wiki-store.ts
index 275038f1..8f0add0f 100644
--- a/src/stores/wiki-store.ts
+++ b/src/stores/wiki-store.ts
@@ -15,6 +15,11 @@ interface SearchApiConfig {
apiKey: string
}
+interface EmbeddingConfig {
+ enabled: boolean
+ model: string // e.g. "text-embedding-qwen3-embedding-0.6b"
+}
+
interface WikiState {
project: WikiProject | null
fileTree: FileNode[]
@@ -24,6 +29,7 @@ interface WikiState {
activeView: "wiki" | "sources" | "search" | "graph" | "lint" | "review" | "settings"
llmConfig: LlmConfig
searchApiConfig: SearchApiConfig
+ embeddingConfig: EmbeddingConfig
dataVersion: number
setProject: (project: WikiProject | null) => void
@@ -34,6 +40,7 @@ interface WikiState {
setActiveView: (view: WikiState["activeView"]) => void
setLlmConfig: (config: LlmConfig) => void
setSearchApiConfig: (config: SearchApiConfig) => void
+ setEmbeddingConfig: (config: EmbeddingConfig) => void
bumpDataVersion: () => void
}
@@ -66,9 +73,15 @@ export const useWikiStore = create<WikiState>((set) => ({
apiKey: "",
},
+ embeddingConfig: {
+ enabled: false,
+ model: "",
+ },
+
setLlmConfig: (llmConfig) => set({ llmConfig }),
setSearchApiConfig: (searchApiConfig) => set({ searchApiConfig }),
+ setEmbeddingConfig: (embeddingConfig) => set({ embeddingConfig }),
bumpDataVersion: () => set((state) => ({ dataVersion: state.dataVersion + 1 })),
}))
-export type { WikiState, LlmConfig, SearchApiConfig }
+export type { WikiState, LlmConfig, SearchApiConfig, EmbeddingConfig }