Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
fix(embedding): forward multimodal capability through AccountBoundEmbedder (#5644)
Zayn Jarvis60b32b1e0e91
diff --git a/openviking/config/embedding.py b/openviking/config/embedding.pyindex acc5dad2b..51bba1fc0 100644--- a/openviking/config/embedding.py+++ b/openviking/config/embedding.py@@ -218,6 +218,11 @@ class AccountEmbeddingProvider:prepared = resource.embedder.prepare_embedding_input(content)return account_id, resource.fingerprint, repr(prepared)+ async def supports_multimodal(self, account_id: str) -> bool:+ """Report the current resource's multimodal capability without borrowing it."""+ resource = await self._resource_for(account_id)+ return bool(resource.embedder.supports_multimodal)+async def embed(self, account_id: str, content, *, is_query: bool = False):resource = await self._borrow(account_id)try:@@ -294,6 +299,9 @@ class AccountBoundEmbedder:async def query_embedding_cache_key(self, content):return await self.provider.query_cache_key(self.account_id, content)+ async def supports_multimodal_async(self) -> bool:+ return await self.provider.supports_multimodal(self.account_id)+async def embed_async(self, content, is_query=False):return await self.embed_compatible(content, is_query=is_query)diff --git a/openviking/models/embedder/base.py b/openviking/models/embedder/base.pyindex 12cfbe284..efb9ec136 100644--- a/openviking/models/embedder/base.py+++ b/openviking/models/embedder/base.py@@ -200,6 +200,19 @@ async def embed_compat(return await embedder.embed_async(embedding_input, is_query=is_query)+async def embedder_supports_multimodal(embedder: Any) -> bool:+ """Whether ``embedder`` accepts image inputs.++ Account-bound embedders resolve the account's current resource, so the+ capability must be read asynchronously instead of from an attribute.+ """+ from openviking.config.embedding import AccountBoundEmbedder++ if isinstance(embedder, AccountBoundEmbedder):+ return await embedder.supports_multimodal_async()+ return bool(getattr(embedder, "supports_multimodal", False))++async def _embed_from_request_cache(key: Any, factory: Callable[[], Awaitable["EmbedResult"]]) -> "EmbedResult":diff --git a/openviking/retrieve/hierarchical_retriever.py b/openviking/retrieve/hierarchical_retriever.pyindex e2abb16db..6be9e25b8 100644--- a/openviking/retrieve/hierarchical_retriever.py+++ b/openviking/retrieve/hierarchical_retriever.py@@ -13,7 +13,11 @@ from typing import Any, Dict, List, Optionalfrom openviking.core.context import ContextLevelfrom openviking.core.retrieval_targets import default_target_directoriesfrom openviking.core.retrieval_types import SearchType-from openviking.models.embedder.base import EmbedResult, embed_compat+from openviking.models.embedder.base import (+ EmbedResult,+ embed_compat,+ embedder_supports_multimodal,+)from openviking.models.rerank import RerankClientfrom openviking.retrieve.retrieval_stats import get_stats_collectorfrom openviking.server.identity import RequestContext@@ -152,7 +156,9 @@ class HierarchicalRetriever:query_vector = Nonesparse_query_vector = Noneif search_type == "semantic" and self.embedder:- if image_query and not getattr(self.embedder, "supports_multimodal", False):+ # Hot path: the capability comes from the in-memory account config and+ # cached embedder resource (no I/O, no model call, nothing borrowed).+ if image_query and not await embedder_supports_multimodal(self.embedder):raise InvalidArgumentError("Image search requires a multimodal embedding model.")with telemetry.measure("search.embed_query"):embedding_input = getattr(query, "embedding_input", None) or query.querydiff --git a/tests/retrieve/test_hierarchical_retriever_image.py b/tests/retrieve/test_hierarchical_retriever_image.pyindex 1c3591c8f..b02a8814b 100644--- a/tests/retrieve/test_hierarchical_retriever_image.py+++ b/tests/retrieve/test_hierarchical_retriever_image.py@@ -117,3 +117,116 @@ async def test_image_query_requires_multimodal_embedder(monkeypatch):),ctx=_ctx(),)+++class _ProviderEmbedder(MultimodalEmbedder):+ """Fake provider client whose capability follows the account config."""++ def __init__(self, supports_multimodal: bool):+ super().__init__()+ self.supports_multimodal = supports_multimodal+ self.closed = False++ def close(self):+ self.closed = True+++async def account_embedding_provider(monkeypatch):+ from openviking.config.binding import manager_over_source+ from openviking.config.embedding import AccountEmbeddingProvider+ from openviking.config.source import MemoryConfigSource+ from openviking.config.vector import AccountVectorConfigResolver+ from openviking_cli.utils.config import set_openviking_config+ from openviking_cli.utils.config.embedding_config import EmbeddingConfig+ from openviking_cli.utils.config.open_viking_config import (+ OpenVikingConfig,+ OpenVikingConfigSingleton,+ )++ clients = []++ def create(config):+ client = _ProviderEmbedder(config.dense.input == "multimodal")+ clients.append(client)+ return client++ monkeypatch.setattr(EmbeddingConfig, "get_embedder", create)+ monkeypatch.setattr(+ "openviking.retrieve.hierarchical_retriever.VikingDBManagerProxy",+ FakeProxy,+ )+ base = OpenVikingConfig.from_dict(+ {+ "embedding": {+ "dense": {+ "model": "fake-multimodal",+ "dimension": 1,+ "provider": "openai",+ "api_key": "cluster-key",+ "input": "multimodal",+ }+ }+ }+ )+ set_openviking_config(base)+ manager = manager_over_source(MemoryConfigSource(), base_config=base)+ provider = AccountEmbeddingProvider(AccountVectorConfigResolver(manager), manager)+ await manager.initialize()+ try:+ yield manager, provider, clients+ finally:+ await provider.close()+ OpenVikingConfigSingleton.reset_instance()+++def _image_query():+ return TypedQuery(+ query="",+ context_type=None,+ intent="",+ embedding_input=[{"type": "image_url", "image_url": {"url": "data:image/png;base64,abc"}}],+ image_query=True,+ )+++async def test_image_query_through_account_bound_multimodal_embedder(account_embedding_provider):+ _manager, provider, clients = account_embedding_provider+ retriever = HierarchicalRetriever(storage=object(), embedder=provider.bind("acc"))+ retriever._rerank_client = object()++ await retriever.retrieve(_image_query(), ctx=_ctx(), limit=1)++ assert clients[-1].seen == _image_query().embedding_input+++async def test_image_query_capability_follows_account_embedding_config(+ account_embedding_provider,+):+ manager, provider, clients = account_embedding_provider+ embedder = provider.bind("acc")+ retriever = HierarchicalRetriever(storage=object(), embedder=embedder)+ retriever._rerank_client = object()+ await retriever.retrieve(_image_query(), ctx=_ctx(), limit=1)++ await manager.patch_account(+ "acc",+ {+ "embedding": {+ "dense": {+ "model": "fake-text",+ "dimension": 1,+ "input": "text",+ "credentials": [{"provider": "openai", "api_key": "acc-key"}],+ }+ }+ },+ creating=True,+ )++ with pytest.raises(InvalidArgumentError, match="multimodal embedding"):+ await retriever.retrieve(_image_query(), ctx=_ctx(), limit=1)+ assert clients[0].closed+ assert not clients[-1].seendiff --git a/tests/server/test_api_search.py b/tests/server/test_api_search.pyindex 36ac50d6c..bbbe5d292 100644--- a/tests/server/test_api_search.py+++ b/tests/server/test_api_search.py@@ -1327,3 +1327,44 @@ async def test_glob_forwards_tags_and_tag_projection_to_filesystem_service(monkeassert seen["tags"] == ["env=prod"]assert seen["include_tags"] is True++[email protected]("multimodal", [True, False])+async def test_find_image_query_uses_account_embedder_capability(+ client: httpx.AsyncClient, service, monkeypatch, multimodal: bool+):+ from openviking.models.embedder.base import DenseEmbedderBase+ from openviking_cli.utils.config.embedding_config import EmbeddingConfig++ seen = []++ class ImageEmbedder(DenseEmbedderBase):+ def __init__(self, dimension: int):+ super().__init__(model_name="test-image-embedder")+ self._dimension = dimension++ @property+ def supports_multimodal(self) -> bool:+ return multimodal++ def embed(self, content, is_query: bool = False) -> EmbedResult:+ if is_query:+ seen.append(content)+ return EmbedResult(dense_vector=[0.1] * self._dimension)++ def get_dimension(self) -> int:+ return self._dimension++ monkeypatch.setattr(EmbeddingConfig, "get_embedder", lambda self: ImageEmbedder(self.dimension))+ await service.embedding_provider.invalidate(UserIdentifier.the_default_user().account_id)+ image_url = "data:image/png;base64,iVBORw0KGgo="++ response = await client.post("/api/v1/search/find", json={"query": "", "image_url": image_url})++ if multimodal:+ assert response.status_code == 200, response.text+ assert seen and seen[-1][-1] == {"type": "image_url", "image_url": {"url": image_url}}+ else:+ assert response.status_code == 400+ assert response.json()["error"]["code"] == "INVALID_ARGUMENT"+ assert not seen