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
Feat:支持原生部署的vikingdb (#84)
chuanbao666e4251dc1521e
diff --git a/openviking/storage/vectordb/collection/vikingdb_clients.py b/openviking/storage/vectordb/collection/vikingdb_clients.pynew file mode 100644index 000000000..287d039aa--- /dev/null+++ b/openviking/storage/vectordb/collection/vikingdb_clients.py@@ -0,0 +1,100 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: Apache-2.0+import json+from typing import Any, Dict, Optional++import requests++from openviking.utils.logger import default_logger as logger++# Default request timeout (seconds)+DEFAULT_TIMEOUT = 30++# VikingDB API Version+VIKING_DB_VERSION = "2025-06-09"++# SDK Action to VikingDB API path and method mapping+VIKINGDB_APIS = {+ # Collection APIs+ "ListVikingdbCollection": ("/api/vikingdb/ListCollection", "POST"),+ "CreateVikingdbCollection": ("/api/vikingdb/CreateCollection", "POST"),+ "DeleteVikingdbCollection": ("/api/vikingdb/DeleteCollection", "POST"),+ "UpdateVikingdbCollection": ("/api/vikingdb/UpdateCollection", "POST"),+ "GetVikingdbCollection": ("/api/vikingdb/GetCollection", "POST"),+ # Index APIs+ "ListVikingdbIndex": ("/api/vikingdb/ListIndex", "POST"),+ "CreateVikingdbIndex": ("/api/vikingdb/CreateIndex", "POST"),+ "DeleteVikingdbIndex": ("/api/vikingdb/DeleteIndex", "POST"),+ "UpdateVikingdbIndex": ("/api/vikingdb/UpdateIndex", "POST"),+ "GetVikingdbIndex": ("/api/vikingdb/GetIndex", "POST"),+ # ApiKey APIs+ "ListVikingdbApiKey": ("/api/vikingdb/list", "POST"),+ "CreateVikingdbApiKey": ("/api/vikingdb/create", "POST"),+ "DeleteVikingdbApiKey": ("/api/vikingdb/delete", "POST"),+ "UpdateVikingdbApiKey": ("/api/vikingdb/update", "POST"),+ "ListVikingdbApiKeyResources": ("/api/apikey/resource/list", "POST"),+}+++class VikingDBClient:+ """+ Client for VikingDB private deployment.+ Uses custom host and headers for authentication/context.+ """++ def __init__(self, host: str, headers: Optional[Dict[str, str]] = None):+ """+ Initialize VikingDB client.++ Args:+ host: VikingDB service host (e.g., "http://localhost:8080")+ headers: Custom headers for requests+ """+ self.host = host.rstrip("/")+ self.headers = headers or {}++ if not self.host:+ raise ValueError("Host is required for VikingDBClient")++ def do_req(+ self,+ method: str,+ path: str = "/",+ req_params: Optional[Dict[str, Any]] = None,+ req_body: Optional[Dict[str, Any]] = None,+ ) -> requests.Response:+ """+ Perform HTTP request to VikingDB service.++ Args:+ method: HTTP method (GET, POST, etc.)+ path: Request path+ req_params: Query parameters+ req_body: Request body++ Returns:+ requests.Response object+ """+ if not path.startswith("/"):+ path = "/" + path++ url = f"{self.host}{path}"+ headers = {+ "Accept": "application/json",+ "Content-Type": "application/json",+ }+ headers.update(self.headers)++ try:+ response = requests.request(+ method=method,+ url=url,+ headers=headers,+ params=req_params,+ data=json.dumps(req_body) if req_body is not None else None,+ timeout=DEFAULT_TIMEOUT,+ )+ return response+ except Exception as e:+ logger.error(f"Request to {url} failed: {e}")+ raise ediff --git a/openviking/storage/vectordb/collection/vikingdb_collection.py b/openviking/storage/vectordb/collection/vikingdb_collection.pynew file mode 100644index 000000000..5a877edb0--- /dev/null+++ b/openviking/storage/vectordb/collection/vikingdb_collection.py@@ -0,0 +1,396 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: Apache-2.0+import json+from typing import Any, Dict, List, Optional++from openviking.storage.vectordb.collection.collection import ICollection+from openviking.storage.vectordb.collection.result import (+ AggregateResult,+ DataItem,+ FetchDataInCollectionResult,+ SearchItemResult,+ SearchResult,+)+from openviking.storage.vectordb.collection.vikingdb_clients import (+ VIKINGDB_APIS,+ VikingDBClient,+)+from openviking.utils.logger import default_logger as logger+++class VikingDBCollection(ICollection):+ """+ VikingDB collection implementation for private deployment.+ """++ def __init__(+ self,+ host: str,+ headers: Optional[Dict[str, str]] = None,+ meta_data: Optional[Dict[str, Any]] = None,+ ):+ super().__init__()+ self.client = VikingDBClient(host, headers)+ self.meta_data = meta_data if meta_data is not None else {}+ self.project_name = self.meta_data.get("ProjectName", "default")+ self.collection_name = self.meta_data.get("CollectionName", "")++ def _console_post(self, data: Dict[str, Any], action: str):+ path, method = VIKINGDB_APIS[action]+ response = self.client.do_req(method, path=path, req_body=data)+ if response.status_code != 200:+ logger.error(f"Request to {action} failed: {response.text}")+ return {}+ try:+ result = response.json()+ if "Result" in result:+ return result["Result"]+ return result.get("data", {})+ except json.JSONDecodeError:+ return {}++ def _console_get(self, params: Optional[Dict[str, Any]], action: str):+ if params is None:+ params = {}+ path, method = VIKINGDB_APIS[action]+ # Console GET actions are actually POSTs in VikingDB API+ response = self.client.do_req(method, path=path, req_body=params)++ if response.status_code != 200:+ logger.error(f"Request to {action} failed: {response.text}")+ return {}+ try:+ result = response.json()+ return result.get("Result", {})+ except json.JSONDecodeError:+ return {}++ def _data_post(self, path: str, data: Dict[str, Any]):+ response = self.client.do_req("POST", path, req_body=data)+ if response.status_code != 200:+ logger.error(f"Request to {path} failed: {response.text}")+ return {}+ try:+ result = response.json()+ return result.get("result", {})+ except json.JSONDecodeError:+ return {}++ def _data_get(self, path: str, params: Dict[str, Any]):+ response = self.client.do_req("GET", path, req_params=params)+ if response.status_code != 200:+ logger.error(f"Request to {path} failed: {response.text}")+ return {}+ try:+ result = response.json()+ return result.get("result", {})+ except json.JSONDecodeError:+ return {}++ def update(self, fields: Optional[Dict[str, Any]] = None, description: Optional[str] = None):+ data = {+ "ProjectName": self.project_name,+ "CollectionName": self.collection_name,+ }+ if fields:+ data["Fields"] = fields+ if description is not None:+ data["Description"] = description++ return self._console_post(data, action="UpdateVikingdbCollection")++ def get_meta_data(self):+ params = {+ "ProjectName": self.project_name,+ "CollectionName": self.collection_name,+ }+ return self._console_get(params, action="GetVikingdbCollection")++ def close(self):+ pass++ def drop(self):+ raise NotImplementedError("collection should be managed manually")++ def create_index(self, index_name: str, meta_data: Dict[str, Any]):+ raise NotImplementedError("index should be pre-created")++ def has_index(self, index_name: str):+ indexes = self.list_indexes()+ return index_name in indexes if isinstance(indexes, list) else False++ def get_index(self, index_name: str):+ return self.get_index_meta_data(index_name)++ def list_indexes(self):+ params = {+ "ProjectName": self.project_name,+ "CollectionName": self.collection_name,+ }+ return self._console_get(params, action="ListVikingdbIndex")++ def update_index(+ self,+ index_name: str,+ scalar_index: Optional[Dict[str, Any]] = None,+ description: Optional[str] = None,+ ):+ raise NotImplementedError("index should be managed manually")++ def get_index_meta_data(self, index_name: str):+ params = {+ "ProjectName": self.project_name,+ "CollectionName": self.collection_name,+ "IndexName": index_name,+ }+ return self._console_get(params, action="GetVikingdbIndex")++ def drop_index(self, index_name: str):+ raise NotImplementedError("index should be managed manually")++ def upsert_data(self, data_list: List[Dict[str, Any]], ttl: int = 0):+ path = "/api/vikingdb/data/upsert"+ data = {+ "project": self.project_name,+ "collection_name": self.collection_name,+ "data": data_list,+ "ttl": ttl,+ }+ return self._data_post(path, data)++ def fetch_data(self, primary_keys: List[Any]) -> FetchDataInCollectionResult:+ path = "/api/vikingdb/data/fetch_in_collection"+ data = {+ "project": self.project_name,+ "collection_name": self.collection_name,+ "ids": primary_keys,+ }+ resp_data = self._data_post(path, data)+ return self._parse_fetch_result(resp_data)++ def delete_data(self, primary_keys: List[Any]):+ path = "/api/vikingdb/data/delete"+ data = {+ "project": self.project_name,+ "collection_name": self.collection_name,+ "ids": primary_keys,+ }+ return self._data_post(path, data)++ def delete_all_data(self):+ path = "/api/vikingdb/data/delete"+ data = {+ "project": self.project_name,+ "collection_name": self.collection_name,+ "del_all": True,+ }+ return self._data_post(path, data)++ def _parse_fetch_result(self, data: Dict[str, Any]) -> FetchDataInCollectionResult:+ result = FetchDataInCollectionResult()+ if isinstance(data, dict):+ if "fetch" in data:+ fetch = data.get("fetch", [])+ result.items = [+ DataItem(+ id=item.get("id"),+ fields=item.get("fields"),+ )+ for item in fetch+ ]+ if "ids_not_exist" in data:+ result.ids_not_exist = data.get("ids_not_exist", [])+ return result++ def _parse_search_result(self, data: Dict[str, Any]) -> SearchResult:+ result = SearchResult()+ if isinstance(data, dict) and "data" in data:+ data_list = data.get("data", [])+ result.data = [+ SearchItemResult(+ id=item.get("id"),+ fields=item.get("fields"),+ score=item.get("score"),+ )+ for item in data_list+ ]+ return result++ def search_by_vector(+ self,+ index_name: str,+ dense_vector: Optional[List[float]] = None,+ limit: int = 10,+ offset: int = 0,+ filters: Optional[Dict[str, Any]] = None,+ sparse_vector: Optional[Dict[str, float]] = None,+ output_fields: Optional[List[str]] = None,+ ) -> SearchResult:+ path = "/api/vikingdb/data/search/vector"+ data = {+ "project": self.project_name,+ "collection_name": self.collection_name,+ "index_name": index_name,+ "dense_vector": dense_vector,+ "sparse_vector": sparse_vector or {},+ "filter": filters,+ "output_fields": output_fields,+ "limit": limit,+ "offset": offset,+ }+ resp_data = self._data_post(path, data)+ return self._parse_search_result(resp_data)++ def search_by_id(+ self,+ index_name: str,+ id: Any,+ limit: int = 10,+ offset: int = 0,+ filters: Optional[Dict[str, Any]] = None,+ output_fields: Optional[List[str]] = None,+ ) -> SearchResult:+ path = "/api/vikingdb/data/search/id"+ data = {+ "project": self.project_name,+ "collection_name": self.collection_name,+ "index_name": index_name,+ "id": id,+ "filter": filters,+ "output_fields": output_fields,+ "limit": limit,+ "offset": offset,+ }+ resp_data = self._data_post(path, data)+ return self._parse_search_result(resp_data)++ def search_by_multimodal(+ self,+ index_name: str,+ text: Optional[str] = None,+ image: Optional[Any] = None,+ video: Optional[Any] = None,+ limit: int = 10,+ offset: int = 0,+ filters: Optional[Dict[str, Any]] = None,+ output_fields: Optional[List[str]] = None,+ ) -> SearchResult:+ path = "/api/vikingdb/data/search/multi_modal"+ data = {+ "project": self.project_name,+ "collection_name": self.collection_name,+ "index_name": index_name,+ "text": text,+ "image": image,+ "video": video,+ "filter": filters,+ "output_fields": output_fields,+ "limit": limit,+ "offset": offset,+ }+ resp_data = self._data_post(path, data)+ return self._parse_search_result(resp_data)++ def search_by_random(+ self,+ index_name: str,+ limit: int = 10,+ offset: int = 0,+ filters: Optional[Dict[str, Any]] = None,+ output_fields: Optional[List[str]] = None,+ ) -> SearchResult:+ path = "/api/vikingdb/data/search/random"+ data = {+ "project": self.project_name,+ "collection_name": self.collection_name,+ "index_name": index_name,+ "filter": filters,+ "output_fields": output_fields,+ "limit": limit,+ "offset": offset,+ }+ resp_data = self._data_post(path, data)+ return self._parse_search_result(resp_data)++ def search_by_keywords(+ self,+ index_name: str,+ keywords: Optional[List[str]] = None,+ query: Optional[str] = None,+ limit: int = 10,+ offset: int = 0,+ filters: Optional[Dict[str, Any]] = None,+ output_fields: Optional[List[str]] = None,+ ) -> SearchResult:+ path = "/api/vikingdb/data/search/keywords"+ data = {+ "project": self.project_name,+ "collection_name": self.collection_name,+ "index_name": index_name,+ "keywords": keywords,+ "query": query,+ "filter": filters,+ "output_fields": output_fields,+ "limit": limit,+ "offset": offset,+ }+ resp_data = self._data_post(path, data)+ return self._parse_search_result(resp_data)++ def search_by_scalar(+ self,+ index_name: str,+ field: str,+ order: Optional[str] = "desc",+ limit: int = 10,+ offset: int = 0,+ filters: Optional[Dict[str, Any]] = None,+ output_fields: Optional[List[str]] = None,+ ) -> SearchResult:+ path = "/api/vikingdb/data/search/scalar"+ data = {+ "project": self.project_name,+ "collection_name": self.collection_name,+ "index_name": index_name,+ "field": field,+ "order": order,+ "filter": filters,+ "output_fields": output_fields,+ "limit": limit,+ "offset": offset,+ }+ resp_data = self._data_post(path, data)+ return self._parse_search_result(resp_data)++ def aggregate_data(+ self,+ index_name: str,+ op: str = "count",+ field: Optional[str] = None,+ filters: Optional[Dict[str, Any]] = None,+ cond: Optional[Dict[str, Any]] = None,+ ) -> AggregateResult:+ path = "/api/vikingdb/data/aggregate"+ data = {+ "project": self.project_name,+ "collection_name": self.collection_name,+ "index_name": index_name,+ "agg": {+ "op": op,+ "field": field,+ },+ "filter": filters,+ }+ resp_data = self._data_post(path, data)+ return self._parse_aggregate_result(resp_data, op, field)++ def _parse_aggregate_result(+ self, data: Dict[str, Any], op: str, field: Optional[str]+ ) -> AggregateResult:+ result = AggregateResult(op=op, field=field)+ if isinstance(data, dict):+ if "agg" in data:+ result.agg = data["agg"]+ else:+ result.agg = data+ return resultdiff --git a/openviking/storage/vectordb/project/vikingdb_project.py b/openviking/storage/vectordb/project/vikingdb_project.pynew file mode 100644index 000000000..bfb42d545--- /dev/null+++ b/openviking/storage/vectordb/project/vikingdb_project.py@@ -0,0 +1,162 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: Apache-2.0+from typing import Any, Dict, List, Optional++from openviking.storage.vectordb.collection.collection import Collection+from openviking.storage.vectordb.collection.vikingdb_clients import (+ VIKINGDB_APIS,+ VikingDBClient,+)+from openviking.storage.vectordb.collection.vikingdb_collection import VikingDBCollection+from openviking.utils.logger import default_logger as logger+++def get_or_create_vikingdb_project(+ project_name: str = "default", config: Optional[Dict[str, Any]] = None+):+ """+ Get or create a VikingDB project for private deployment.++ Args:+ project_name: Project name+ config: Configuration dict with keys:+ - Host: VikingDB service host+ - Headers: Custom headers for authentication/context++ Returns:+ VikingDBProject instance+ """+ if config is None:+ raise ValueError("config is required")++ host = config.get("Host")+ headers = config.get("Headers")++ if not host:+ raise ValueError("config must contain 'Host'")++ return VikingDBProject(host=host, headers=headers, project_name=project_name)+++class VikingDBProject:+ """+ VikingDB project class for private deployment.+ Manages multiple VikingDBCollection instances.+ """++ def __init__(+ self, host: str, headers: Optional[Dict[str, str]] = None, project_name: str = "default"+ ):+ """+ Initialize VikingDB project.++ Args:+ host: VikingDB service host+ headers: Custom headers for requests+ project_name: Project name+ """+ self.host = host+ self.headers = headers+ self.project_name = project_name++ logger.info(f"Initialized VikingDB project: {project_name} with host {host}")++ def close(self):+ """Close project"""+ pass++ def has_collection(self, collection_name: str) -> bool:+ """Check if collection exists by calling API"""+ client = VikingDBClient(self.host, self.headers)+ path, method = VIKINGDB_APIS["GetVikingdbCollection"]+ data = {"ProjectName": self.project_name, "CollectionName": collection_name}+ response = client.do_req(method, path=path, req_body=data)+ return response.status_code == 200++ def get_collection(self, collection_name: str) -> Optional[Collection]:+ """Get collection by name by calling API"""+ client = VikingDBClient(self.host, self.headers)+ path, method = VIKINGDB_APIS["GetVikingdbCollection"]+ data = {"ProjectName": self.project_name, "CollectionName": collection_name}+ response = client.do_req(method, path=path, req_body=data)+ if response.status_code != 200:+ return None++ try:+ result = response.json()+ meta_data = result.get("Result", {})+ if not meta_data:+ return None+ vikingdb_collection = VikingDBCollection(+ host=self.host, headers=self.headers, meta_data=meta_data+ )+ return Collection(vikingdb_collection)+ except Exception:+ return None++ def _get_collections(self) -> List[str]:+ """List all collection names from server"""+ client = VikingDBClient(self.host, self.headers)+ path, method = VIKINGDB_APIS["ListVikingdbCollection"]+ data = {"ProjectName": self.project_name}+ response = client.do_req(method, path=path, req_body=data)+ if response.status_code != 200:+ logger.error(f"List collections failed: {response.text}")+ return []+ try:+ result = response.json()+ colls = result.get("Result", {}).get("Collections", [])+ return colls+ except Exception:+ return []++ def list_collections(self) -> List[str]:+ """List all collection names from server"""+ colls = self._get_collections()+ return [coll.get("CollectionName") for coll in colls]++ def get_collections(self) -> Dict[str, Collection]:+ """Get all collections from server"""+ colls = self._get_collections()+ return {+ c["CollectionName"]: Collection(+ VikingDBCollection(host=self.host, headers=self.headers, meta_data=c)+ )+ for c in colls+ }++ def create_collection(self, collection_name: str, meta_data: Dict[str, Any]) -> Collection:+ """collection should be pre-created"""+ raise NotImplementedError("collection should be pre-created")++ def get_or_create_collection(+ self, collection_name: str, meta_data: Optional[Dict[str, Any]] = None+ ) -> Collection:+ """+ Get or create collection.++ Args:+ collection_name: Collection name+ meta_data: Collection metadata (required if not exists)++ Returns:+ Collection instance+ """+ collection = self.get_collection(collection_name)+ if collection:+ return collection++ if meta_data is None:+ raise ValueError(f"meta_data is required to create collection {collection_name}")++ return self.create_collection(collection_name, meta_data)++ def drop_collection(self, collection_name: str):+ """Drop specified collection"""+ collection = self.get_collection(collection_name)+ if not collection:+ logger.warning(f"Collection {collection_name} does not exist")+ return++ collection.drop()+ logger.info(f"Dropped VikingDB collection: {collection_name}")diff --git a/openviking/storage/viking_vector_index_backend.py b/openviking/storage/viking_vector_index_backend.pyindex 91c266c02..8f4aec680 100644--- a/openviking/storage/viking_vector_index_backend.py+++ b/openviking/storage/viking_vector_index_backend.py@@ -109,6 +109,24 @@ class VikingVectorIndexBackend(VikingDBInterface):logger.info(f"VectorDB backend initialized in Volcengine mode: region={volc_config['Region']}")+ elif config.backend == "vikingdb":+ if not config.vikingdb.host:+ raise ValueError("VikingDB backend requires a valid host")+ # VikingDB private deployment mode+ self._mode = config.backend+ viking_config = {+ "Host": config.vikingdb.host,+ "Headers": config.vikingdb.headers,+ }++ from openviking.storage.vectordb.project.vikingdb_project import (+ get_or_create_vikingdb_project,+ )++ self.project = get_or_create_vikingdb_project(+ project_name=self.DEFAULT_PROJECT_NAME, config=viking_config+ )+ logger.info(f"VikingDB backend initialized in private mode: {config.vikingdb.host}")elif config.backend == "http":if not config.url:raise ValueError("HTTP backend requires a valid URL")diff --git a/openviking/utils/config/open_viking_config.py b/openviking/utils/config/open_viking_config.pyindex 6d6c646d0..c851b5794 100644--- a/openviking/utils/config/open_viking_config.py+++ b/openviking/utils/config/open_viking_config.py@@ -292,7 +292,7 @@ def initialize_openviking_config(# Embedded mode: local storageconfig.storage.agfs.backend = config.storage.agfs.backend or "local"config.storage.agfs.path = path- config.storage.vectordb.backend = "local"+ config.storage.vectordb.backend = config.storage.vectordb.backend or "local"config.storage.vectordb.path = pathelif vectordb_url and agfs_url:# Service mode: remote servicesdiff --git a/openviking/utils/config/vectordb_config.py b/openviking/utils/config/vectordb_config.pyindex 9af43fdea..8786abcaa 100644--- a/openviking/utils/config/vectordb_config.py+++ b/openviking/utils/config/vectordb_config.py@@ -1,6 +1,6 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: Apache-2.0-from typing import Optional+from typing import Dict, Optionalfrom pydantic import BaseModel, Field, model_validator@@ -16,6 +16,15 @@ class VolcengineConfig(BaseModel):host: Optional[str] = Field(default=None, description="Volcengine VikingDB host (optional)")+class VikingDBConfig(BaseModel):+ """Configuration for VikingDB private deployment."""++ host: Optional[str] = Field(default=None, description="VikingDB service host")+ headers: Optional[Dict[str, str]] = Field(+ default_factory=dict, description="Custom headers for requests"+ )++class VectorDBBackendConfig(BaseModel):"""Configuration for VectorDB backend.@@ -61,12 +70,18 @@ class VectorDBBackendConfig(BaseModel):description="Volcengine VikingDB configuration for 'volcengine' type",)+ # VikingDB private deployment mode+ vikingdb: Optional[VikingDBConfig] = Field(+ default_factory=lambda: VikingDBConfig(),+ description="VikingDB private deployment configuration for 'vikingdb' type",+ )+@model_validator(mode="after")def validate_config(self):"""Validate configuration completeness and consistency"""- if self.backend not in ["local", "http", "volcengine"]:+ if self.backend not in ["local", "http", "volcengine", "vikingdb"]:raise ValueError(- f"Invalid VectorDB backend: '{self.backend}'. Must be one of: 'local', 'http', 'volcengine'"+ f"Invalid VectorDB backend: '{self.backend}'. Must be one of: 'local', 'http', 'volcengine', 'vikingdb'")if self.backend == "local":@@ -83,4 +98,8 @@ class VectorDBBackendConfig(BaseModel):if not self.volcengine.region:raise ValueError("VectorDB volcengine backend requires 'region' to be set")+ elif self.backend == "vikingdb":+ if not self.vikingdb or not self.vikingdb.host:+ raise ValueError("VectorDB vikingdb backend requires 'host' to be set")+return selfdiff --git a/tests/vectordb/test_vikingdb_project.py b/tests/vectordb/test_vikingdb_project.pynew file mode 100644index 000000000..14f5867a2--- /dev/null+++ b/tests/vectordb/test_vikingdb_project.py@@ -0,0 +1,96 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: Apache-2.0+import json+import sys+import unittest++from openviking.storage.vectordb.collection.collection import Collection+from openviking.storage.vectordb.collection.vikingdb_collection import VikingDBCollection+from openviking.storage.vectordb.project.vikingdb_project import get_or_create_vikingdb_project++[email protected](sys.platform == "darwin", "Only run on macOS")+class TestVikingDBProject(unittest.TestCase):+ """+ Unit tests for VikingDB Project and Collection implementation for private deployment.+ """++ def setUp(self):+ self.config = {+ "Host": "http://localhost:8080",+ "Headers": {+ "X-Top-Account-Id": "1",+ "X-Top-User-Id": "1000",+ "X-Top-IdentityName": "test-user",+ "X-Top-Role-Id": "data",+ },+ }+ self.project_name = "test_project"+ meta_data = {+ "Fields": [+ {"FieldName": "id", "FieldType": "string", "IsPrimaryKey": True},+ {"FieldName": "vector", "FieldType": "vector", "Dim": 128},+ {"FieldName": "text", "FieldType": "string"},+ ]+ }+ self.meta_data = meta_data++ def test_create_vikingdb_project(self):+ """Test project initialization."""+ project = get_or_create_vikingdb_project(self.project_name, self.config)+ self.assertEqual(project.project_name, self.project_name)+ self.assertEqual(project.host, self.config["Host"])+ self.assertEqual(project.headers, self.config["Headers"])++ def test_create_collection(self):+ """Test collection creation with custom headers."""+ project = get_or_create_vikingdb_project(self.project_name, self.config)+ meta_data = self.meta_data++ collection = project.create_collection("test_coll", meta_data)++ self.assertIsNotNone(collection)+ self.assertIn("test_coll", project.list_collections())++ def test_upsert_data(self):+ """Test data upsert with custom headers and path."""+ project = get_or_create_vikingdb_project(self.project_name, self.config)++ # Get existing or create new collection+ meta_data = self.meta_data+ collection = project.get_or_create_collection("test_coll", meta_data)++ data = [{"id": "1", "vector": [0.1] * 128, "text": "123"}]+ res = collection.upsert_data(data)+ self.assertIsNone(res)++ def test_fetch_data(self):+ """Test data fetching."""+ project = get_or_create_vikingdb_project(self.project_name, self.config)++ collection = project.get_or_create_collection("test_coll", self.meta_data)++ # Upsert some data first to fetch it+ data = [{"id": "1", "vector": [0.1] * 128, "text": "hello"}]+ collection.upsert_data(data)++ result = collection.fetch_data(["1"])++ self.assertEqual(len(result.items), 1)+ self.assertEqual(result.items[0].id, "1")+ self.assertEqual(result.items[0].fields["text"], "hello")++ def test_drop_collection(self):+ """Test collection dropping."""+ project = get_or_create_vikingdb_project(self.project_name, self.config)++ collection = project.get_or_create_collection("test_coll", self.meta_data)+ if not collection:+ assert False, "Collection should exist after creation"++ collection.drop()+ collection = project.get_collection("test_coll")+ self.assertIsNone(collection)++if __name__ == "__main__":+ unittest.main()