{"record":{"id":"18949133598fa0b8","repo":"mem0ai/mem0","slug":"vector-dimension-mismatch-expected-this-dimensi","errorCode":null,"errorMessage":"Vector dimension mismatch. Expected ${this.dimension}, got ${vecs[i].length}","messagePattern":"Vector dimension mismatch\\. Expected (.+?), got (.+?)","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"mem0-ts/src/oss/src/vector_stores/memory.ts","lineNumber":235,"sourceCode":"      }\n    }\n\n    return true;\n  }\n\n  async insert(\n    vectors: number[][],\n    ids: string[],\n    payloads: Record<string, any>[],\n  ): Promise<void> {\n    const stmt = this.db.prepare(\n      `INSERT OR REPLACE INTO vectors (id, vector, payload) VALUES (?, ?, ?)`,\n    );\n    const insertMany = this.db.transaction(\n      (vecs: number[][], vIds: string[], vPayloads: Record<string, any>[]) => {\n        for (let i = 0; i < vecs.length; i++) {\n          if (vecs[i].length !== this.dimension) {\n            throw new Error(\n              `Vector dimension mismatch. Expected ${this.dimension}, got ${vecs[i].length}`,\n            );\n          }\n          const vectorBuffer = Buffer.from(new Float32Array(vecs[i]).buffer);\n          stmt.run(vIds[i], vectorBuffer, JSON.stringify(vPayloads[i]));\n        }\n      },\n    );\n    insertMany(vectors, ids, payloads);\n  }\n\n  private tokenize(text: string): string[] {\n    return text.toLowerCase().split(/\\s+/).filter(Boolean);\n  }\n\n  async keywordSearch(\n    query: string,\n    topK: number = 10,","sourceCodeStart":217,"sourceCodeEnd":253,"githubUrl":"https://github.com/mem0ai/mem0/blob/001c235229be8795e3834520467bd0d661ed8f34/mem0-ts/src/oss/src/vector_stores/memory.ts#L217-L253","documentation":"Before writing rows into the SQLite 'vectors' table, insert() verifies every vector's length against the dimension the store was created with (from the embedding config at init time). A mismatch means the embedding provider produced vectors of a different size than the schema was initialized for; storing them would corrupt similarity search over the Float32 blobs.","triggerScenarios":"Creating the store with one embedder dimension (e.g. openai text-embedding-3-small = 1536) then calling add()/insert() with vectors from a different model (e.g. 384-dim all-MiniLM); switching embedding providers between runs against the same SQLite file; passing hand-built vectors of the wrong length.","commonSituations":"Changing the embedding config without deleting/recreating the SQLite database file; mixing local (Ollama nomic-embed-text, 768) and hosted models across environments; custom embedders with a different output size.","solutions":["Align the embedding provider config with the vectors being inserted (same model everywhere).","If you changed embedders intentionally, delete the SQLite DB file (or call reset/createCol) so the store re-initializes with the new dimension.","If dimension must differ, pass an explicit dimension in the store config that matches your embedder output.","Log vectors[0].length before insert when wiring up a new embedder to catch this early."],"exampleFix":"// before\nconst store = new Memory({ vectorStore: { provider: 'memory', config: { path: 'mem.db', collectionName: 'mem', embeddingModel: { name: 'openai/text-embedding-3-small', ... } } } });\nawait memory.add('hi'); // embedder now returns 768-dim -> throws on insert\n\n// after: recreate DB with the new embedder dimension\nawait fs.rm('mem.db');\nconst memory = new Memory({ embedder: { provider: 'ollama', config: { model: 'nomic-embed-text' } }, vectorStore: { provider: 'memory', config: { path: 'mem.db', collectionName: 'mem', dimension: 768 } } });","handlingStrategy":"validation","validationCode":"const dim = (await embedder.embed('probe')).length;\nif (vectors.some((v) => v.length !== dim)) {\n  throw new Error(`Embedder outputs ${dim}, got vectors of length ${new Set(vectors.map(v => v.length))}`);\n}","typeGuard":"const isDimension = (v: number[], dim: number): boolean => v.length === dim;","tryCatchPattern":"try { await store.insert(vectors, ids, payloads); }\ncatch (e) {\n  if (e instanceof Error && e.message.startsWith('Vector dimension mismatch')) {\n    // embedder changed: recreate store/DB with the new dimension, re-embed, retry\n  } else throw e;\n}","preventionTips":["Pin one embedding model per SQLite DB file; change model = new file/collection.","Pass an explicit dimension in the store config matching your embedder.","Delete the DB file when switching embedders in dev/test."],"tags":["dimension-mismatch","embeddings","sqlite","vector-store","config"],"backgroundTag":null,"analyzedSha":"001c235229be8795e3834520467bd0d661ed8f34","analyzedAt":"2026-08-15T01:55:42.685Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}