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(prompt) support configurable prompt template directories (#1096)
Jiahui Zhou026cd8e4ec30
diff --git a/openviking/prompts/manager.py b/openviking/prompts/manager.pyindex b8e155392..e7a6df223 100644--- a/openviking/prompts/manager.py+++ b/openviking/prompts/manager.py@@ -2,6 +2,7 @@# SPDX-License-Identifier: AGPL-3.0"""Prompt template management for OpenViking."""+import osimport threadingfrom pathlib import Pathfrom typing import Any, Dict, List, Optional@@ -10,6 +11,11 @@ import yamlfrom jinja2 import Templatefrom pydantic import BaseModel, Field+from openviking_cli.utils.config import (+ OPENVIKING_PROMPT_TEMPLATES_DIR_ENV,+ get_openviking_config,+)+class PromptMetadata(BaseModel):"""Metadata for a prompt template."""@@ -67,11 +73,32 @@ class PromptManager:If None, uses bundled templates.enable_caching: Enable prompt template caching"""- self.templates_dir = templates_dir or self._get_bundled_templates_dir()+ self.templates_dir = self._resolve_templates_dir(templates_dir)self.enable_caching = enable_cachingself._cache: Dict[str, PromptTemplate] = {}self._lock = threading.RLock()+ @classmethod+ def _resolve_templates_dir(cls, templates_dir: Optional[Path]) -> Path:+ """Resolve prompt templates directory with runtime overrides."""+ if templates_dir is not None:+ return Path(templates_dir)++ env_dir = os.environ.get(OPENVIKING_PROMPT_TEMPLATES_DIR_ENV)+ if env_dir:+ return Path(env_dir).expanduser()++ try:+ config = get_openviking_config()+ except FileNotFoundError:+ return cls._get_bundled_templates_dir()++ config_dir = config.prompts.templates_dir.strip()+ if config_dir:+ return Path(config_dir).expanduser()++ return cls._get_bundled_templates_dir()+@staticmethoddef _get_bundled_templates_dir() -> Path:"""Get path to bundled prompt templates."""@@ -120,7 +147,17 @@ class PromptManager:parts = prompt_id.split(".")category = parts[0]name = "_".join(parts[1:])- return self.templates_dir / category / f"{name}.yaml"+ relative_path = Path(category) / f"{name}.yaml"++ primary_path = self.templates_dir / relative_path+ if primary_path.exists():+ return primary_path++ bundled_path = self._get_bundled_templates_dir() / relative_path+ if bundled_path.exists():+ return bundled_path++ return primary_pathdef render(self,diff --git a/openviking_cli/utils/config/__init__.py b/openviking_cli/utils/config/__init__.pyindex a42796dca..349e2b307 100644--- a/openviking_cli/utils/config/__init__.py+++ b/openviking_cli/utils/config/__init__.py@@ -12,6 +12,7 @@ from .consts import (DEFAULT_OVCLI_CONF,OPENVIKING_CLI_CONFIG_ENV,OPENVIKING_CONFIG_ENV,+ OPENVIKING_PROMPT_TEMPLATES_DIR_ENV,SYSTEM_CONFIG_DIR,)from .embedding_config import EmbeddingConfig@@ -39,6 +40,7 @@ from .parser_config import (get_parser_config,load_parser_configs_from_dict,)+from .prompts_config import PromptsConfigfrom .rerank_config import RerankConfigfrom .storage_config import StorageConfigfrom .vectordb_config import VectorDBBackendConfig@@ -53,6 +55,7 @@ __all__ = ["LogConfig","OPENVIKING_CLI_CONFIG_ENV","OPENVIKING_CONFIG_ENV",+ "OPENVIKING_PROMPT_TEMPLATES_DIR_ENV","OpenVikingConfig","OpenVikingConfigSingleton","OVCLIConfig",@@ -72,6 +75,7 @@ __all__ = ["get_parser_config","load_parser_configs_from_dict","PARSER_CONFIG_REGISTRY",+ "PromptsConfig","get_openviking_config","initialize_openviking_config","load_json_config",diff --git a/openviking_cli/utils/config/consts.py b/openviking_cli/utils/config/consts.pyindex 4dfe1f95a..5584fdcd0 100644--- a/openviking_cli/utils/config/consts.py+++ b/openviking_cli/utils/config/consts.py@@ -9,6 +9,7 @@ SYSTEM_CONFIG_DIR = Path("/etc/openviking")OPENVIKING_CONFIG_ENV = "OPENVIKING_CONFIG_FILE"OPENVIKING_CLI_CONFIG_ENV = "OPENVIKING_CLI_CONFIG_FILE"+OPENVIKING_PROMPT_TEMPLATES_DIR_ENV = "OPENVIKING_PROMPT_TEMPLATES_DIR"DEFAULT_OV_CONF = "ov.conf"DEFAULT_OVCLI_CONF = "ovcli.conf"diff --git a/openviking_cli/utils/config/open_viking_config.py b/openviking_cli/utils/config/open_viking_config.pyindex f10c759d1..3fce2aa75 100644--- a/openviking_cli/utils/config/open_viking_config.py+++ b/openviking_cli/utils/config/open_viking_config.py@@ -35,6 +35,7 @@ from .parser_config import (TextConfig,VideoConfig,)+from .prompts_config import PromptsConfigfrom .rerank_config import RerankConfigfrom .storage_config import StorageConfigfrom .vlm_config import VLMConfig@@ -150,6 +151,11 @@ class OpenVikingConfig(BaseModel):default_factory=lambda: MemoryConfig(), description="Memory configuration")+ prompts: PromptsConfig = Field(+ default_factory=lambda: PromptsConfig(),+ description="Prompt template configuration",+ )+model_config = {"arbitrary_types_allowed": True, "extra": "forbid"}@classmethoddiff --git a/openviking_cli/utils/config/prompts_config.py b/openviking_cli/utils/config/prompts_config.pynew file mode 100644index 000000000..340c96529--- /dev/null+++ b/openviking_cli/utils/config/prompts_config.py@@ -0,0 +1,28 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+from typing import Any, Dict++from pydantic import BaseModel, Field+++class PromptsConfig(BaseModel):+ """Prompt template configuration for OpenViking."""++ templates_dir: str = Field(+ default="",+ description=(+ "Custom prompt templates directory. If set, PromptManager loads prompt "+ "templates from this directory instead of the bundled templates."+ ),+ )++ model_config = {"extra": "forbid"}++ @classmethod+ def from_dict(cls, config: Dict[str, Any]) -> "PromptsConfig":+ """Create configuration from dictionary."""+ return cls(**config)++ def to_dict(self) -> Dict[str, Any]:+ """Convert configuration to dictionary."""+ return self.model_dump()diff --git a/tests/test_prompt_manager.py b/tests/test_prompt_manager.pynew file mode 100644index 000000000..fca4f07b1--- /dev/null+++ b/tests/test_prompt_manager.py@@ -0,0 +1,126 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0++import json+from pathlib import Path++from openviking.prompts.manager import PromptManager+from openviking_cli.utils.config.open_viking_config import OpenVikingConfigSingleton++PROMPT_TEMPLATES_ENV = "OPENVIKING_PROMPT_TEMPLATES_DIR"+++def _write_template(templates_dir: Path, content: str) -> None:+ template_path = templates_dir / "memory" / "profile.yaml"+ template_path.parent.mkdir(parents=True, exist_ok=True)+ template_path.write_text(+ json.dumps(+ {+ "metadata": {+ "id": "memory.profile",+ "name": "Profile",+ "description": "Test template",+ "version": "1.0.0",+ "language": "en",+ "category": "memory",+ },+ "template": content,+ }+ ),+ encoding="utf-8",+ )+++def _write_config(config_path: Path, templates_dir: Path) -> None:+ config_path.write_text(+ json.dumps(+ {+ "storage": {+ "workspace": str(config_path.parent / "workspace"),+ "agfs": {"backend": "local", "mode": "binding-client"},+ "vectordb": {"backend": "local"},+ },+ "embedding": {+ "dense": {+ "provider": "openai",+ "model": "text-embedding-3-small",+ "api_key": "test-key",+ }+ },+ "prompts": {+ "templates_dir": str(templates_dir),+ },+ }+ ),+ encoding="utf-8",+ )+++def teardown_function() -> None:+ OpenVikingConfigSingleton.reset_instance()+++def test_prompt_manager_prefers_environment_templates_dir(tmp_path, monkeypatch):+ env_dir = tmp_path / "env-prompts"+ config_dir = tmp_path / "config-prompts"+ config_path = tmp_path / "ov.conf"++ _write_template(env_dir, "env-template")+ _write_template(config_dir, "config-template")+ _write_config(config_path, config_dir)++ OpenVikingConfigSingleton.reset_instance()+ monkeypatch.setenv("OPENVIKING_CONFIG_FILE", str(config_path))+ monkeypatch.setenv(PROMPT_TEMPLATES_ENV, str(env_dir))++ manager = PromptManager(enable_caching=False)++ assert manager.templates_dir == env_dir+ assert manager.render("memory.profile") == "env-template"+++def test_prompt_manager_uses_ov_conf_templates_dir_when_env_is_unset(tmp_path, monkeypatch):+ config_dir = tmp_path / "config-prompts"+ config_path = tmp_path / "ov.conf"++ _write_template(config_dir, "config-template")+ _write_config(config_path, config_dir)++ OpenVikingConfigSingleton.reset_instance()+ monkeypatch.setenv("OPENVIKING_CONFIG_FILE", str(config_path))+ monkeypatch.delenv(PROMPT_TEMPLATES_ENV, raising=False)++ manager = PromptManager(enable_caching=False)++ assert manager.templates_dir == config_dir+ assert manager.render("memory.profile") == "config-template"+++def test_prompt_manager_falls_back_to_bundled_templates_dir(monkeypatch):+ OpenVikingConfigSingleton.reset_instance()+ monkeypatch.delenv("OPENVIKING_CONFIG_FILE", raising=False)+ monkeypatch.delenv(PROMPT_TEMPLATES_ENV, raising=False)++ manager = PromptManager(enable_caching=False)++ assert manager.templates_dir == PromptManager._get_bundled_templates_dir()+++def test_prompt_manager_falls_back_to_bundled_template_when_custom_dir_is_partial(+ tmp_path, monkeypatch+):+ custom_dir = tmp_path / "custom-prompts"+ config_path = tmp_path / "ov.conf"++ _write_template(custom_dir, "custom-profile-template")+ _write_config(config_path, custom_dir)++ OpenVikingConfigSingleton.reset_instance()+ monkeypatch.setenv("OPENVIKING_CONFIG_FILE", str(config_path))+ monkeypatch.delenv(PROMPT_TEMPLATES_ENV, raising=False)++ manager = PromptManager(enable_caching=False)++ assert manager.render("memory.profile") == "custom-profile-template"+ bundled_template = manager.load_template("vision.image_understanding")+ assert bundled_template.metadata.id == "vision.image_understanding"