agentmemory icon indicating copy to clipboard operation
agentmemory copied to clipboard

feat(vector): auto-index observations into vector store | 向量索引自动集成

Open mechanic-Q opened this issue 7 months ago • 4 comments

Summary | 概述

Automatically add compressed observations to the VectorIndex during the observe lifecycle, enabling hybrid BM25+Vector search without manual index building.

在观察生命周期中自动将压缩记忆添加到向量索引,实现 BM25+向量混合搜索。

Motivation | 动机

The VectorIndex and EmbeddingProvider infrastructure exists but observations were only added to the BM25 index. The vector index remained empty unless manually populated. This meant the hybrid search (BM25 + Vector RRF fusion) couldn't leverage semantic similarity — only BM25 keyword matching was active. For non-English content (Chinese, multilingual), BM25 alone is insufficient because the tokenizer can't handle CJK text well. Vector search bridges this gap.

向量索引基础设施已存在,但观察结果仅被添加到 BM25 索引,向量索引保持为空。混合搜索无法利用语义相似度,仅靠 BM25 关键词匹配。对于中文等非英文内容,纯 BM25 效果差,向量搜索可以弥补这一差距。

Changes | 改动

  • src/functions/observe.ts: After synthetic compression and BM25 indexing, auto-embed the narrative and add to vector index
  • src/index.ts: Pass vectorIndex and embeddingProvider to registerObserveFunction
  • Auto-indexing runs within try-catch — embedding failures are logged but don't block observation capture
  • Only activates when an embedding provider is configured (opt-in by setting AGENTMEMORY_LOCAL_EMBEDDING_MODEL or cloud API keys)

Combined with PR #223 (configurable embedding)

# Enable multilingual hybrid search (BM25 + Vector)
AGENTMEMORY_LOCAL_EMBEDDING_MODEL=Xenova/bge-m3

This combination gives agentmemory full Chinese/multilingual semantic search capability — BM25 handles exact terms, vector handles meaning.

Backwards Compatibility | 向后兼容

New params are optional. When vectorIndex or embeddingProvider is null/undefined (default), the auto-indexing is skipped. No behavior change for existing deployments.

Summary by CodeRabbit

Release Notes

  • New Features
    • Added optional vector indexing and embedding support for observations, enabling automatic metadata indexing when configured
    • Enhanced with external control over vector auto-indexing functionality
    • Improved resilience through graceful error handling that prevents vector operation failures from disrupting observation workflows

mechanic-Q avatar May 02 '26 07:05 mechanic-Q

@mechanic-Q is attempting to deploy a commit to the rohitg00's projects Team on Vercel.

A member of the Team first needs to authorize it.

vercel[bot] avatar May 02 '26 07:05 vercel[bot]

📝 Walkthrough

Walkthrough

Updated registerObserveFunction to accept optional vectorIndex and embeddingProvider parameters. During non-LLM compression, the function now attempts to embed and index a combined "title + narrative" string, with embedding failures logged but not blocking the observation flow.

Changes

Vector Indexing Integration

Layer / File(s) Summary
Type Imports & Signature
src/functions/observe.ts (lines 2, 11, 39–43)
Added imports for EmbeddingProvider and VectorIndex. Updated registerObserveFunction signature to accept optional vectorIndex and embeddingProvider parameters.
Embedding & Indexing Logic
src/functions/observe.ts (lines 244–255)
After synthetic compression creation, conditionally embeds a combined "title + narrative" string and adds the vector to the index when both providers are available. Embedding/indexing errors are caught and logged without aborting the observation flow.
Initialization Wiring
src/index.ts (line 184)
Updated registerObserveFunction call to pass vectorIndex and embeddingProvider arguments during function registration.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

A rabbit hops through vectors bright, 🐰
Embedding titles in the night,
If indexing fails, we warn but stay,
Observations flow the rabbit's way! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(vector): auto-index observations into vector store' clearly and specifically describes the main change: adding automatic vector indexing of observations. It is concise, directly related to the primary feature being added, and follows conventional commit format.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • [ ] Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
Review rate limit: 4/8 reviews remaining, refill in 29 minutes and 56 seconds.

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 02 '26 07:05 coderabbitai[bot]

Hi, When AGENTMEMORY_AUTO_COMPRESS=true, mem::observe triggers mem::compress and does not run the new vectorIndex.add() code path, so the vector index stays empty even if an EmbeddingProvider is configured.

Severity: action required | Category: correctness

How to fix: Index vectors in mem::compress

Agent prompt to fix - you can give this to your LLM of choice:

Issue description

With AGENTMEMORY_AUTO_COMPRESS=true, mem::observe delegates compression to mem::compress, but vectors are only added during the synthetic compression path. This leaves the VectorIndex empty in the LLM compression mode.

Issue Context

  • Vector indexing currently happens only for buildSyntheticCompression(raw) output.
  • mem::compress persists the compressed observation and updates BM25 (getSearchIndex().add(compressed)), but does not embed/store vectors.

Fix Focus Areas

  • src/functions/observe.ts[222-256]
  • src/functions/compress.ts[170-178]

What to change

  • Add optional vectorIndex + embeddingProvider plumb-through to registerCompressFunction and embed compressed.title + ' ' + compressed.narrative (or similar) inside mem::compress after KV set/BM25 add.
  • Ensure failures are best-effort (log warn, do not fail compression).
  • Keep behavior consistent with synthetic path (same obsId/sessionId used).

Spotted by Qodo code review - free for open-source projects.

Qodo-Free-For-OSS avatar May 03 '26 10:05 Qodo-Free-For-OSS

Reviewed — this fixes a real gap. Verified locally: vectorIndex.add(...) was only called from IndexPersistence.restoreFrom() on startup, never from the live observe pipeline. So unless an instance had been running long enough for persistence to kick in (or had imported a snapshot), the in-memory vector index was empty even though embeddingProvider was wired. New observations went into BM25 only, defeating the point of the hybrid search story.

What I like:

  • Threading vectorIndex + embeddingProvider through registerObserveFunction(...) — explicit dependencies, easy to see the data flow at the call site in index.ts.
  • The catch block logs and continues. Embedding-provider failures shouldn't kill an observation; BM25 still indexes it.
  • Built from synthetic.title + " " + synthetic.narrative — same shape the persistence layer uses, so the embedding semantics stay consistent across live and restored vectors.

Two small notes:

  • The embed call is awaited inline. On a busy session with a heavy embedding provider (OpenAI / Voyage), this will add latency to every PostToolUse observation. Worth flagging in the PR body so we know when to revisit. The non-blocking alternative would be void embeddingProvider.embed(...).then(vec => vectorIndex.add(obsId, payload.sessionId, vec)), but that risks ordering issues if observations fire faster than embeds resolve. Awaiting is the safer default.
  • IndexPersistence.save() should now also be picking up these live-added vectors — please confirm a save-then-reload cycle preserves them. (If save() reads from vectorIndex.serialize() and that's the same instance, this is automatic, but worth a one-line check.)

No blockers. Approving — holding for @rohitg00 to land.

rohitg00 avatar May 08 '26 18:05 rohitg00