Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(rag): honor the configured default embedding model and guarantee chunk sizes fit its context
Akarshan Biswas22fda86f30c7
diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.tsindex 8ba3056e4..e0fe47b19 100644--- a/extensions/llamacpp-extension/src/index.ts+++ b/extensions/llamacpp-extension/src/index.ts@@ -3386,7 +3386,13 @@ export default class llamacpp_extension extends AIEngine {}}- async embed(text: string[]): Promise<EmbeddingResponse> {+ /**+ * Resolves the default/preferred embedding model, importing and loading+ * sentence-transformer-mini as the fallback, then ensures a session exists.+ * Shared by embed() and getEmbeddingContextSize() so both agree on which+ * model is "the" embedding model.+ */+ private async ensureEmbeddingModelLoaded(): Promise<SessionInfo> {const downloadedModelList = await this.list()const installedEmbedding = downloadedModelList.filter((m) => (m as any).embedding === true@@ -3394,11 +3400,11 @@ export default class llamacpp_extension extends AIEngine {const hasMini = downloadedModelList.some((m) => m.id === 'sentence-transformer-mini')- let preferred = getDefaultEmbeddingModelId('llamacpp')+ let preferred = await getDefaultEmbeddingModelId('llamacpp')if (!preferred && installedEmbedding.length === 1 && !hasMini) {preferred = installedEmbedding[0].id- setDefaultEmbeddingModelId('llamacpp', preferred)+ await setDefaultEmbeddingModelId('llamacpp', preferred)logger.info(`Auto-promoted "${preferred}" as default embedding model (single installed model, sentence-transformer-mini not present)`)@@ -3427,6 +3433,51 @@ export default class llamacpp_extension extends AIEngine {}sInfo = await this.load(targetModelId, undefined, true)}+ return sInfo as SessionInfo+ }++ /**+ * Actual post-fit context window of the embedding model, read from the+ * router's /props endpoint (the same source getModelProps uses for chat+ * models). Used by RAG ingestion to size chunks so they don't exceed the+ * model's n_ctx (e.g. sentence-transformer-mini natively caps at 256).+ */+ async getEmbeddingContextSize(): Promise<number | undefined> {+ const sInfo = await this.ensureEmbeddingModelLoaded()+ const props = await this.getModelProps(sInfo.model_id)+ return props?.nCtx+ }++ /**+ * Real token counts from the embedding model's own tokenizer via /tokenize+ * on its session port. Char-based chunking can't reliably predict token+ * count (subword tokenizers vary widely by content), so callers that need+ * a hard guarantee against exceed_context_size_error should verify with+ * this rather than estimating from character length.+ */+ async countEmbeddingTokens(texts: string[]): Promise<number[]> {+ const sInfo = await this.ensureEmbeddingModelLoaded()+ const counts: number[] = []+ for (const text of texts) {+ const res = await fetch(`http://localhost:${sInfo.port}/tokenize`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'Authorization': `Bearer ${sInfo.api_key}`,+ },+ body: JSON.stringify({ content: text }),+ })+ if (!res.ok) {+ throw new Error(`Tokenize request failed with status ${res.status}`)+ }+ const json = (await res.json()) as { tokens?: unknown[] }+ counts.push(Array.isArray(json.tokens) ? json.tokens.length : 0)+ }+ return counts+ }++ async embed(text: string[]): Promise<EmbeddingResponse> {+ const sInfo = await this.ensureEmbeddingModelLoaded()const ubatchSize =(this.config?.ubatch_size && this.config.ubatch_size > 0@@ -3457,7 +3508,7 @@ export default class llamacpp_extension extends AIEngine {}const sendBatch = async (batchInput: string[]) => {- const response = await attemptRequest(sInfo as SessionInfo, batchInput)+ const response = await attemptRequest(sInfo, batchInput)if (!response.ok) {const errorData = await response.json().catch(() => null)throw new Error(@@ -3474,7 +3525,7 @@ export default class llamacpp_extension extends AIEngine {}return mergeEmbedResponses(- (sInfo as SessionInfo).model_id,+ sInfo.model_id,batchResults) as EmbeddingResponse}diff --git a/extensions/llamacpp-extension/src/util.ts b/extensions/llamacpp-extension/src/util.tsindex d8a337e7a..31b6d9f96 100644--- a/extensions/llamacpp-extension/src/util.ts+++ b/extensions/llamacpp-extension/src/util.ts@@ -1,3 +1,5 @@+import { invoke } from '@tauri-apps/api/core'+// File path utilitiesexport function basenameNoExt(filePath: string): string {const VALID_EXTENSIONS = [".tar.gz", ".zip"];@@ -32,11 +34,34 @@ interface ProxyState {noProxy: string}-export function getDefaultEmbeddingModelId(+const DEFAULT_EMBEDDING_MODEL_KEY = 'default-embedding-model'++// The web-app's useDefaultEmbeddingModel store persists this key through+// the Rust settings backend (settings_get/settings_set -> settings.json),+// not webview localStorage, on desktop. Read/write the same backend so this+// extension sees the model the user actually picked in Settings; localStorage+// is only a fallback for `dev:web` (no Tauri shell).+async function readDefaultEmbeddingModelRaw(): Promise<string | null> {+ try {+ const value = await invoke<string | null>('settings_get', {+ key: DEFAULT_EMBEDDING_MODEL_KEY,+ })+ if (value != null) return value+ } catch {+ /* not running under Tauri, or command unavailable */+ }+ try {+ return localStorage.getItem(DEFAULT_EMBEDDING_MODEL_KEY)+ } catch {+ return null+ }+}++export async function getDefaultEmbeddingModelId(provider: string = 'llamacpp'-): string | undefined {+): Promise<string | undefined> {try {- const raw = localStorage.getItem('default-embedding-model')+ const raw = await readDefaultEmbeddingModelRaw()if (!raw) return undefinedconst parsed = JSON.parse(raw)const map = parsed?.state?.defaultByProvider@@ -47,18 +72,31 @@ export function getDefaultEmbeddingModelId(}}-export function setDefaultEmbeddingModelId(provider: string, modelId: string) {+export async function setDefaultEmbeddingModelId(+ provider: string,+ modelId: string+) {try {- const raw = localStorage.getItem('default-embedding-model')+ const raw = await readDefaultEmbeddingModelRaw()const parsed = raw ? JSON.parse(raw) : { state: {}, version: 0 }const state = parsed.state ?? {}const map = state.defaultByProvider ?? {}map[provider] = modelIdparsed.state = { ...state, defaultByProvider: map }if (parsed.version === undefined) parsed.version = 0- localStorage.setItem('default-embedding-model', JSON.stringify(parsed))+ const serialized = JSON.stringify(parsed)+ try {+ await invoke('settings_set', {+ key: DEFAULT_EMBEDDING_MODEL_KEY,+ value: serialized,+ })+ return+ } catch {+ /* not running under Tauri, or command unavailable */+ }+ localStorage.setItem(DEFAULT_EMBEDDING_MODEL_KEY, serialized)} catch {- /* localStorage write failed; non-fatal */+ /* non-fatal */}}diff --git a/extensions/vector-db-extension/src/index.ts b/extensions/vector-db-extension/src/index.tsindex a3742c4ac..0a461b5b7 100644--- a/extensions/vector-db-extension/src/index.ts+++ b/extensions/vector-db-extension/src/index.ts@@ -2,6 +2,15 @@ import { VectorDBExtension, type SearchMode, type VectorDBStatus, type VectorChuimport * as vecdb from '@janhq/tauri-plugin-vector-db-api'import * as ragApi from '@janhq/tauri-plugin-rag-api'+// Conservative average for English/dense text; real tokenizers vary (CJK+// runs closer to 1-2 chars/token), so this stays a deliberate underestimate+// rather than an exact conversion.+const CHARS_PER_TOKEN_ESTIMATE = 3+const CONTEXT_SAFETY_MARGIN = 0.8+const MIN_CHUNK_SIZE_CHARS = 64+// Reserves room for BOS/special tokens the tokenizer adds beyond raw content.+const EMBEDDING_CONTEXT_SAFETY_TOKENS = 8+export default class VectorDBExt extends VectorDBExtension {async onLoad(): Promise<void> {// no-op@@ -144,13 +153,74 @@ export default class VectorDBExt extends VectorDBExtension {// Optional helper for chunkingprivate async chunkText(text: string, chunkSize: number, chunkOverlap: number): Promise<string[]> {- return await vecdb.chunkText(text, chunkSize, chunkOverlap)+ const safeChunkSize = await this.clampToEmbeddingContext(chunkSize, chunkOverlap)+ const rawChunks = await vecdb.chunkText(text, safeChunkSize, chunkOverlap)+ return await this.ensureChunksFitEmbeddingContext(rawChunks)}- private async embedTexts(texts: string[]): Promise<number[][]> {- const llm = window.core?.extensionManager.getByName('@janhq/llamacpp-extension') as AIEngine & {+ /**+ * chunk_text (Rust) splits by raw character count with no tokenizer+ * awareness. Clamp the char budget to the embedding model's real n_ctx so+ * most chunks fit on the first try (cheap, but only an estimate).+ */+ private async clampToEmbeddingContext(chunkSize: number, chunkOverlap: number): Promise<number> {+ const llm = this.getEmbeddingEngine()+ if (!llm?.getEmbeddingContextSize) return chunkSize+ const ctxSize = await llm.getEmbeddingContextSize().catch(() => undefined)+ if (!ctxSize || ctxSize <= 0) return chunkSize+ const safeMaxChars = Math.floor(+ ctxSize * CHARS_PER_TOKEN_ESTIMATE * CONTEXT_SAFETY_MARGIN+ )+ const budget = Math.max(MIN_CHUNK_SIZE_CHARS, safeMaxChars - chunkOverlap)+ return Math.min(chunkSize, budget)+ }++ /**+ * Character-based estimates can't be trusted for every tokenizer/content+ * mix (subword tokenizers on dense text can run well under the assumed+ * chars-per-token ratio). Verify each chunk against the embedding model's+ * real tokenizer and recursively halve any chunk that still doesn't fit,+ * so ingestion can never hit exceed_context_size_error.+ */+ private async ensureChunksFitEmbeddingContext(chunks: string[]): Promise<string[]> {+ const llm = this.getEmbeddingEngine()+ if (!llm?.getEmbeddingContextSize || !llm?.countEmbeddingTokens) return chunks+ const ctxSize = await llm.getEmbeddingContextSize().catch(() => undefined)+ if (!ctxSize || ctxSize <= 0) return chunks+ const budget = Math.max(1, ctxSize - EMBEDDING_CONTEXT_SAFETY_TOKENS)++ const out: string[] = []+ for (const chunk of chunks) {+ out.push(...(await this.splitChunkToFit(chunk, budget, llm)))+ }+ return out+ }++ private async splitChunkToFit(+ text: string,+ budget: number,+ llm: { countEmbeddingTokens: (texts: string[]) => Promise<number[]> }+ ): Promise<string[]> {+ if (!text) return []+ const [count] = await llm.countEmbeddingTokens([text]).catch(() => [0])+ if (count <= budget || text.length <= MIN_CHUNK_SIZE_CHARS) return [text]+ const mid = Math.floor(text.length / 2)+ return [+ ...(await this.splitChunkToFit(text.slice(0, mid), budget, llm)),+ ...(await this.splitChunkToFit(text.slice(mid), budget, llm)),+ ]+ }++ private getEmbeddingEngine() {+ return window.core?.extensionManager.getByName('@janhq/llamacpp-extension') as AIEngine & {embed?: (texts: string[]) => Promise<{ data: Array<{ embedding: number[]; index: number }> }>+ getEmbeddingContextSize?: () => Promise<number | undefined>+ countEmbeddingTokens?: (texts: string[]) => Promise<number[]>}+ }++ private async embedTexts(texts: string[]): Promise<number[][]> {+ const llm = this.getEmbeddingEngine()if (!llm?.embed) throw new Error('llamacpp extension not available')const res = await llm.embed(texts)