Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 35 additions & 3 deletions mempalace/backends/chroma.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,31 @@
logger = logging.getLogger(__name__)


def get_embedding_function():
"""Return an embedding function based on env, or ``None`` for Chroma's default.

Set ``EMBEDDING_PROVIDER=ollama`` to route embeddings through a local
Ollama server (GPU-accelerated). Tunables:

- ``OLLAMA_URL`` (default ``http://localhost:11434``) - base URL
- ``OLLAMA_EMBED_MODEL`` (default ``nomic-embed-text``)
- ``OLLAMA_EMBED_TIMEOUT`` seconds (default ``60``)

Returning ``None`` keeps ChromaDB's ``DefaultEmbeddingFunction`` (ONNX
MiniLM, 384 dims, CPU) for backward compatibility with existing palaces.
"""
provider = os.environ.get("EMBEDDING_PROVIDER", "").lower()

Copilot AI Apr 17, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

provider = os.environ.get("EMBEDDING_PROVIDER", "").lower() doesn't handle leading/trailing whitespace (e.g., " ollama"), which can make the opt-in flag unexpectedly fail. Consider normalizing with .strip().lower() before comparing.

Suggested change
provider = os.environ.get("EMBEDDING_PROVIDER", "").lower()
provider = os.environ.get("EMBEDDING_PROVIDER", "").strip().lower()

Copilot uses AI. Check for mistakes.
if provider != "ollama":
return None
from chromadb.utils.embedding_functions import OllamaEmbeddingFunction

return OllamaEmbeddingFunction(
url=os.environ.get("OLLAMA_URL") or "http://localhost:11434",
model_name=os.environ.get("OLLAMA_EMBED_MODEL") or "nomic-embed-text",
timeout=int(os.environ.get("OLLAMA_EMBED_TIMEOUT") or "60"),
)
Comment on lines +33 to +55

Copilot AI Apr 17, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

get_embedding_function() is newly introduced but currently has no automated coverage. Consider adding unit tests that (1) default to None when EMBEDDING_PROVIDER is unset/other values, and (2) with EMBEDDING_PROVIDER=ollama reads URL/model/timeout defaults + overrides from env so regressions are caught without requiring a live Ollama server (can assert the returned object type/attributes or that it is callable).

Copilot uses AI. Check for mistakes.
Comment on lines +51 to +55

Copilot AI Apr 17, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

timeout=int(os.environ.get("OLLAMA_EMBED_TIMEOUT") or "60") will raise ValueError for a non-integer env value, and that error will be fairly opaque to users. Consider validating/parsing with a clearer exception message (e.g., "OLLAMA_EMBED_TIMEOUT must be an integer number of seconds") or falling back to the default when parsing fails.

Copilot uses AI. Check for mistakes.


def _fix_blob_seq_ids(palace_path: str):
"""Fix ChromaDB 0.6.x -> 1.5.x migration bug: BLOB seq_ids -> INTEGER.

Expand Down Expand Up @@ -124,12 +149,17 @@ def get_collection(self, palace_path: str, collection_name: str, create: bool =
pass

client = self._client(palace_path)
ef = get_embedding_function()
if create:
collection = client.get_or_create_collection(
collection_name, metadata={"hnsw:space": "cosine"}
collection_name,
metadata={"hnsw:space": "cosine"},
embedding_function=ef,
)
else:
collection = client.get_collection(collection_name)
collection = client.get_collection(
collection_name, embedding_function=ef
)

Copilot AI Apr 17, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ef = get_embedding_function() can be None, but embedding_function=ef is always passed into get_or_create_collection() / get_collection(). To avoid type mismatches (and potential runtime issues if chromadb doesn't accept None here), consider only including the embedding_function kwarg when ef is not None and otherwise letting Chroma use its default behavior.

Copilot uses AI. Check for mistakes.
return ChromaCollection(collection)

def get_or_create_collection(
Expand All @@ -147,6 +177,8 @@ def create_collection(
) -> "ChromaCollection":
"""Create (not get-or-create) *collection_name* with cosine HNSW space."""
collection = self._client(palace_path).create_collection(
collection_name, metadata={"hnsw:space": hnsw_space}
collection_name,
metadata={"hnsw:space": hnsw_space},
embedding_function=get_embedding_function(),
)
Comment on lines 209 to 213

Copilot AI Apr 17, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

create_collection(..., embedding_function=get_embedding_function()) will pass None through when Ollama is not enabled. If the intent is "use Chroma's default embedding function", consider conditionally omitting the kwarg when get_embedding_function() returns None for consistency with older/newer chromadb versions and to keep typing clean.

Copilot uses AI. Check for mistakes.
return ChromaCollection(collection)
14 changes: 11 additions & 3 deletions mempalace/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
sanitize_content,
)
from .version import __version__ # noqa: E402
from .backends.chroma import ChromaBackend, ChromaCollection # noqa: E402
from .backends.chroma import ChromaBackend, ChromaCollection, get_embedding_function # noqa: E402
from .query_sanitizer import sanitize_query # noqa: E402
from .searcher import search_memories # noqa: E402
from .palace_graph import ( # noqa: E402
Expand Down Expand Up @@ -216,16 +216,24 @@ def _get_collection(create=False):
global _collection_cache, _metadata_cache, _metadata_cache_time
try:
client = _get_client()
ef = get_embedding_function()
if create:
Comment on lines 218 to 223

Copilot AI Apr 17, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because _get_collection() wraps the whole block in except Exception: return None, any misconfiguration in get_embedding_function() (e.g., invalid OLLAMA_EMBED_TIMEOUT, missing Ollama EF in older chromadb installs) will be silently swallowed and later surfaces as "no palace" behavior. Consider at least logging the exception (or narrowing the exception handling) so embedding-provider configuration errors are debuggable.

Copilot uses AI. Check for mistakes.
_collection_cache = ChromaCollection(
client.get_or_create_collection(
_config.collection_name, metadata={"hnsw:space": "cosine"}
_config.collection_name,
metadata={"hnsw:space": "cosine"},
embedding_function=ef, # type: ignore[arg-type]
)

Copilot AI Apr 17, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new # type: ignore[arg-type] on embedding_function=ef is masking a real typing mismatch introduced by allowing ef to be None. Prefer avoiding the ignore by only passing embedding_function when ef is not None (e.g., build a kwargs dict), or by adjusting get_embedding_function()'s return type / local typing so the call sites stay type-safe.

Copilot uses AI. Check for mistakes.
)
_metadata_cache = None
_metadata_cache_time = 0
elif _collection_cache is None:
_collection_cache = ChromaCollection(client.get_collection(_config.collection_name))
_collection_cache = ChromaCollection(
client.get_collection(
_config.collection_name,
embedding_function=ef, # type: ignore[arg-type]
)
)
_metadata_cache = None
_metadata_cache_time = 0
return _collection_cache
Expand Down
Loading