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: add `openviking-server init` interactive setup wizard for local Ollama model deployment (#1353)
t0saki4287e36195d3
diff --git a/openviking/server/bootstrap.py b/openviking/server/bootstrap.pyindex 1bd8c509e..3c8fc6b65 100644--- a/openviking/server/bootstrap.py+++ b/openviking/server/bootstrap.py@@ -131,6 +131,27 @@ def main():print(e, file=sys.stderr)sys.exit(1)+ # Ensure Ollama is running if configured+ try:+ from openviking_cli.utils.ollama import detect_ollama_in_config, ensure_ollama_for_server++ ov_config = OpenVikingConfigSingleton.get_instance()+ uses_ollama, ollama_host, ollama_port = detect_ollama_in_config(ov_config)+ if uses_ollama:+ result = ensure_ollama_for_server(ollama_host, ollama_port)+ if result.success:+ print(f"Ollama is running at {ollama_host}:{ollama_port}")+ else:+ print(+ f"Warning: Ollama not available at {ollama_host}:{ollama_port}. "+ f"Embedding/VLM may fail. ({result.message})",+ file=sys.stderr,+ )+ if result.stderr_output:+ print(f" Ollama stderr: {result.stderr_output}", file=sys.stderr)+ except Exception as e:+ print(f"Warning: Ollama pre-flight check failed: {e}", file=sys.stderr)+# Override with command line argumentsif args.host is not None:config.host = _normalize_host_arg(args.host)diff --git a/openviking/server/routers/system.py b/openviking/server/routers/system.pyindex ba5bd4666..3e571469b 100644--- a/openviking/server/routers/system.py+++ b/openviking/server/routers/system.py@@ -99,6 +99,23 @@ async def readiness_check(request: Request):except Exception as e:checks["api_key_manager"] = f"error: {e}"+ # 4. Ollama: connectivity check if configured+ try:+ from openviking_cli.utils.config.open_viking_config import OpenVikingConfigSingleton+ from openviking_cli.utils.ollama import check_ollama_running, detect_ollama_in_config++ ov_config = OpenVikingConfigSingleton.get_instance()+ uses_ollama, ollama_host, ollama_port = detect_ollama_in_config(ov_config)+ if uses_ollama:+ if check_ollama_running(ollama_host, ollama_port):+ checks["ollama"] = "ok"+ else:+ checks["ollama"] = f"unreachable at {ollama_host}:{ollama_port}"+ else:+ checks["ollama"] = "not_configured"+ except Exception as e:+ checks["ollama"] = f"error: {e}"+all_ok = all(v in ("ok", "not_configured") for v in checks.values())status_code = 200 if all_ok else 503return JSONResponse(diff --git a/openviking_cli/doctor.py b/openviking_cli/doctor.pyindex bcb231aaf..2d7f8dfbb 100644--- a/openviking_cli/doctor.py+++ b/openviking_cli/doctor.py@@ -1,8 +1,8 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""ov doctor - validate OpenViking subsystems and report actionable diagnostics.+"""openviking-server doctor - validate OpenViking subsystems and report actionable diagnostics.-Unlike ``ov health`` (which pings a running server), ``ov doctor`` checks+Unlike ``ov health`` (which pings a running server), ``openviking-server doctor`` checkslocal prerequisites without requiring a server: config file, Python version,native vector engine, AGFS, embedding provider, VLM provider, and disk space."""@@ -160,6 +160,10 @@ def check_embedding() -> tuple[bool, str, Optional[str]]:if provider == "unknown":return False, "No embedding provider configured", "Add embedding.dense section to ov.conf"+ # Ollama doesn't need an API key+ if provider == "ollama":+ return True, f"{provider}/{model}", None+api_key = dense.get("api_key", "")if not api_key or api_key.startswith("{"):return (@@ -188,6 +192,10 @@ def check_vlm() -> tuple[bool, str, Optional[str]]:if not provider:return False, "No VLM provider configured", "Add vlm section to ov.conf"+ # Ollama via LiteLLM doesn't need a real API key+ if provider == "litellm" and model.startswith("ollama/"):+ return True, f"{provider}/{model}", None+api_key = vlm.get("api_key", "")if not api_key or api_key.startswith("{"):return (@@ -199,6 +207,43 @@ def check_vlm() -> tuple[bool, str, Optional[str]]:return True, f"{provider}/{model}", None+def check_ollama() -> tuple[bool, str, Optional[str]]:+ """Check Ollama connectivity if the config uses an Ollama provider."""+ config_path = _find_config()+ if config_path is None:+ return True, "not configured", None++ data = _load_config_json(config_path)+ if data is None:+ return True, "not configured", None++ # Detect whether config uses Ollama+ dense = data.get("embedding", {}).get("dense", {})+ vlm = data.get("vlm", {})+ uses_embedding = dense.get("provider") == "ollama"+ uses_vlm = vlm.get("provider") == "litellm" and (vlm.get("model", "")).startswith("ollama/")++ if not uses_embedding and not uses_vlm:+ return True, "not configured", None++ from openviking_cli.utils.ollama import check_ollama_running, parse_ollama_url++ # Determine host/port from config+ if uses_embedding:+ host, port = parse_ollama_url(dense.get("api_base"))+ else:+ host, port = parse_ollama_url(vlm.get("api_base"))++ if check_ollama_running(host, port):+ return True, f"running at {host}:{port}", None++ return (+ False,+ f"unreachable at {host}:{port}",+ "Run 'ollama serve' or check your Ollama configuration",+ )++def check_disk() -> tuple[bool, str, Optional[str]]:"""Check free disk space in the workspace directory."""config_path = _find_config()@@ -237,6 +282,7 @@ _CHECKS = [("AGFS", check_agfs),("Embedding", check_embedding),("VLM", check_vlm),+ ("Ollama", check_ollama),("Disk", check_disk),]@@ -279,5 +325,5 @@ def run_doctor() -> int:def main() -> int:- """Entry point for ``ov doctor``."""+ """Entry point for ``openviking-server doctor``."""return run_doctor()diff --git a/openviking_cli/server_bootstrap.py b/openviking_cli/server_bootstrap.pyindex 2385145af..3fd3374f0 100644--- a/openviking_cli/server_bootstrap.py+++ b/openviking_cli/server_bootstrap.py@@ -9,6 +9,9 @@ and initialises the config singleton via module-level loggers).The real bootstrap logic stays in ``openviking.server.bootstrap``; we justpre-parse ``--config`` and set the environment variable before that moduleis ever imported.++Subcommands ``init`` and ``doctor`` are handled here directly (they don't+need a running server)."""import os@@ -16,6 +19,17 @@ import sysdef main():+ # Intercept subcommands that don't need the server.+ if len(sys.argv) > 1 and sys.argv[1] == "init":+ from openviking_cli.setup_wizard import main as init_main++ sys.exit(init_main())++ if len(sys.argv) > 1 and sys.argv[1] == "doctor":+ from openviking_cli.doctor import main as doctor_main++ sys.exit(doctor_main())+# Pre-parse --config from sys.argv before any openviking imports,# so the env var is visible when the config singleton first initialises.for i, arg in enumerate(sys.argv):diff --git a/openviking_cli/setup_wizard.py b/openviking_cli/setup_wizard.pynew file mode 100644index 000000000..e25281e10--- /dev/null+++ b/openviking_cli/setup_wizard.py@@ -0,0 +1,601 @@+"""openviking-server init - interactive setup wizard for OpenViking.++Guides users through model selection and configuration, with a focus on+local deployment via Ollama for macOS / Apple Silicon beginners.+"""++from __future__ import annotations++import json+import os+import subprocess+import sys+from dataclasses import dataclass+from pathlib import Path+from typing import Any++from openviking_cli.utils.config.consts import DEFAULT_CONFIG_DIR+from openviking_cli.utils.ollama import (+ check_ollama_running,+ get_ollama_models,+ install_ollama,+ is_model_available,+ is_ollama_installed,+ ollama_pull_model,+ start_ollama,+)++# ---------------------------------------------------------------------------+# ANSI helpers (same pattern as doctor.py)+# ---------------------------------------------------------------------------++_USE_COLOR = hasattr(sys.stdout, "isatty") and sys.stdout.isatty()+++def _green(t: str) -> str:+ return f"\033[32m{t}\033[0m" if _USE_COLOR else t+++def _red(t: str) -> str:+ return f"\033[31m{t}\033[0m" if _USE_COLOR else t+++def _yellow(t: str) -> str:+ return f"\033[33m{t}\033[0m" if _USE_COLOR else t+++def _dim(t: str) -> str:+ return f"\033[2m{t}\033[0m" if _USE_COLOR else t+++def _bold(t: str) -> str:+ return f"\033[1m{t}\033[0m" if _USE_COLOR else t+++def _cyan(t: str) -> str:+ return f"\033[36m{t}\033[0m" if _USE_COLOR else t+++# ---------------------------------------------------------------------------+# Interactive prompt helpers (stdlib only)+# ---------------------------------------------------------------------------+++def _prompt_choice(prompt: str, options: list[tuple[str, str]], default: int = 1) -> int:+ """Display numbered options and return 1-based selection index."""+ print(f"\n {_bold(prompt)}\n")+ for i, (label, desc) in enumerate(options, 1):+ marker = " "+ line = f" {marker}[{i}] {label}"+ if desc:+ line += f" {_dim(desc)}"+ print(line)++ while True:+ try:+ raw = input(f"\n Select [{default}]: ").strip()+ except EOFError:+ return default+ if not raw:+ return default+ try:+ choice = int(raw)+ if 1 <= choice <= len(options):+ return choice+ except ValueError:+ pass+ print(f" {_red('Please enter a number between 1 and ' + str(len(options)))}")+++def _prompt_input(prompt: str, default: str = "") -> str:+ """Prompt for free-text input with optional default."""+ suffix = f" [{default}]" if default else ""+ try:+ raw = input(f" {prompt}{suffix}: ").strip()+ except EOFError:+ return default+ return raw or default+++def _prompt_confirm(prompt: str, default: bool = True) -> bool:+ """Yes/no confirmation prompt."""+ hint = "Y/n" if default else "y/N"+ try:+ raw = input(f" {prompt} [{hint}]: ").strip().lower()+ except EOFError:+ return default+ if not raw:+ return default+ return raw in ("y", "yes")+++# ---------------------------------------------------------------------------+# System info+# ---------------------------------------------------------------------------+++def _get_system_ram_gb() -> int:+ """Get total system RAM in GB."""+ try:+ pages = os.sysconf("SC_PHYS_PAGES")+ page_size = os.sysconf("SC_PAGE_SIZE")+ return (pages * page_size) // (1024**3)+ except (ValueError, OSError, AttributeError):+ pass+ # Windows fallback+ try:+ import ctypes++ kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]++ class MEMORYSTATUSEX(ctypes.Structure):+ _fields_ = [+ ("dwLength", ctypes.c_ulong),+ ("dwMemoryLoad", ctypes.c_ulong),+ ("ullTotalPhys", ctypes.c_ulonglong),+ ("ullAvailPhys", ctypes.c_ulonglong),+ ("ullTotalPageFile", ctypes.c_ulonglong),+ ("ullAvailPageFile", ctypes.c_ulonglong),+ ("ullTotalVirtual", ctypes.c_ulonglong),+ ("ullAvailVirtual", ctypes.c_ulonglong),+ ("ullAvailExtendedVirtual", ctypes.c_ulonglong),+ ]++ stat = MEMORYSTATUSEX()+ stat.dwLength = ctypes.sizeof(stat)+ kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))+ return stat.ullTotalPhys // (1024**3)+ except Exception:+ return 0+++# ---------------------------------------------------------------------------+# Ollama interaction (delegates to openviking_cli.utils.ollama)+# ---------------------------------------------------------------------------+++def _ensure_ollama() -> bool:+ """Make sure Ollama is installed and running (interactive). Returns True if ready."""+ print("\n Checking Ollama...", end=" ", flush=True)++ if is_ollama_installed():+ if check_ollama_running():+ print(_green("running at localhost:11434"))+ return True+ print(_yellow("installed but not running"))+ print(f" {_dim('Starting Ollama...')}", end=" ", flush=True)+ result = start_ollama()+ if result.success:+ print(_green("ready"))+ else:+ msg = result.stderr_output or result.message+ print(_yellow(f"failed ({msg})"))+ return result.success++ # Not installed+ print(_yellow("not installed"))+ if not _prompt_confirm("Install Ollama now?"):+ print(f"\n {_dim('Manual install: https://ollama.com/download')}")+ return False++ print()+ if not install_ollama():+ print(f" {_red('Installation failed.')}")+ print(f" {_dim('Try manually: https://ollama.com/download')}")+ return False++ print(f" {_green('OK')} Ollama installed")+ print(f" {_dim('Starting Ollama...')}", end=" ", flush=True)+ result = start_ollama()+ if result.success:+ print(_green("ready"))+ else:+ msg = result.stderr_output or result.message+ print(_yellow(f"failed ({msg})"))+ return result.success+++# ---------------------------------------------------------------------------+# Model presets+# ---------------------------------------------------------------------------+++@dataclass+class EmbeddingPreset:+ label: str+ model: str # Ollama model name+ dimension: int+ size_hint: str+ min_ram_gb: int # Minimum recommended RAM+++@dataclass+class VLMPreset:+ label: str+ ollama_model: str # For ollama pull+ litellm_model: str # For config: "ollama/xxx"+ size_hint: str+ min_ram_gb: int # Minimum recommended RAM+++EMBEDDING_PRESETS: list[EmbeddingPreset] = [+ EmbeddingPreset("Qwen3-Embedding 0.6B", "qwen3-embedding:0.6b", 1024, "~639 MB", 4),+ EmbeddingPreset("Qwen3-Embedding 4B", "qwen3-embedding:4b", 1024, "~2.5 GB", 8),+ EmbeddingPreset("Qwen3-Embedding 8B", "qwen3-embedding:8b", 1024, "~4.7 GB", 16),+ EmbeddingPreset("EmbeddingGemma 300M", "embeddinggemma:300m", 768, "~622 MB", 4),+]++VLM_PRESETS: list[VLMPreset] = [+ VLMPreset("Qwen 3.5 2B", "qwen3.5:2b", "ollama/qwen3.5:2b", "~2.7 GB", 4),+ VLMPreset("Qwen 3.5 4B", "qwen3.5:4b", "ollama/qwen3.5:4b", "~3.4 GB", 8),+ VLMPreset("Qwen 3.5 9B", "qwen3.5:9b", "ollama/qwen3.5:9b", "~6.6 GB", 16),+ VLMPreset("Qwen 3.5 27B", "qwen3.5:27b", "ollama/qwen3.5:27b", "~17 GB", 32),+ VLMPreset("Qwen 3.5 35B", "qwen3.5:35b", "ollama/qwen3.5:35b", "~24 GB", 48),+ VLMPreset("Qwen 3.5 122B", "qwen3.5:122b", "ollama/qwen3.5:122b", "~81 GB", 128),+ VLMPreset("Gemma 4 E2B", "gemma4:e2b", "ollama/gemma4:e2b", "~7.2 GB", 16),+ VLMPreset("Gemma 4 E4B", "gemma4:e4b", "ollama/gemma4:e4b", "~9.6 GB", 16),+ VLMPreset("Gemma 4 26B", "gemma4:26b", "ollama/gemma4:26b", "~18 GB", 32),+ VLMPreset("Gemma 4 31B", "gemma4:31b", "ollama/gemma4:31b", "~20 GB", 48),+]++# Recommended defaults indexed by RAM tier+_RAM_TIERS: list[tuple[int, int, int]] = [+ # (max_ram_gb, embedding_preset_index, vlm_preset_index)+ (8, 0, 0), # ≤8 GB: qwen3-embedding:0.6b + qwen3.5:2b+ (16, 0, 1), # 8-16 GB: qwen3-embedding:0.6b + qwen3.5:4b+ (32, 2, 2), # 16-32 GB: qwen3-embedding:8b + qwen3.5:9b+ (64, 2, 7), # 32-64 GB: qwen3-embedding:8b + gemma4:e4b+]+_RAM_DEFAULT_EMBED = 2 # ≥64 GB: qwen3-embedding:8b+_RAM_DEFAULT_VLM = 3 # ≥64 GB: qwen3.5:27b+++def _get_recommended_indices(ram_gb: int) -> tuple[int, int]:+ """Return (embedding_index, vlm_index) for the RAM tier (0-based)."""+ for max_ram, emb_idx, vlm_idx in _RAM_TIERS:+ if ram_gb <= max_ram:+ return emb_idx, vlm_idx+ return _RAM_DEFAULT_EMBED, _RAM_DEFAULT_VLM+++# ---------------------------------------------------------------------------+# Cloud provider presets+# ---------------------------------------------------------------------------+++@dataclass+class CloudProvider:+ label: str+ provider: str+ default_api_base: str+ default_embedding_model: str+ default_embedding_dim: int+ default_vlm_model: str+++CLOUD_PROVIDERS: list[CloudProvider] = [+ CloudProvider(+ "OpenAI", "openai", "https://api.openai.com/v1",+ "text-embedding-3-small", 1536, "gpt-4o-mini",+ ),+ CloudProvider(+ "Volcengine (Doubao)", "volcengine", "https://ark.cn-beijing.volces.com/api/v3",+ "doubao-embedding-vision-250615", 1024, "doubao-seed-2-0-pro-260215",+ ),+]+++# ---------------------------------------------------------------------------+# Config building+# ---------------------------------------------------------------------------+++def _build_ollama_config(+ embedding: EmbeddingPreset,+ vlm: VLMPreset,+ workspace: str,+) -> dict[str, Any]:+ """Build ov.conf dict for Ollama-based setup."""+ return {+ "storage": {"workspace": workspace},+ "embedding": {+ "dense": {+ "provider": "ollama",+ "model": embedding.model,+ "api_base": "http://localhost:11434/v1",+ "dimension": embedding.dimension,+ "input": "text",+ },+ },+ "vlm": {+ "provider": "litellm",+ "model": vlm.litellm_model,+ "api_key": "no-key",+ "api_base": "http://localhost:11434",+ "temperature": 0.0,+ "max_retries": 2,+ },+ }+++def _build_cloud_config(+ provider: CloudProvider,+ embedding_api_key: str,+ embedding_model: str,+ embedding_dim: int,+ vlm_api_key: str,+ vlm_model: str,+ workspace: str,+ embedding_api_base: str | None = None,+ vlm_api_base: str | None = None,+) -> dict[str, Any]:+ """Build ov.conf dict for cloud API setup."""+ return {+ "storage": {"workspace": workspace},+ "embedding": {+ "dense": {+ "provider": provider.provider,+ "model": embedding_model,+ "api_key": embedding_api_key,+ "api_base": embedding_api_base or provider.default_api_base,+ "dimension": embedding_dim,+ },+ },+ "vlm": {+ "provider": provider.provider,+ "model": vlm_model,+ "api_key": vlm_api_key,+ "api_base": vlm_api_base or provider.default_api_base,+ "temperature": 0.0,+ "max_retries": 2,+ },+ }+++# ---------------------------------------------------------------------------+# Config I/O+# ---------------------------------------------------------------------------++_DEFAULT_CONFIG_PATH = DEFAULT_CONFIG_DIR / "ov.conf"+_DEFAULT_WORKSPACE = str(DEFAULT_CONFIG_DIR / "data")+++def _write_config(config_dict: dict[str, Any], config_path: Path) -> bool:+ """Write config dict as JSON. Backs up existing file as .bak."""+ try:+ config_path.parent.mkdir(parents=True, exist_ok=True)+ if config_path.exists():+ backup = config_path.with_suffix(".conf.bak")+ config_path.rename(backup)+ print(f" {_dim('Existing config backed up to ' + str(backup))}")+ config_path.write_text(json.dumps(config_dict, indent=2, ensure_ascii=False) + "\n",+ encoding="utf-8")+ return True+ except OSError as exc:+ print(f" {_red(f'Failed to write config: {exc}')}")+ return False+++# ---------------------------------------------------------------------------+# Wizard flows+# ---------------------------------------------------------------------------+++def _wizard_ollama() -> dict[str, Any] | None:+ """Ollama-based local model setup flow."""+ # Ensure Ollama is installed and running+ ollama_running = _ensure_ollama()++ if not ollama_running:+ if not _prompt_confirm(+ "Continue without Ollama? (config will be generated but models won't be pulled)",+ default=False,+ ):+ return None++ available_models = get_ollama_models() if ollama_running else []++ # System RAM+ ram_gb = _get_system_ram_gb()+ rec_embed_idx, rec_vlm_idx = _get_recommended_indices(ram_gb)+ if ram_gb > 0:+ print(f"\n {_dim(f'Detected {ram_gb} GB RAM')}")++ # --- Embedding selection ---+ embed_options: list[tuple[str, str]] = []+ for i, p in enumerate(EMBEDDING_PRESETS):+ rec = " *" if i == rec_embed_idx else ""+ avail = ""+ if ollama_running and is_model_available(p.model, available_models):+ avail = _green(" [downloaded]")+ embed_options.append((+ f"{p.label}",+ f"({p.dimension}d, {p.size_hint}){avail}{rec}",+ ))++ embed_choice = _prompt_choice("Embedding model:", embed_options, default=rec_embed_idx + 1)+ embedding = EMBEDDING_PRESETS[embed_choice - 1]++ # Pull embedding model+ if ollama_running and not is_model_available(embedding.model, available_models):+ if _prompt_confirm(f"'{embedding.model}' not found locally. Pull now?"):+ print()+ if not ollama_pull_model(embedding.model):+ print(f" {_yellow('Pull failed. You can pull it later: ollama pull ' + embedding.model)}")+ else:+ print(f" {_green('OK')} {embedding.model} pulled successfully")++ # --- VLM selection ---+ vlm_options: list[tuple[str, str]] = []+ for i, p in enumerate(VLM_PRESETS):+ rec = " *" if i == rec_vlm_idx else ""+ avail = ""+ if ollama_running and is_model_available(p.ollama_model, available_models):+ avail = _green(" [downloaded]")+ vlm_options.append((+ f"{p.label}",+ f"({p.size_hint}){avail}{rec}",+ ))++ vlm_choice = _prompt_choice("Language model (VLM):", vlm_options, default=rec_vlm_idx + 1)+ vlm = VLM_PRESETS[vlm_choice - 1]++ # Pull VLM model+ if ollama_running and not is_model_available(vlm.ollama_model, available_models):+ if _prompt_confirm(f"'{vlm.ollama_model}' not found locally. Pull now?"):+ print()+ if not ollama_pull_model(vlm.ollama_model):+ print(f" {_yellow('Pull failed. You can pull it later: ollama pull ' + vlm.ollama_model)}")+ else:+ print(f" {_green('OK')} {vlm.ollama_model} pulled successfully")++ # Workspace+ workspace = _prompt_input("Workspace", default=_DEFAULT_WORKSPACE)++ return _build_ollama_config(embedding, vlm, workspace)+++def _wizard_cloud() -> dict[str, Any] | None:+ """Cloud API model setup flow."""+ # Provider selection+ provider_options = [(p.label, "") for p in CLOUD_PROVIDERS]+ provider_options.append(("Other (manual)", ""))+ choice = _prompt_choice("Cloud provider:", provider_options, default=1)++ if choice > len(CLOUD_PROVIDERS):+ # Manual / Other+ print(f"\n See example config: {_cyan('examples/ov.conf.example')}")+ print(f" Edit {_cyan(str(_DEFAULT_CONFIG_PATH))} manually.\n")+ return None++ provider = CLOUD_PROVIDERS[choice - 1]++ # Embedding config+ print(f"\n {_bold('Embedding configuration')}")+ embedding_api_key = _prompt_input("API Key")+ if not embedding_api_key:+ print(f" {_red('API key is required')}")+ return None+ embedding_model = _prompt_input("Model", default=provider.default_embedding_model)+ embedding_dim_str = _prompt_input("Dimension", default=str(provider.default_embedding_dim))+ try:+ embedding_dim = int(embedding_dim_str)+ except ValueError:+ embedding_dim = provider.default_embedding_dim+ embedding_api_base = _prompt_input("API Base", default=provider.default_api_base)++ # VLM config+ print(f"\n {_bold('VLM configuration')}")+ vlm_api_key = _prompt_input("API Key (same as above?)", default=embedding_api_key)+ vlm_model = _prompt_input("Model", default=provider.default_vlm_model)+ vlm_api_base = _prompt_input("API Base", default=provider.default_api_base)++ # Workspace+ workspace = _prompt_input("Workspace", default=_DEFAULT_WORKSPACE)++ return _build_cloud_config(+ provider, embedding_api_key, embedding_model, embedding_dim,+ vlm_api_key, vlm_model, workspace,+ embedding_api_base, vlm_api_base,+ )+++def _wizard_custom() -> dict[str, Any] | None:+ """Custom configuration - point user to example config."""+ example = Path(__file__).parent.parent / "examples" / "ov.conf.example"+ if example.exists():+ print(f"\n Example config: {_cyan(str(example))}")+ print(f" Config path: {_cyan(str(_DEFAULT_CONFIG_PATH))}")++ editor = os.environ.get("EDITOR", os.environ.get("VISUAL", ""))+ if editor:+ if _prompt_confirm(f"Open {_DEFAULT_CONFIG_PATH} in {editor}?"):+ _DEFAULT_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)+ if not _DEFAULT_CONFIG_PATH.exists():+ # Copy example as starting point+ try:+ _DEFAULT_CONFIG_PATH.write_text(example.read_text(encoding="utf-8"),+ encoding="utf-8")+ except OSError:+ pass+ subprocess.run([editor, str(_DEFAULT_CONFIG_PATH)], check=False)+ else:+ print(f"\n {_dim('Set $EDITOR to open the config file automatically.')}")+ return None+++# ---------------------------------------------------------------------------+# Main orchestrator+# ---------------------------------------------------------------------------+++def run_init() -> int:+ """Run the interactive setup wizard."""+ print(f"\n {_bold('OpenViking Setup')}")+ print(f" {'=' * 16}\n")++ # Check for existing config+ if _DEFAULT_CONFIG_PATH.exists():+ print(f" {_yellow('Existing config found:')} {_DEFAULT_CONFIG_PATH}")+ if not _prompt_confirm("Overwrite? (current config will be backed up as .bak)"):+ print(" Setup cancelled.\n")+ return 0++ # Deployment mode+ mode = _prompt_choice("Choose setup mode:", [+ ("Local models via Ollama", "(recommended for macOS / Apple Silicon)"),+ ("Cloud API", "(OpenAI, Volcengine, etc.)"),+ ("Custom", "(manual editing)"),+ ], default=1)++ config_dict: dict[str, Any] | None = None++ if mode == 1:+ config_dict = _wizard_ollama()+ elif mode == 2:+ config_dict = _wizard_cloud()+ else:+ _wizard_custom()+ return 0++ if config_dict is None:+ print("\n Setup cancelled.\n")+ return 0++ # Summary+ emb = config_dict.get("embedding", {}).get("dense", {})+ vlm = config_dict.get("vlm", {})+ ws = config_dict.get("storage", {}).get("workspace", _DEFAULT_WORKSPACE)++ print(f"\n {_bold('Summary:')}")+ print(f" Embedding: {emb.get('provider', '')} / {emb.get('model', '')} ({emb.get('dimension', '')}d)")+ print(f" VLM: {vlm.get('provider', '')} / {vlm.get('model', '')}")+ print(f" Workspace: {ws}")+ print(f" Config: {_DEFAULT_CONFIG_PATH}")++ if not _prompt_confirm("\n Save configuration?"):+ print("\n Setup cancelled.\n")+ return 0++ # Write+ if not _write_config(config_dict, _DEFAULT_CONFIG_PATH):+ return 1++ print(f" {_green('OK')} Configuration written to {_DEFAULT_CONFIG_PATH}\n")++ # Post-init tips+ print(f" {_bold('Next steps:')}")+ print(f" Start the server: {_cyan('openviking-server')}")+ print(f" Validate setup: {_cyan('openviking-server doctor')}")+ print()++ return 0+++def main() -> int:+ """Entry point for ``openviking-server init``."""+ try:+ return run_init()+ except KeyboardInterrupt:+ print("\n\n Setup cancelled.\n")+ return 130diff --git a/openviking_cli/utils/config/embedding_config.py b/openviking_cli/utils/config/embedding_config.pyindex 14e472464..35c5971a8 100644--- a/openviking_cli/utils/config/embedding_config.py+++ b/openviking_cli/utils/config/embedding_config.py@@ -232,6 +232,12 @@ class EmbeddingModelConfig(BaseModel):"all-minilm-l6-v2": 384,"snowflake-arctic-embed": 1024,"snowflake-arctic-embed-l": 1024,+ "qwen3-embedding": 1024,+ "qwen3-embedding:0.6b": 1024,+ "qwen3-embedding:4b": 1024,+ "qwen3-embedding:8b": 1024,+ "embeddinggemma": 768,+ "embeddinggemma:300m": 768,}model_lower = (self.model or "").lower()if model_lower in ollama_model_dimensions:diff --git a/openviking_cli/utils/ollama.py b/openviking_cli/utils/ollama.pynew file mode 100644index 000000000..11655e1ea--- /dev/null+++ b/openviking_cli/utils/ollama.py@@ -0,0 +1,290 @@+"""Shared Ollama utilities for OpenViking.++Used by both the ``openviking-server init`` setup wizard and the ``openviking-server``+bootstrap to detect, start, and health-check a local Ollama instance.++Design principle: **ensure running, never stop** — Ollama is a shared+service that other tools may depend on. We start it if needed but never+tear it down on exit.++stdlib-only (no third-party dependencies).+"""++from __future__ import annotations++import json+import platform+import shutil+import subprocess+import tempfile+import time+import urllib.error+import urllib.parse+import urllib.request+from dataclasses import dataclass++# ---------------------------------------------------------------------------+# Constants+# ---------------------------------------------------------------------------++OLLAMA_DEFAULT_HOST = "localhost"+OLLAMA_DEFAULT_PORT = 11434++_LOCAL_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})++# ---------------------------------------------------------------------------+# Data types+# ---------------------------------------------------------------------------+++@dataclass+class OllamaStartResult:+ """Result of attempting to start / ensure Ollama is available."""++ success: bool+ stderr_output: str = ""+ message: str = ""+++# ---------------------------------------------------------------------------+# URL parsing+# ---------------------------------------------------------------------------+++def parse_ollama_url(api_base: str | None) -> tuple[str, int]:+ """Extract ``(host, port)`` from an Ollama *api_base* URL.++ Handles forms like ``http://localhost:11434/v1`` or+ ``http://gpu-server:11434``. Falls back to defaults when *api_base*+ is ``None`` or unparseable.+ """+ if not api_base:+ return OLLAMA_DEFAULT_HOST, OLLAMA_DEFAULT_PORT+ try:+ parsed = urllib.parse.urlparse(api_base)+ host = parsed.hostname or OLLAMA_DEFAULT_HOST+ port = parsed.port or OLLAMA_DEFAULT_PORT+ return host, port+ except Exception:+ return OLLAMA_DEFAULT_HOST, OLLAMA_DEFAULT_PORT+++# ---------------------------------------------------------------------------+# Ollama detection / health+# ---------------------------------------------------------------------------+++def check_ollama_running(+ host: str = OLLAMA_DEFAULT_HOST,+ port: int = OLLAMA_DEFAULT_PORT,+) -> bool:+ """Return ``True`` if Ollama is responding at *host*:*port*."""+ try:+ url = f"http://{host}:{port}/api/tags"+ req = urllib.request.Request(url, method="GET")+ with urllib.request.urlopen(req, timeout=3):+ return True+ except (urllib.error.URLError, OSError, TimeoutError):+ return False+++def get_ollama_models(+ host: str = OLLAMA_DEFAULT_HOST,+ port: int = OLLAMA_DEFAULT_PORT,+) -> list[str]:+ """Fetch names of locally available Ollama models."""+ try:+ url = f"http://{host}:{port}/api/tags"+ req = urllib.request.Request(url, method="GET")+ with urllib.request.urlopen(req, timeout=5) as resp:+ data = json.loads(resp.read().decode())+ return [m["name"] for m in data.get("models", [])]+ except (urllib.error.URLError, OSError, TimeoutError, json.JSONDecodeError, KeyError):+ return []+++def is_model_available(model_name: str, available: list[str]) -> bool:+ """Check if *model_name* is available locally (prefix match for tag variants)."""+ for m in available:+ if m == model_name or m.startswith(model_name + "-"):+ return True+ # model_name without tag matches model with ":latest"+ if ":" not in model_name and m.split(":")[0] == model_name:+ return True+ return False+++# ---------------------------------------------------------------------------+# Ollama installation & startup+# ---------------------------------------------------------------------------+++def ollama_pull_model(model_name: str) -> bool:+ """Pull an Ollama model via CLI (shows native progress bar)."""+ try:+ result = subprocess.run(["ollama", "pull", model_name], check=False)+ return result.returncode == 0+ except FileNotFoundError:+ return False+++def is_ollama_installed() -> bool:+ """Check if the ``ollama`` CLI binary is on PATH."""+ return shutil.which("ollama") is not None+++def install_ollama() -> bool:+ """Install Ollama automatically based on the current platform."""+ system = platform.system()++ if system == "Darwin":+ if shutil.which("brew"):+ result = subprocess.run(["brew", "install", "ollama"], check=False)+ if result.returncode == 0:+ return True+ result = subprocess.run(+ ["bash", "-c", "curl -fsSL https://ollama.com/install.sh | sh"],+ check=False,+ )+ return result.returncode == 0++ elif system == "Linux":+ result = subprocess.run(+ ["bash", "-c", "curl -fsSL https://ollama.com/install.sh | sh"],+ check=False,+ )+ return result.returncode == 0++ return False+++def start_ollama(+ host: str = OLLAMA_DEFAULT_HOST,+ port: int = OLLAMA_DEFAULT_PORT,+) -> OllamaStartResult:+ """Start ``ollama serve`` in the background and wait for it to be ready.++ Unlike the old fire-and-forget approach, stderr is captured so that+ failure reasons are visible to the caller.++ Returns an :class:`OllamaStartResult` with ``success`` and any+ ``stderr_output`` on failure.+ """+ # Already running?+ if check_ollama_running(host, port):+ return OllamaStartResult(success=True, message="already running")++ stderr_file = tempfile.TemporaryFile(mode="w+")+ try:+ subprocess.Popen(+ ["ollama", "serve"],+ stdout=subprocess.DEVNULL,+ stderr=stderr_file,+ )+ except FileNotFoundError:+ stderr_file.close()+ return OllamaStartResult(+ success=False,+ message="ollama command not found",+ )++ # Poll up to 15 seconds for readiness+ for _ in range(30):+ time.sleep(0.5)+ if check_ollama_running(host, port):+ stderr_file.close()+ return OllamaStartResult(success=True, message="started")++ # Timeout — read stderr for diagnostics+ stderr_output = ""+ try:+ stderr_file.seek(0)+ stderr_output = stderr_file.read()+ except Exception:+ pass+ finally:+ stderr_file.close()++ return OllamaStartResult(+ success=False,+ stderr_output=stderr_output,+ message="timeout waiting for Ollama to become ready",+ )+++# ---------------------------------------------------------------------------+# Config detection+# ---------------------------------------------------------------------------+++def detect_ollama_in_config(config) -> tuple[bool, str, int]:+ """Detect whether *config* uses Ollama and return ``(uses_ollama, host, port)``.++ *config* is an :class:`OpenVikingConfig` instance (imported lazily to+ avoid circular deps).++ Detection rules:+ - ``embedding.dense.provider == "ollama"``+ - ``vlm.provider == "litellm"`` **and** ``vlm.model`` starts with ``"ollama/"``+ """+ host, port = OLLAMA_DEFAULT_HOST, OLLAMA_DEFAULT_PORT+ uses_ollama = False++ # Check embedding+ dense = getattr(config.embedding, "dense", None)+ if dense is not None and getattr(dense, "provider", None) == "ollama":+ uses_ollama = True+ api_base = getattr(dense, "api_base", None)+ host, port = parse_ollama_url(api_base)++ # Check VLM+ vlm = getattr(config, "vlm", None)+ if vlm is not None:+ vlm_provider = getattr(vlm, "provider", None)+ vlm_model = getattr(vlm, "model", None) or ""+ if vlm_provider == "litellm" and vlm_model.startswith("ollama/"):+ if not uses_ollama:+ # Only use VLM's URL if embedding didn't already set it+ api_base = getattr(vlm, "api_base", None)+ host, port = parse_ollama_url(api_base)+ uses_ollama = True++ return uses_ollama, host, port+++# ---------------------------------------------------------------------------+# Server-oriented ensure (non-interactive)+# ---------------------------------------------------------------------------+++def ensure_ollama_for_server(+ host: str = OLLAMA_DEFAULT_HOST,+ port: int = OLLAMA_DEFAULT_PORT,+) -> OllamaStartResult:+ """Ensure Ollama is available — non-interactive, for server startup.++ - Already running → success.+ - Remote host (not localhost) → only probe, never attempt local start.+ - Not installed → warn, return failure (no interactive install).+ - Installed but not running → ``ollama serve`` with stderr capture.+ """+ # 1. Already running?+ if check_ollama_running(host, port):+ return OllamaStartResult(success=True, message=f"running at {host}:{port}")++ # 2. Remote host — can't start locally+ if host not in _LOCAL_HOSTS:+ return OllamaStartResult(+ success=False,+ message=f"Ollama at {host}:{port} is not reachable. Cannot auto-start remote Ollama.",+ )++ # 3. Not installed?+ if not is_ollama_installed():+ return OllamaStartResult(+ success=False,+ message="ollama is not installed. Install from https://ollama.com/download",+ )++ # 4. Installed but not running — start it+ return start_ollama(host, port)diff --git a/tests/cli/test_doctor.py b/tests/cli/test_doctor.pyindex 428975053..e0a60a2f5 100644--- a/tests/cli/test_doctor.py+++ b/tests/cli/test_doctor.py@@ -1,6 +1,6 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""Tests for ``ov doctor`` diagnostic checks."""+"""Tests for ``openviking-server doctor`` diagnostic checks."""from __future__ import annotationsdiff --git a/tests/cli/test_setup_wizard.py b/tests/cli/test_setup_wizard.pynew file mode 100644index 000000000..2a690639c--- /dev/null+++ b/tests/cli/test_setup_wizard.py@@ -0,0 +1,207 @@+"""Tests for the openviking-server init setup wizard."""++from __future__ import annotations++import json+from unittest.mock import MagicMock, patch++from openviking_cli.setup_wizard import (+ CLOUD_PROVIDERS,+ EMBEDDING_PRESETS,+ VLM_PRESETS,+ _build_cloud_config,+ _build_ollama_config,+ _get_recommended_indices,+ _write_config,+)+from openviking_cli.utils.ollama import (+ check_ollama_running,+ get_ollama_models,+ is_model_available,+)++# ---------------------------------------------------------------------------+# Ollama detection+# ---------------------------------------------------------------------------+++class TestOllamaDetection:+ def test_ollama_running(self):+ mock_resp = MagicMock()+ mock_resp.__enter__ = MagicMock(return_value=mock_resp)+ mock_resp.__exit__ = MagicMock(return_value=False)++ with patch("openviking_cli.utils.ollama.urllib.request.urlopen", return_value=mock_resp):+ assert check_ollama_running() is True++ def test_ollama_not_running(self):+ import urllib.error++ with patch(+ "openviking_cli.utils.ollama.urllib.request.urlopen",+ side_effect=urllib.error.URLError("refused"),+ ):+ assert check_ollama_running() is False++ def test_get_models(self):+ mock_data = json.dumps({+ "models": [+ {"name": "qwen3-embedding:0.6b", "size": 639000000},+ {"name": "gemma4:e4b", "size": 9600000000},+ ]+ }).encode()++ mock_resp = MagicMock()+ mock_resp.read.return_value = mock_data+ mock_resp.__enter__ = MagicMock(return_value=mock_resp)+ mock_resp.__exit__ = MagicMock(return_value=False)++ with patch("openviking_cli.utils.ollama.urllib.request.urlopen", return_value=mock_resp):+ models = get_ollama_models()+ assert "qwen3-embedding:0.6b" in models+ assert "gemma4:e4b" in models++ def test_get_models_error(self):+ import urllib.error++ with patch(+ "openviking_cli.utils.ollama.urllib.request.urlopen",+ side_effect=urllib.error.URLError("refused"),+ ):+ assert get_ollama_models() == []+++# ---------------------------------------------------------------------------+# Model availability+# ---------------------------------------------------------------------------+++class TestModelAvailability:+ def test_exact_match(self):+ available = ["qwen3-embedding:0.6b", "gemma4:e4b"]+ assert is_model_available("qwen3-embedding:0.6b", available) is True++ def test_no_match(self):+ available = ["qwen3-embedding:0.6b"]+ assert is_model_available("nomic-embed-text", available) is False++ def test_tagless_matches_latest(self):+ available = ["gemma:300m"]+ assert is_model_available("gemma", available) is True++ def test_prefix_variant(self):+ available = ["qwen3-embedding:0.6b-fp16"]+ assert is_model_available("qwen3-embedding:0.6b", available) is True+++# ---------------------------------------------------------------------------+# Config building+# ---------------------------------------------------------------------------+++class TestConfigBuilding:+ def test_ollama_config_structure(self):+ embedding = EMBEDDING_PRESETS[0] # qwen3-embedding:0.6b+ vlm = VLM_PRESETS[0] # qwen3.5:2b++ config = _build_ollama_config(embedding, vlm, "/tmp/ov_test")++ assert config["storage"]["workspace"] == "/tmp/ov_test"++ dense = config["embedding"]["dense"]+ assert dense["provider"] == "ollama"+ assert dense["model"] == "qwen3-embedding:0.6b"+ assert dense["dimension"] == 1024+ assert dense["api_base"] == "http://localhost:11434/v1"++ vlm_cfg = config["vlm"]+ assert vlm_cfg["provider"] == "litellm"+ assert vlm_cfg["model"] == "ollama/qwen3.5:2b"+ assert vlm_cfg["api_key"] == "no-key"+ assert vlm_cfg["api_base"] == "http://localhost:11434"++ def test_cloud_config_structure(self):+ provider = CLOUD_PROVIDERS[0] # OpenAI++ config = _build_cloud_config(+ provider,+ embedding_api_key="sk-test",+ embedding_model="text-embedding-3-small",+ embedding_dim=1536,+ vlm_api_key="sk-test",+ vlm_model="gpt-4o-mini",+ workspace="/tmp/ov_test",+ )++ assert config["embedding"]["dense"]["api_key"] == "sk-test"+ assert config["vlm"]["api_key"] == "sk-test"+ assert config["vlm"]["provider"] == "openai"++ def test_all_presets_valid(self):+ """Every preset should produce a config with required fields."""+ for emb in EMBEDDING_PRESETS:+ for vlm in VLM_PRESETS:+ config = _build_ollama_config(emb, vlm, "/tmp/test")+ assert "embedding" in config+ assert "vlm" in config+ assert config["embedding"]["dense"]["dimension"] > 0+++# ---------------------------------------------------------------------------+# RAM-based recommendations+# ---------------------------------------------------------------------------+++class TestRAMRecommendations:+ def test_low_ram(self):+ emb_idx, vlm_idx = _get_recommended_indices(4)+ assert EMBEDDING_PRESETS[emb_idx].model == "qwen3-embedding:0.6b"+ assert VLM_PRESETS[vlm_idx].ollama_model == "qwen3.5:2b"++ def test_medium_ram(self):+ emb_idx, vlm_idx = _get_recommended_indices(16)+ assert EMBEDDING_PRESETS[emb_idx].model == "qwen3-embedding:0.6b"+ assert VLM_PRESETS[vlm_idx].ollama_model == "qwen3.5:4b"++ def test_high_ram(self):+ emb_idx, vlm_idx = _get_recommended_indices(32)+ assert EMBEDDING_PRESETS[emb_idx].model == "qwen3-embedding:8b"++ def test_very_high_ram(self):+ emb_idx, vlm_idx = _get_recommended_indices(128)+ assert EMBEDDING_PRESETS[emb_idx].model == "qwen3-embedding:8b"+++# ---------------------------------------------------------------------------+# Config writing+# ---------------------------------------------------------------------------+++class TestConfigWriting:+ def test_write_new_config(self, tmp_path):+ config_path = tmp_path / "ov.conf"+ config = _build_ollama_config(EMBEDDING_PRESETS[0], VLM_PRESETS[0], str(tmp_path / "data"))++ assert _write_config(config, config_path) is True+ assert config_path.exists()++ loaded = json.loads(config_path.read_text(encoding="utf-8"))+ assert loaded["embedding"]["dense"]["provider"] == "ollama"++ def test_backup_existing(self, tmp_path):+ config_path = tmp_path / "ov.conf"+ config_path.write_text('{"old": true}', encoding="utf-8")++ config = _build_ollama_config(EMBEDDING_PRESETS[0], VLM_PRESETS[0], str(tmp_path / "data"))+ assert _write_config(config, config_path) is True++ backup = tmp_path / "ov.conf.bak"+ assert backup.exists()+ assert json.loads(backup.read_text())["old"] is True++ def test_creates_parent_dirs(self, tmp_path):+ config_path = tmp_path / "subdir" / "ov.conf"+ config = _build_ollama_config(EMBEDDING_PRESETS[0], VLM_PRESETS[0], "/tmp/data")++ assert _write_config(config, config_path) is True+ assert config_path.exists()diff --git a/tests/unit/test_ollama_utils.py b/tests/unit/test_ollama_utils.pynew file mode 100644index 000000000..8fea27ccf--- /dev/null+++ b/tests/unit/test_ollama_utils.py@@ -0,0 +1,193 @@+"""Tests for the shared Ollama utility module."""++from __future__ import annotations++from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest++from openviking_cli.utils.ollama import (+ OllamaStartResult,+ check_ollama_running,+ detect_ollama_in_config,+ ensure_ollama_for_server,+ parse_ollama_url,+ start_ollama,+)+++# ---------------------------------------------------------------------------+# parse_ollama_url+# ---------------------------------------------------------------------------+++class TestParseOllamaUrl:+ def test_localhost_with_v1_suffix(self):+ assert parse_ollama_url("http://localhost:11434/v1") == ("localhost", 11434)++ def test_custom_host(self):+ assert parse_ollama_url("http://gpu-server:11434") == ("gpu-server", 11434)++ def test_ip_address(self):+ assert parse_ollama_url("http://192.168.1.100:11434/v1") == ("192.168.1.100", 11434)++ def test_custom_port(self):+ assert parse_ollama_url("http://localhost:8080") == ("localhost", 8080)++ def test_none_returns_defaults(self):+ assert parse_ollama_url(None) == ("localhost", 11434)++ def test_empty_returns_defaults(self):+ assert parse_ollama_url("") == ("localhost", 11434)+++# ---------------------------------------------------------------------------+# detect_ollama_in_config+# ---------------------------------------------------------------------------+++def _make_config(+ embedding_provider="volcengine",+ embedding_api_base=None,+ vlm_provider="volcengine",+ vlm_model="doubao-seed",+ vlm_api_base=None,+):+ """Build a minimal config-like object for detect_ollama_in_config."""+ dense = SimpleNamespace(provider=embedding_provider, api_base=embedding_api_base)+ embedding = SimpleNamespace(dense=dense)+ vlm = SimpleNamespace(provider=vlm_provider, model=vlm_model, api_base=vlm_api_base)+ return SimpleNamespace(embedding=embedding, vlm=vlm)+++class TestDetectOllamaInConfig:+ def test_embedding_ollama_detected(self):+ config = _make_config(+ embedding_provider="ollama",+ embedding_api_base="http://localhost:11434/v1",+ )+ uses, host, port = detect_ollama_in_config(config)+ assert uses is True+ assert host == "localhost"+ assert port == 11434++ def test_vlm_ollama_detected(self):+ config = _make_config(+ vlm_provider="litellm",+ vlm_model="ollama/gemma4:e4b",+ vlm_api_base="http://localhost:11434",+ )+ uses, host, port = detect_ollama_in_config(config)+ assert uses is True+ assert host == "localhost"+ assert port == 11434++ def test_both_detected_uses_embedding_url(self):+ config = _make_config(+ embedding_provider="ollama",+ embedding_api_base="http://gpu-server:11434/v1",+ vlm_provider="litellm",+ vlm_model="ollama/qwen3.5:9b",+ vlm_api_base="http://localhost:11434",+ )+ uses, host, port = detect_ollama_in_config(config)+ assert uses is True+ assert host == "gpu-server" # embedding takes priority++ def test_neither_detected(self):+ config = _make_config()+ uses, host, port = detect_ollama_in_config(config)+ assert uses is False++ def test_litellm_non_ollama_model(self):+ config = _make_config(vlm_provider="litellm", vlm_model="anthropic/claude-3")+ uses, _, _ = detect_ollama_in_config(config)+ assert uses is False++ def test_custom_api_base(self):+ config = _make_config(+ embedding_provider="ollama",+ embedding_api_base="http://192.168.1.50:8080/v1",+ )+ uses, host, port = detect_ollama_in_config(config)+ assert uses is True+ assert host == "192.168.1.50"+ assert port == 8080+++# ---------------------------------------------------------------------------+# ensure_ollama_for_server+# ---------------------------------------------------------------------------+++class TestEnsureOllamaForServer:+ @patch("openviking_cli.utils.ollama.check_ollama_running", return_value=True)+ def test_already_running(self, mock_check):+ result = ensure_ollama_for_server()+ assert result.success is True+ assert "running" in result.message++ @patch("openviking_cli.utils.ollama.check_ollama_running", return_value=False)+ def test_remote_host_unreachable(self, mock_check):+ result = ensure_ollama_for_server(host="gpu-server", port=11434)+ assert result.success is False+ assert "remote" in result.message.lower()++ @patch("openviking_cli.utils.ollama.check_ollama_running", return_value=False)+ @patch("openviking_cli.utils.ollama.is_ollama_installed", return_value=False)+ def test_not_installed(self, mock_installed, mock_check):+ result = ensure_ollama_for_server()+ assert result.success is False+ assert "not installed" in result.message++ @patch("openviking_cli.utils.ollama.start_ollama")+ @patch("openviking_cli.utils.ollama.is_ollama_installed", return_value=True)+ @patch("openviking_cli.utils.ollama.check_ollama_running", return_value=False)+ def test_installed_starts_ollama(self, mock_check, mock_installed, mock_start):+ mock_start.return_value = OllamaStartResult(success=True, message="started")+ result = ensure_ollama_for_server()+ assert result.success is True+ mock_start.assert_called_once()+++# ---------------------------------------------------------------------------+# start_ollama+# ---------------------------------------------------------------------------+++class TestStartOllama:+ @patch("openviking_cli.utils.ollama.check_ollama_running", return_value=True)+ def test_already_running_returns_success(self, mock_check):+ result = start_ollama()+ assert result.success is True+ assert result.message == "already running"++ @patch("openviking_cli.utils.ollama.check_ollama_running", return_value=False)+ @patch("subprocess.Popen", side_effect=FileNotFoundError)+ def test_command_not_found(self, mock_popen, mock_check):+ result = start_ollama()+ assert result.success is False+ assert "not found" in result.message++ @patch("openviking_cli.utils.ollama.check_ollama_running")+ @patch("subprocess.Popen")+ @patch("openviking_cli.utils.ollama.time.sleep")+ def test_start_success(self, mock_sleep, mock_popen, mock_check):+ # First call: not running (initial check), second call onward: running+ mock_check.side_effect = [False, False, True]+ mock_popen.return_value = MagicMock()++ result = start_ollama()+ assert result.success is True+ assert result.message == "started"++ @patch("openviking_cli.utils.ollama.check_ollama_running", return_value=False)+ @patch("subprocess.Popen")+ @patch("openviking_cli.utils.ollama.time.sleep")+ def test_start_timeout(self, mock_sleep, mock_popen, mock_check):+ mock_popen.return_value = MagicMock()++ result = start_ollama()+ assert result.success is False+ assert "timeout" in result.message.lower()