{"repo": "Chen-zexi/vllm-cli", "n_pairs": 125, "version": "v2_function_scoped", "contexts": {"tests/test_ollama_integration_fixed.py::314": {"resolved_imports": ["src/vllm_cli/models/cache.py", "src/vllm_cli/models/manager.py", "src/vllm_cli/models/discovery.py"], "used_names": ["ModelManager", "build_model_dict", "patch"], "enclosing_function": "test_full_ollama_workflow", "extracted_code": "# Source: src/vllm_cli/models/manager.py\nclass ModelManager:\n \"\"\"\n Manages model discovery, caching, and metadata operations.\n\n Provides a high-level interface for model operations including\n listing, searching, and retrieving model information with\n integrated caching for performance.\n \"\"\"\n\n def __init__(self):\n self.cache = ModelCache()\n\n def list_available_models(self, refresh: bool = False) -> List[Dict[str, Any]]:\n \"\"\"\n List all available downloaded models with caching.\n\n Model scanning can be expensive, so results are cached for a short time\n to improve performance when multiple UI components need model data.\n\n Args:\n refresh: Force refresh the model cache, ignoring TTL\n\n Returns:\n List of model dictionaries with keys:\n - name: Full model name (publisher/model)\n - size: Model size in bytes\n - path: Path to model directory\n - type: Model type (model, custom_model)\n - publisher: Model publisher/organization\n - display_name: Human-readable model name\n - metadata: Additional model metadata\n \"\"\"\n # If refresh is forced, clear cache first to ensure fresh data\n if refresh:\n self.cache.clear_cache()\n logger.debug(\"Cache cleared for forced refresh\")\n else:\n # Check cache only if not refreshing\n cached_models = self.cache.get_cached_models()\n if cached_models is not None:\n return cached_models\n\n # Fetch fresh model data\n models = scan_for_models()\n\n # Process and normalize model data\n processed_models = []\n for item in models:\n # Accept all model types from hf-model-tool\n model_types = [\"model\", \"custom_model\", \"ollama_model\", \"gguf_model\"]\n if item.get(\"type\") in model_types:\n # For Ollama/GGUF models, use the item directly (already formatted)\n if item.get(\"type\") in [\"ollama_model\", \"gguf_model\"]:\n processed_models.append(item)\n else:\n model_dict = build_model_dict(item)\n processed_models.append(model_dict)\n\n # Sort models by name\n processed_models.sort(key=lambda x: x[\"name\"])\n\n # Update cache\n self.cache.cache_models(processed_models)\n\n logger.info(f\"Found {len(processed_models)} models\")\n return processed_models\n\n def get_model_details(self, model_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get detailed information about a specific model.\n\n Args:\n model_name: Name of the model to get details for\n\n Returns:\n Dictionary with model details or None if not found\n \"\"\"\n # First, try to find from cached models\n models = self.list_available_models()\n model_info = None\n\n for model in models:\n if model[\"name\"] == model_name or model.get(\"display_name\") == model_name:\n model_info = model\n break\n\n if not model_info:\n logger.warning(f\"Model {model_name} not found\")\n return None\n\n # Build detailed information\n details = {\n \"name\": model_info[\"name\"],\n \"full_name\": model_info[\"name\"],\n \"path\": model_info.get(\"path\", \"\"),\n \"size\": model_info.get(\"size\", 0),\n \"type\": model_info.get(\"type\", \"model\"),\n \"publisher\": model_info.get(\"publisher\", \"unknown\"),\n \"display_name\": model_info.get(\"display_name\", model_name),\n }\n\n # Extract metadata if available\n metadata = model_info.get(\"metadata\", {})\n if metadata:\n details[\"architecture\"] = (\n metadata.get(\"architectures\", [\"unknown\"])[0]\n if metadata.get(\"architectures\")\n else \"unknown\"\n )\n details[\"model_type\"] = metadata.get(\"model_type\", \"unknown\")\n details[\"torch_dtype\"] = metadata.get(\"torch_dtype\", \"unknown\")\n details[\"vocab_size\"] = metadata.get(\"vocab_size\", \"unknown\")\n\n # Add to main details\n details[\"metadata\"] = metadata\n\n # Try to read config.json for more details if path exists\n if details[\"path\"]:\n from .metadata import extract_model_config\n\n config_data = extract_model_config(details[\"path\"])\n if config_data:\n details.update(config_data)\n\n return details\n\n def search_models(self, query: str) -> List[Dict[str, Any]]:\n \"\"\"\n Search for models matching a query.\n\n Args:\n query: Search query string\n\n Returns:\n List of matching models\n \"\"\"\n models = self.list_available_models()\n query_lower = query.lower()\n\n # Filter models matching the query\n matches = []\n for model in models:\n if (\n query_lower in model[\"name\"].lower()\n or query_lower in model.get(\"display_name\", \"\").lower()\n or query_lower in model.get(\"publisher\", \"\").lower()\n ):\n matches.append(model)\n\n return matches\n\n def get_model_count(self) -> int:\n \"\"\"\n Get the total number of available models.\n\n Returns:\n Number of available models\n \"\"\"\n return len(self.list_available_models())\n\n def get_models_by_publisher(self, publisher: str) -> List[Dict[str, Any]]:\n \"\"\"\n Get all models from a specific publisher.\n\n Args:\n publisher: Publisher/organization name\n\n Returns:\n List of models from the publisher\n \"\"\"\n models = self.list_available_models()\n return [\n model\n for model in models\n if model.get(\"publisher\", \"\").lower() == publisher.lower()\n ]\n\n def get_models_by_type(self, model_type: str) -> List[Dict[str, Any]]:\n \"\"\"\n Get all models of a specific type.\n\n Args:\n model_type: Type of model (e.g., 'model', 'custom_model')\n\n Returns:\n List of models of the specified type\n \"\"\"\n models = self.list_available_models()\n return [model for model in models if model.get(\"type\") == model_type]\n\n def refresh_cache(self) -> None:\n \"\"\"Force refresh of the model cache.\"\"\"\n # First, force registry refresh to pick up any changes\n try:\n import os\n from pathlib import Path\n\n from hf_model_tool import get_registry\n\n # Clear all possible cache files\n cache_locations = [\n Path.home() / \".config/hf-model-tool/registry_cache.json\",\n Path.home() / \".cache/hf-model-tool/registry.json\",\n Path.home() / \".hf-model-tool/cache.json\",\n ]\n\n for cache_file in cache_locations:\n if cache_file.exists():\n try:\n os.remove(cache_file)\n logger.debug(f\"Removed cache file: {cache_file}\")\n except Exception as e:\n logger.debug(f\"Could not remove {cache_file}: {e}\")\n\n # Get registry and clear its in-memory cache\n registry = get_registry()\n\n # Clear all in-memory collections\n registry.models.clear()\n registry.custom_models.clear()\n registry.ollama_models.clear()\n registry.gguf_models.clear()\n registry.lora_adapters.clear()\n registry.datasets.clear()\n\n # Reset scan time to force rescan\n registry._last_scan_time = 0\n\n # Force complete rescan without incremental updates\n registry.scan_all(force=True, incremental=False)\n logger.info(\"Forced complete registry refresh\")\n except Exception as e:\n logger.debug(f\"Registry refresh error: {e}\")\n\n # Clear the cache to ensure we don't get stale data\n self.cache.clear_cache()\n logger.debug(\"Cache cleared\")\n\n # Now fetch fresh models - this will populate the cache with new data\n models = self.list_available_models(refresh=True)\n logger.info(f\"Model cache refreshed with {len(models)} models\")\n\n def get_cache_stats(self) -> Dict[str, Any]:\n \"\"\"\n Get cache statistics.\n\n Returns:\n Dictionary with cache statistics\n \"\"\"\n return self.cache.get_cache_stats()\n\n\n# Source: src/vllm_cli/models/discovery.py\ndef build_model_dict(item: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Build a standardized model dictionary from model data.\n\n Takes raw model information from various sources and normalizes\n it into a consistent format.\n\n Args:\n item: Model item data\n\n Returns:\n Standardized model dictionary\n \"\"\"\n publisher = item.get(\"publisher\", \"unknown\")\n display_name = item.get(\"display_name\", item.get(\"name\", \"unknown\"))\n\n # Create proper model name\n if publisher and publisher != \"unknown\":\n model_name = f\"{publisher}/{display_name}\"\n else:\n model_name = display_name\n\n return {\n \"name\": model_name,\n \"size\": item.get(\"size\", 0),\n \"path\": item.get(\"path\", \"\"),\n \"type\": item.get(\"type\", \"model\"),\n \"publisher\": publisher,\n \"display_name\": display_name,\n \"metadata\": item.get(\"metadata\", {}),\n }", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 9607}, "tests/proxy/test_integration.py::285": {"resolved_imports": ["src/vllm_cli/proxy/config.py", "src/vllm_cli/proxy/manager.py", "src/vllm_cli/proxy/models.py", "src/vllm_cli/proxy/server_process.py"], "used_names": ["MagicMock", "ModelConfig", "ProxyConfig", "ProxyManager", "patch"], "enclosing_function": "test_gpu_assignment_integration", "extracted_code": "# Source: src/vllm_cli/proxy/manager.py\nclass ProxyManager:\n \"\"\"\n Manages the lifecycle of multiple vLLM servers and the proxy server.\n \"\"\"\n\n def __init__(self, config: Optional[ProxyConfig] = None):\n \"\"\"\n Initialize the proxy manager.\n\n Args:\n config: Proxy configuration (uses defaults if not provided)\n \"\"\"\n self.proxy_config = config or ProxyConfig()\n self.proxy_process: Optional[ProxyServerProcess] = None\n self.vllm_servers: Dict[str, VLLMServer] = {}\n self.config_manager = ConfigManager()\n\n def _proxy_api_request(\n self,\n method: str,\n endpoint: str,\n json_data: Optional[Dict] = None,\n timeout: float = 5.0,\n ) -> Optional[Any]:\n \"\"\"\n Helper method for making HTTP requests to the proxy API.\n\n Args:\n method: HTTP method (POST, DELETE, GET)\n endpoint: API endpoint path\n json_data: Optional JSON data for request body\n timeout: Request timeout in seconds\n\n Returns:\n Response object if successful, None if failed\n \"\"\"\n try:\n import httpx\n\n url = f\"http://localhost:{self.proxy_config.port}{endpoint}\"\n with httpx.Client() as client:\n if method == \"POST\":\n response = client.post(url, json=json_data, timeout=timeout)\n elif method == \"DELETE\":\n response = client.delete(url, timeout=timeout)\n elif method == \"GET\":\n response = client.get(url, timeout=timeout)\n else:\n logger.error(f\"Unsupported HTTP method: {method}\")\n return None\n\n if response.status_code == 200:\n return response\n else:\n logger.warning(\n f\"API request failed: {method} {endpoint} - \"\n f\"{response.status_code}: {response.text}\"\n )\n return None\n\n except Exception as e:\n logger.warning(f\"API request error: {method} {endpoint} - {e}\")\n return None\n\n def start_proxy(self) -> bool:\n \"\"\"\n Start the proxy server.\n\n Returns:\n True if proxy started successfully\n \"\"\"\n try:\n # Create proxy server process instance\n self.proxy_process = ProxyServerProcess(self.proxy_config)\n\n # Start proxy as a subprocess\n if not self.proxy_process.start():\n logger.error(\"Failed to start proxy server process\")\n return False\n\n # Give it a moment to fully initialize\n time.sleep(2)\n\n # Register all running models with the proxy\n # Note: We'll need to update this to work with subprocess\n # For now, models will register when they start\n\n logger.info(\n f\"Proxy server started on \"\n f\"{self.proxy_config.host}:{self.proxy_config.port}\"\n )\n return True\n\n except Exception as e:\n logger.error(f\"Failed to start proxy server: {e}\")\n return False\n\n def stop_proxy(self):\n \"\"\"Stop the proxy server and all vLLM instances.\"\"\"\n logger.info(\"Stopping proxy server and all model servers...\")\n\n # Stop all vLLM servers\n for model_name in list(self.vllm_servers.keys()):\n self.stop_model(model_name)\n\n # Stop proxy server process\n if self.proxy_process:\n self.proxy_process.stop()\n self.proxy_process = None\n logger.info(\"Proxy server stopped\")\n\n def start_model(self, model_config: ModelConfig) -> bool:\n \"\"\"\n Start a vLLM server for a specific model.\n\n Args:\n model_config: Configuration for the model\n\n Returns:\n True if server started successfully\n \"\"\"\n try:\n # Check if model is already running\n if model_config.name in self.vllm_servers:\n logger.warning(f\"Model '{model_config.name}' is already running\")\n return False\n\n # Build vLLM server configuration\n vllm_config = self._build_vllm_config(model_config)\n\n # Pre-register with proxy if it's running\n if self.proxy_process and self.proxy_process.is_running():\n pre_register_data = {\n \"port\": model_config.port,\n \"gpu_ids\": model_config.gpu_ids,\n \"config_name\": model_config.name,\n }\n\n response = self._proxy_api_request(\n \"POST\", \"/proxy/pre_register\", pre_register_data\n )\n if response:\n logger.info(\n f\"Pre-registered model '{model_config.name}' with proxy\"\n )\n else:\n logger.warning(\n f\"Failed to pre-register model '{model_config.name}' with proxy\"\n )\n\n # Create and start vLLM server\n server = VLLMServer(vllm_config)\n if not server.start():\n logger.error(f\"Failed to start vLLM server for '{model_config.name}'\")\n return False\n\n # Store server reference\n self.vllm_servers[model_config.name] = server\n\n logger.info(\n f\"Started vLLM server process for '{model_config.name}' \"\n f\"on port {model_config.port} using GPUs {model_config.gpu_ids}\"\n )\n\n # Note: Registration with proxy will happen after startup completes\n # Registration happens during wait_and_register_model()\n\n return True\n\n except Exception as e:\n logger.error(f\"Failed to start model '{model_config.name}': {e}\")\n return False\n\n def wait_and_register_model(self, model_config: ModelConfig) -> bool:\n \"\"\"\n Wait for a model to complete startup and trigger proxy refresh.\n\n Args:\n model_config: Configuration for the model\n\n Returns:\n True if model started and registered successfully\n \"\"\"\n if model_config.name not in self.vllm_servers:\n logger.error(f\"Model '{model_config.name}' not found in servers\")\n return False\n\n server = self.vllm_servers[model_config.name]\n\n # Wait for server to complete startup\n if not server.wait_for_startup():\n logger.error(f\"Server '{model_config.name}' failed to complete startup\")\n # Clean up the failed server\n server.stop()\n del self.vllm_servers[model_config.name]\n return False\n\n # Trigger proxy refresh to verify and activate the model\n if self.proxy_process and self.proxy_process.is_running():\n # Call refresh to verify the pre-registered model\n response = self._proxy_api_request(\n \"POST\", \"/proxy/refresh_models\", timeout=10.0\n )\n if response:\n try:\n result = response.json()\n summary = result.get(\"summary\", {})\n if summary.get(\"registered\", 0) > 0:\n logger.info(\n f\"Model '{model_config.name}' successfully activated \"\n f\"on port {model_config.port}\"\n )\n return True\n else:\n logger.warning(\n f\"Model '{model_config.name}' started but \"\n f\"not activated in proxy\"\n )\n return True # Model is running, just not registered\n except Exception as e:\n logger.error(f\"Failed to parse refresh response: {e}\")\n return True # Model is running\n else:\n logger.warning(\n f\"Failed to refresh proxy after starting \"\n f\"model '{model_config.name}'\"\n )\n return True # Model is running even if refresh failed\n\n logger.info(f\"Model '{model_config.name}' is ready\")\n return True\n\n def refresh_model_registrations(self) -> Dict[str, Any]:\n \"\"\"\n Refresh model registrations with the proxy.\n\n Calls the proxy's refresh endpoint to verify all models in the registry.\n\n Returns:\n Dictionary with registration results\n \"\"\"\n if not self.proxy_process or not self.proxy_process.is_running():\n logger.warning(\"Proxy is not running, cannot refresh registrations\")\n return {\"status\": \"error\", \"message\": \"Proxy server is not running\"}\n\n # Call the refresh endpoint\n response = self._proxy_api_request(\n \"POST\", \"/proxy/refresh_models\", timeout=10.0\n )\n\n if response:\n try:\n result = response.json()\n summary = result.get(\"summary\", {})\n logger.info(\n f\"Model registration refresh completed: \"\n f\"{summary.get('registered', 0)} newly registered, \"\n f\"{summary.get('failed', 0)} newly failed, \"\n f\"{summary.get('already_available', 0)} already available, \"\n f\"{summary.get('removed', 0)} removed\"\n )\n return result\n except Exception as e:\n logger.error(f\"Failed to parse refresh response: {e}\")\n return {\"status\": \"error\", \"message\": f\"Failed to parse response: {e}\"}\n else:\n logger.error(\"Failed to refresh model registrations\")\n return {\n \"status\": \"error\",\n \"message\": \"Failed to connect to proxy refresh endpoint\",\n }\n\n def get_proxy_registry_status(self) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get full model registry status from proxy.\n\n Returns:\n Dictionary containing proxy status and all registered models,\n or None if proxy is not running\n \"\"\"\n if not self.proxy_process or not self.proxy_process.is_running():\n logger.warning(\"Proxy is not running, cannot get registry status\")\n return None\n\n response = self._proxy_api_request(\"GET\", \"/proxy/registry\")\n if response:\n try:\n return response.json()\n except Exception as e:\n logger.error(f\"Failed to parse proxy status response: {e}\")\n return None\n return None\n\n def sleep_model(self, model_name: str, level: int = 1) -> bool:\n \"\"\"\n Put a model to sleep, freeing GPU memory but keeping the port.\n Runs asynchronously and returns immediately.\n\n Args:\n model_name: Name of the model to sleep\n level: Sleep level (1=offload weights, 2=discard weights)\n\n Returns:\n True if sleep request was initiated successfully\n \"\"\"\n if model_name not in self.vllm_servers:\n logger.warning(f\"Model '{model_name}' is not running\")\n return False\n\n server = self.vllm_servers[model_name]\n port = server.port\n\n try:\n import threading\n\n import httpx\n\n def sleep_thread():\n try:\n # Use 10 minute timeout for very slow operations\n client = httpx.Client(timeout=600.0)\n logger.info(\n f\"Sending sleep request to model '{model_name}' \"\n f\"(level {level})...\"\n )\n response = client.post(\n f\"http://localhost:{port}/sleep?level={level}\"\n )\n client.close()\n\n if response.status_code == 200:\n logger.info(\n f\"Model '{model_name}' successfully put to sleep \"\n f\"(level {level})\"\n )\n\n # Update proxy registry state\n if self.proxy_process and self.proxy_process.is_running():\n state_data = {\n \"port\": port,\n \"state\": \"sleeping\",\n \"sleep_level\": level,\n }\n self._proxy_api_request(\"POST\", \"/proxy/state\", state_data)\n else:\n logger.error(\n f\"Failed to sleep model '{model_name}': \"\n f\"HTTP {response.status_code}\"\n )\n\n except Exception as e:\n logger.error(f\"Failed to sleep model '{model_name}': {e}\")\n\n # Start in background thread\n thread = threading.Thread(target=sleep_thread, daemon=True)\n thread.start()\n logger.info(f\"Sleep operation initiated for '{model_name}'\")\n return True\n\n except Exception as e:\n logger.error(f\"Failed to initiate sleep for '{model_name}': {e}\")\n return False\n\n def wake_model(self, model_name: str) -> bool:\n \"\"\"\n Wake up a sleeping model.\n Runs asynchronously and returns immediately.\n\n Args:\n model_name: Name of the model to wake\n\n Returns:\n True if wake request was initiated successfully\n \"\"\"\n if model_name not in self.vllm_servers:\n logger.warning(f\"Model '{model_name}' is not running\")\n return False\n\n server = self.vllm_servers[model_name]\n port = server.port\n\n try:\n import threading\n\n import httpx\n\n def wake_thread():\n try:\n # Use 10 minute timeout for very slow operations\n client = httpx.Client(timeout=600.0)\n logger.info(f\"Sending wake-up request to model '{model_name}'...\")\n response = client.post(f\"http://localhost:{port}/wake_up\")\n client.close()\n\n # Accept both 200 (OK) and 202 (Accepted) as success\n if response.status_code in [200, 202]:\n logger.info(f\"Model '{model_name}' successfully woken up\")\n\n # Update proxy registry state\n if self.proxy_process and self.proxy_process.is_running():\n state_data = {\n \"port\": port,\n \"state\": \"running\",\n \"sleep_level\": 0,\n }\n self._proxy_api_request(\"POST\", \"/proxy/state\", state_data)\n else:\n logger.error(\n f\"Failed to wake model '{model_name}': \"\n f\"HTTP {response.status_code}\"\n )\n\n except Exception as e:\n logger.error(f\"Failed to wake model '{model_name}': {e}\")\n\n # Start in background thread\n thread = threading.Thread(target=wake_thread, daemon=True)\n thread.start()\n logger.info(f\"Wake operation initiated for '{model_name}'\")\n return True\n\n except Exception as e:\n logger.error(f\"Failed to initiate wake for '{model_name}': {e}\")\n return False\n\n def is_sleeping(self, model_name: str) -> bool:\n \"\"\"\n Check if a model is sleeping.\n\n Args:\n model_name: Name of the model to check\n\n Returns:\n True if model is sleeping\n \"\"\"\n if model_name not in self.vllm_servers:\n return False\n\n server = self.vllm_servers[model_name]\n port = server.port\n\n try:\n import httpx\n\n client = httpx.Client(timeout=5.0)\n response = client.get(f\"http://localhost:{port}/is_sleeping\")\n client.close()\n\n if response.status_code == 200:\n data = response.json()\n return data.get(\"is_sleeping\", False)\n except Exception:\n pass\n\n return False\n\n def stop_model(self, model_name: str) -> bool:\n \"\"\"\n Stop a vLLM server for a specific model.\n\n Args:\n model_name: Name of the model to stop\n\n Returns:\n True if server stopped successfully\n \"\"\"\n if model_name not in self.vllm_servers:\n logger.warning(f\"Model '{model_name}' is not running\")\n return False\n\n try:\n # Get the port before stopping\n server = self.vllm_servers[model_name]\n port = server.port\n\n # Stop the vLLM server\n server.stop()\n\n # Remove from tracking\n del self.vllm_servers[model_name]\n\n # Unregister from proxy if it's running\n if self.proxy_process and self.proxy_process.is_running():\n # Use the new registry endpoint with port\n if self._proxy_api_request(\"DELETE\", f\"/proxy/models/{port}\"):\n logger.debug(f\"Unregistered model on port {port} from proxy\")\n\n logger.info(f\"Stopped vLLM server for '{model_name}'\")\n return True\n\n except Exception as e:\n logger.error(f\"Failed to stop model '{model_name}': {e}\")\n return False\n\n def unregister_model_from_proxy(self, port: int) -> bool:\n \"\"\"\n Unregister a model from the proxy registry by port.\n This is useful for cleaning up stopped models.\n\n Args:\n port: Port number of the model to unregister\n\n Returns:\n True if successfully unregistered or proxy not running\n \"\"\"\n if self.proxy_process and self.proxy_process.is_running():\n if self._proxy_api_request(\"DELETE\", f\"/proxy/models/{port}\"):\n logger.debug(f\"Unregistered model on port {port} from proxy\")\n return True\n return False\n return True # If proxy not running, consider it success\n\n def start_all_models_no_wait(self) -> int:\n \"\"\"\n Start all model processes without waiting for startup completion.\n\n This method starts all model servers concurrently and returns immediately,\n allowing the caller to monitor startup progress in real-time.\n\n Returns:\n Number of model processes successfully launched\n \"\"\"\n started_count = 0\n for model_config in self.proxy_config.models:\n if model_config.enabled:\n if self.start_model(model_config):\n started_count += 1\n # Small delay to avoid resource conflicts\n time.sleep(0.5)\n\n return started_count\n\n def start_models_with_priorities(self):\n \"\"\"\n Start models sequentially based on loading_priority.\n\n Models are grouped by priority (lower numbers first). Models within\n the same priority group start in parallel. This is a generator that\n yields each priority group after starting its models, allowing the\n UI layer to monitor startup progress with live feedback.\n\n This is useful for GPU-shared deployments where models with low\n gpu-memory-utilization should load first to claim KV cache space.\n\n Yields:\n Dictionary for each priority group:\n - priority: Priority number (or float('inf') for None)\n - priority_label: Human-readable priority label\n - models: List of ModelConfig instances in this group\n - started_models: List of ModelConfig instances that started successfully\n - failed_models: List of model names that failed to start\n - group_index: Current group number (1-indexed)\n - total_groups: Total number of priority groups\n - total_models: Total number of models across all groups\n \"\"\"\n from collections import defaultdict\n\n # Group models by loading_priority\n priority_groups = defaultdict(list)\n for model_config in self.proxy_config.models:\n if model_config.enabled:\n priority = model_config.loading_priority\n # Use a large number for None priority (load last)\n effective_priority = priority if priority is not None else float(\"inf\")\n priority_groups[effective_priority].append(model_config)\n\n # Sort priority groups (ascending order)\n sorted_priorities = sorted(priority_groups.keys())\n\n total_models = sum(len(models) for models in priority_groups.values())\n\n logger.info(\n f\"Starting {total_models} models in {len(sorted_priorities)} \"\n f\"priority group(s)\"\n )\n\n # Process each priority group sequentially\n for priority_idx, priority in enumerate(sorted_priorities, 1):\n models = priority_groups[priority]\n priority_label = (\n f\"Priority {int(priority)}\"\n if priority != float(\"inf\")\n else \"No Priority (Parallel)\"\n )\n\n logger.info(\n f\"Starting priority group {priority_idx}/{len(sorted_priorities)}: \"\n f\"{priority_label} ({len(models)} model(s))\"\n )\n\n # Start all models in this priority group (non-blocking)\n group_started = []\n group_failed = []\n\n for model_config in models:\n if self.start_model(model_config):\n group_started.append(model_config)\n logger.info(\n f\"Started {model_config.name} (port {model_config.port})\"\n )\n # Small delay to avoid resource conflicts\n time.sleep(0.5)\n else:\n group_failed.append(model_config.name)\n logger.error(f\"Failed to start {model_config.name}\")\n\n # Yield this group for UI monitoring (non-blocking)\n yield {\n \"priority\": priority,\n \"priority_label\": priority_label,\n \"models\": models,\n \"started_models\": group_started,\n \"failed_models\": group_failed,\n \"group_index\": priority_idx,\n \"total_groups\": len(sorted_priorities),\n \"total_models\": total_models,\n }\n\n # Control returns here after UI finishes monitoring this group\n\n def _build_vllm_config(self, model_config: ModelConfig) -> Dict[str, Any]:\n \"\"\"\n Build vLLM server configuration from model configuration.\n\n Args:\n model_config: Model configuration\n\n Returns:\n vLLM server configuration dictionary\n \"\"\"\n # Start with profile configuration if specified\n config = {}\n if model_config.profile:\n profile = self.config_manager.get_profile(model_config.profile)\n if profile:\n config = profile.get(\"config\", {}).copy()\n\n # Set model, port, and host\n config[\"model\"] = model_config.model_path\n config[\"port\"] = model_config.port\n config[\"host\"] = self.proxy_config.host # Use host from proxy configuration\n\n # Enable sleep mode for better resource management\n config[\"enable_sleep_mode\"] = True\n\n # Handle GPU assignment\n if model_config.gpu_ids:\n # Set CUDA_VISIBLE_DEVICES via device field\n config[\"device\"] = \",\".join(str(gpu) for gpu in model_config.gpu_ids)\n\n num_gpus = len(model_config.gpu_ids)\n\n # For single GPU assignment, override any parallel settings from profile\n if num_gpus == 1:\n # Remove parallel configuration that conflicts with single GPU\n conflicting_settings = [\n \"tensor_parallel_size\",\n \"pipeline_parallel_size\",\n \"distributed_executor_backend\",\n ]\n\n removed_settings = []\n for setting in conflicting_settings:\n if setting in config:\n removed_settings.append(f\"{setting}={config[setting]}\")\n del config[setting]\n\n # Disable expert parallelism for single GPU\n if config.get(\"enable_expert_parallel\"):\n removed_settings.append(\"enable_expert_parallel=True\")\n config[\"enable_expert_parallel\"] = False\n\n if removed_settings:\n logger.warning(\n f\"Model '{model_config.name}' assigned single GPU. \"\n f\"Overriding profile settings: {', '.join(removed_settings)}\"\n )\n\n elif num_gpus > 1:\n # For multi-GPU, set tensor_parallel_size if not already set\n if \"tensor_parallel_size\" not in config:\n config[\"tensor_parallel_size\"] = num_gpus\n elif config[\"tensor_parallel_size\"] > num_gpus:\n # Adjust if profile expects more GPUs than assigned\n logger.warning(\n f\"Model '{model_config.name}': Adjusting tensor_parallel_size \"\n f\"from {config['tensor_parallel_size']} to {num_gpus} \"\n f\"(assigned GPUs)\"\n )\n config[\"tensor_parallel_size\"] = num_gpus\n\n # Apply any config overrides\n config.update(model_config.config_overrides)\n\n return config\n\n def get_status(self) -> Dict[str, Any]:\n \"\"\"\n Get status of proxy and all model servers.\n\n Returns:\n Status dictionary\n \"\"\"\n status = {\n \"proxy_running\": self.proxy_process and self.proxy_process.is_running(),\n \"proxy_host\": self.proxy_config.host,\n \"proxy_port\": self.proxy_config.port,\n \"models\": [],\n }\n\n for model_name, server in self.vllm_servers.items():\n model_status = {\n \"name\": model_name,\n \"running\": server.is_running(),\n \"port\": server.port,\n \"uptime\": None,\n }\n\n if server.is_running() and server.start_time:\n uptime = time.time() - server.start_time.timestamp()\n model_status[\"uptime\"] = uptime\n\n status[\"models\"].append(model_status)\n\n return status\n\n def reload_model(self, model_name: str) -> bool:\n \"\"\"\n Reload a model (stop and start again).\n\n Args:\n model_name: Name of the model to reload\n\n Returns:\n True if reload successful\n \"\"\"\n # Find the model config\n model_config = None\n for config in self.proxy_config.models:\n if config.name == model_name:\n model_config = config\n break\n\n if not model_config:\n logger.error(f\"Model '{model_name}' not found in configuration\")\n return False\n\n # Stop if running\n if model_name in self.vllm_servers:\n self.stop_model(model_name)\n time.sleep(2) # Wait before restarting\n\n # Start the model\n if not self.start_model(model_config):\n return False\n\n # Wait for startup and register\n return self.wait_and_register_model(model_config)\n\n def allocate_gpus_automatically(self) -> List[ModelConfig]:\n \"\"\"\n Automatically allocate GPUs to models based on available resources.\n\n Returns:\n List of model configurations with GPU allocations\n \"\"\"\n from ..system import get_gpu_info\n\n # Get available GPUs\n gpu_info = get_gpu_info()\n if not gpu_info:\n logger.warning(\"No GPUs available for allocation\")\n return []\n\n num_gpus = len(gpu_info)\n models = self.proxy_config.models\n\n # Simple allocation strategy: distribute GPUs evenly\n allocated_configs = []\n\n if len(models) <= num_gpus:\n # Each model gets at least one GPU\n gpus_per_model = num_gpus // len(models)\n remaining_gpus = num_gpus % len(models)\n\n gpu_index = 0\n for i, model in enumerate(models):\n num_gpus_for_model = gpus_per_model\n if i < remaining_gpus:\n num_gpus_for_model += 1\n\n model.gpu_ids = list(range(gpu_index, gpu_index + num_gpus_for_model))\n gpu_index += num_gpus_for_model\n\n # Allocate port if not specified\n if not model.port:\n model.port = get_next_available_port(8001 + i)\n\n allocated_configs.append(model)\n else:\n # More models than GPUs - some models won't be allocated\n logger.warning(\n f\"More models ({len(models)}) than GPUs ({num_gpus}). \"\n f\"Only first {num_gpus} models will be allocated.\"\n )\n for i in range(num_gpus):\n models[i].gpu_ids = [i]\n if not models[i].port:\n models[i].port = get_next_available_port(8001 + i)\n allocated_configs.append(models[i])\n\n return allocated_configs\n\n def _get_model_config_by_name(self, model_name: str) -> Optional[ModelConfig]:\n \"\"\"\n Get model configuration by model name.\n\n Args:\n model_name: Name of the model\n\n Returns:\n ModelConfig if found, None otherwise\n \"\"\"\n for model_config in self.proxy_config.models:\n if model_config.name == model_name:\n return model_config\n return None\n\n @classmethod\n def from_config_file(cls, config_path: Path) -> \"ProxyManager\":\n \"\"\"\n Create ProxyManager from a configuration file.\n\n Args:\n config_path: Path to configuration file (YAML or JSON)\n\n Returns:\n ProxyManager instance\n \"\"\"\n import json\n\n import yaml\n\n with open(config_path, \"r\") as f:\n if config_path.suffix in [\".yaml\", \".yml\"]:\n config_dict = yaml.safe_load(f)\n else:\n config_dict = json.load(f)\n\n # Parse proxy configuration\n proxy_config = ProxyConfig(**config_dict.get(\"proxy\", {}))\n\n # Parse model configurations\n models = []\n for model_dict in config_dict.get(\"models\", []):\n models.append(ModelConfig(**model_dict))\n proxy_config.models = models\n\n return cls(proxy_config)\n\n\n# Source: src/vllm_cli/proxy/models.py\nclass ModelConfig(BaseModel):\n \"\"\"Configuration for a single model in the proxy.\"\"\"\n\n name: str = Field(..., description=\"Model identifier for API requests\")\n model_path: str = Field(..., description=\"Path or HuggingFace model ID\")\n gpu_ids: List[int] = Field(default_factory=list, description=\"GPU IDs to use\")\n port: int = Field(..., description=\"Port for the vLLM server\")\n profile: Optional[str] = Field(None, description=\"vLLM CLI profile to use\")\n config_overrides: Dict[str, Any] = Field(\n default_factory=dict, description=\"Additional vLLM configuration\"\n )\n enabled: bool = Field(True, description=\"Whether model is enabled\")\n loading_priority: Optional[int] = Field(\n None,\n description=\"Loading priority (lower numbers load first). \"\n \"Models with same priority load in parallel. \"\n \"Models with None priority load after all prioritized models.\",\n )\n\nclass ProxyConfig(BaseModel):\n \"\"\"Configuration for the proxy server.\"\"\"\n\n host: str = Field(\"0.0.0.0\", description=\"Proxy server host\") # nosec B104\n port: int = Field(8000, description=\"Proxy server port\")\n models: List[ModelConfig] = Field(\n default_factory=list, description=\"List of models to serve\"\n )\n enable_cors: bool = Field(True, description=\"Enable CORS headers\")\n enable_metrics: bool = Field(True, description=\"Enable metrics endpoint\")\n log_requests: bool = Field(False, description=\"Log all requests\")", "n_imports_parsed": 9, "n_files_resolved": 4, "n_chars_extracted": 32708}, "tests/proxy/test_e2e.py::467": {"resolved_imports": ["src/vllm_cli/proxy/manager.py", "src/vllm_cli/proxy/models.py", "src/vllm_cli/proxy/server.py", "src/vllm_cli/proxy/registry.py"], "used_names": ["ModelConfig", "ModelState", "ProxyConfig", "ProxyServer", "asyncio", "pytest"], "enclosing_function": "test_e2e_full_model_lifecycle_with_registry", "extracted_code": "# Source: src/vllm_cli/proxy/models.py\nclass ModelConfig(BaseModel):\n \"\"\"Configuration for a single model in the proxy.\"\"\"\n\n name: str = Field(..., description=\"Model identifier for API requests\")\n model_path: str = Field(..., description=\"Path or HuggingFace model ID\")\n gpu_ids: List[int] = Field(default_factory=list, description=\"GPU IDs to use\")\n port: int = Field(..., description=\"Port for the vLLM server\")\n profile: Optional[str] = Field(None, description=\"vLLM CLI profile to use\")\n config_overrides: Dict[str, Any] = Field(\n default_factory=dict, description=\"Additional vLLM configuration\"\n )\n enabled: bool = Field(True, description=\"Whether model is enabled\")\n loading_priority: Optional[int] = Field(\n None,\n description=\"Loading priority (lower numbers load first). \"\n \"Models with same priority load in parallel. \"\n \"Models with None priority load after all prioritized models.\",\n )\n\nclass ProxyConfig(BaseModel):\n \"\"\"Configuration for the proxy server.\"\"\"\n\n host: str = Field(\"0.0.0.0\", description=\"Proxy server host\") # nosec B104\n port: int = Field(8000, description=\"Proxy server port\")\n models: List[ModelConfig] = Field(\n default_factory=list, description=\"List of models to serve\"\n )\n enable_cors: bool = Field(True, description=\"Enable CORS headers\")\n enable_metrics: bool = Field(True, description=\"Enable metrics endpoint\")\n log_requests: bool = Field(False, description=\"Log all requests\")\n\n\n# Source: src/vllm_cli/proxy/server.py\nclass ProxyServer:\n \"\"\"\n FastAPI proxy server that routes OpenAI API requests to appropriate vLLM instances.\n \"\"\"\n\n def __init__(self, config: ProxyConfig):\n \"\"\"Initialize the proxy server with configuration.\"\"\"\n self.config = config\n self.app = FastAPI(title=\"vLLM Multi-Model Proxy\", version=\"0.1.0\")\n self.router = RequestRouter()\n self.registry = ModelRegistry() # Dynamic runtime registry\n self.start_time = datetime.now()\n self.total_requests = 0\n self.model_requests: Dict[str, int] = {}\n\n # HTTP client for forwarding requests\n self.client = httpx.AsyncClient(timeout=httpx.Timeout(timeout=300.0))\n\n # Setup middleware and routes\n self._setup_middleware()\n self._setup_routes()\n\n def _setup_middleware(self):\n \"\"\"Configure middleware for the FastAPI app.\"\"\"\n if self.config.enable_cors:\n self.app.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n )\n\n # Request logging middleware\n if self.config.log_requests:\n\n @self.app.middleware(\"http\")\n async def log_requests(request: Request, call_next):\n start_time = time.time()\n response = await call_next(request)\n duration = time.time() - start_time\n logger.info(\n f\"{request.method} {request.url.path} - \"\n f\"{response.status_code} - {duration:.3f}s\"\n )\n return response\n\n def _setup_routes(self):\n \"\"\"Setup API routes for the proxy server.\"\"\"\n\n @self.app.get(\"/\")\n async def root():\n \"\"\"Root endpoint.\"\"\"\n return {\n \"message\": \"vLLM Multi-Model Proxy Server\",\n \"version\": \"0.1.0\",\n \"models_count\": len(self.router.get_active_models()),\n }\n\n @self.app.get(\"/health\")\n async def health():\n \"\"\"Health check endpoint.\"\"\"\n return {\"status\": \"healthy\", \"timestamp\": datetime.now().isoformat()}\n\n @self.app.get(\"/v1/models\")\n async def list_models():\n \"\"\"List available models (OpenAI API compatible).\"\"\"\n models = self.router.get_active_models()\n return {\n \"object\": \"list\",\n \"data\": [\n {\n \"id\": model_name,\n \"object\": \"model\",\n \"created\": int(time.time()),\n \"owned_by\": \"vllm-cli-proxy\",\n }\n for model_name in models\n ],\n }\n\n @self.app.post(\"/v1/chat/completions\")\n async def chat_completions(request: Request):\n \"\"\"Handle chat completions requests.\"\"\"\n return await self._forward_request(request, \"/v1/chat/completions\")\n\n @self.app.post(\"/v1/completions\")\n async def completions(request: Request):\n \"\"\"Handle completions requests.\"\"\"\n return await self._forward_request(request, \"/v1/completions\")\n\n @self.app.post(\"/v1/embeddings\")\n async def embeddings(request: Request):\n \"\"\"Handle embeddings requests.\"\"\"\n return await self._forward_request(request, \"/v1/embeddings\")\n\n @self.app.post(\"/v1/responses\")\n async def responses(request: Request):\n \"\"\"Handle responses requests (OpenAI Responses API).\"\"\"\n return await self._forward_request(request, \"/v1/responses\")\n\n @self.app.get(\"/proxy/status\")\n async def proxy_status():\n \"\"\"Get proxy server status.\"\"\"\n models_status = []\n\n # Get models from registry\n for port, model_entry in self.registry.get_all_models().items():\n models_status.append(\n ModelStatus(\n name=model_entry.display_name,\n model_path=\"\", # Not tracked in registry\n port=port,\n gpu_ids=model_entry.gpu_ids,\n status=(\n \"running\"\n if model_entry.state.value == \"running\"\n else \"stopped\"\n ),\n registration_status=model_entry.status.value,\n request_count=0, # Not tracked in simplified registry\n )\n )\n\n return ProxyStatus(\n proxy_running=True,\n proxy_port=self.config.port,\n proxy_host=self.config.host,\n models=models_status,\n total_requests=self.total_requests,\n start_time=self.start_time.isoformat(),\n )\n\n @self.app.post(\"/proxy/pre_register\")\n async def pre_register(request: Dict[str, Any]):\n \"\"\"Pre-register a model with pending status.\"\"\"\n try:\n port = request[\"port\"]\n gpu_ids = request.get(\"gpu_ids\", [])\n config_name = request.get(\"config_name\")\n request.get(\"estimated_util\")\n\n logger.info(\n f\"Pre-registering model '{config_name}' on port {port} \"\n f\"with GPUs {gpu_ids}\"\n )\n\n # Pre-register in the runtime registry\n success = self.registry.pre_register(port, gpu_ids, config_name)\n\n if success:\n logger.info(f\"Pre-registered model on port {port}\")\n return {\n \"status\": \"success\",\n \"message\": f\"Pre-registered model on port {port}\",\n }\n else:\n message = f\"Failed to pre-register model on port {port}\"\n logger.error(message)\n raise HTTPException(status_code=400, detail=message)\n\n except Exception as e:\n logger.error(f\"Pre-registration error: {e}\")\n raise HTTPException(status_code=400, detail=str(e))\n\n @self.app.post(\"/proxy/register\")\n async def register_model(request: Dict[str, Any]):\n \"\"\"Register a new model in the runtime registry (backward compatibility).\"\"\"\n try:\n port = request[\"port\"]\n gpu_ids = request.get(\"gpu_ids\", [])\n actual_name = request.get(\"actual_name\", f\"model_{port}\")\n\n # Register in the runtime registry\n success = self.registry.verify_and_activate(port, actual_name)\n\n if success:\n # Add to router for request routing\n backend_url = f\"http://localhost:{port}\"\n self.router.add_backend(\n actual_name, backend_url, {\"port\": port, \"gpu_ids\": gpu_ids}\n )\n\n return {\n \"status\": \"success\",\n \"message\": f\"Registered model '{actual_name}' on port {port}\",\n \"actual_name\": actual_name,\n }\n else:\n message = f\"Failed to register model on port {port}\"\n raise HTTPException(status_code=400, detail=message)\n\n except Exception as e:\n raise HTTPException(status_code=400, detail=str(e))\n\n @self.app.delete(\"/proxy/models/{port}\")\n async def unregister_model(port: int):\n \"\"\"Unregister a model from the runtime registry.\"\"\"\n try:\n # Get model info before unregistering\n model_entry = self.registry.get_model(port)\n if not model_entry:\n raise HTTPException(\n status_code=404, detail=f\"Model on port {port} not found\"\n )\n\n # Unregister from registry\n success = self.registry.remove_model(port)\n message = (\n f\"Model on port {port} unregistered\"\n if success\n else f\"Model on port {port} not found\"\n )\n\n if success:\n # Remove from router\n if model_entry.actual_name:\n try:\n self.router.remove_backend(model_entry.actual_name)\n except Exception:\n pass # Router entry might not exist\n\n return {\"status\": \"success\", \"message\": message}\n else:\n raise HTTPException(status_code=400, detail=message)\n\n except HTTPException:\n raise\n except Exception as e:\n raise HTTPException(status_code=400, detail=str(e))\n\n @self.app.post(\"/proxy/state\")\n async def update_model_state(request: Dict[str, Any]):\n \"\"\"Update the state of a model (running/sleeping/stopped).\"\"\"\n try:\n port = request[\"port\"]\n state = request[\"state\"]\n sleep_level = request.get(\"sleep_level\", 0)\n\n # Update model state\n model_entry = self.registry.get_model(port)\n if model_entry:\n from .registry import ModelState\n\n if state == \"sleeping\":\n model_entry.state = ModelState.SLEEPING\n model_entry.sleep_level = sleep_level\n elif state == \"running\":\n model_entry.state = ModelState.RUNNING\n model_entry.sleep_level = 0\n elif state == \"stopped\":\n model_entry.state = ModelState.STOPPED\n message = f\"Updated state to {state}\"\n return {\"status\": \"success\", \"message\": message}\n else:\n raise HTTPException(\n status_code=404, detail=f\"Model on port {port} not found\"\n )\n\n except Exception as e:\n raise HTTPException(status_code=400, detail=str(e))\n\n @self.app.get(\"/proxy/registry\")\n async def get_registry():\n \"\"\"Get the complete registry status including GPU allocation.\"\"\"\n return self.registry.get_status_summary()\n\n @self.app.post(\"/proxy/refresh_models\")\n async def refresh_models():\n \"\"\"\n Refresh model registry - verify ALL models and update their status.\n \"\"\"\n import httpx\n\n from .registry import ModelState, RegistrationStatus\n\n # Cleanup any stale entries\n removed_count = self.registry.cleanup_stale_entries()\n if removed_count > 0:\n logger.info(f\"Removed {removed_count} stale entries\")\n\n # Get all models and check their status\n all_models = self.registry.get_all_models()\n newly_registered = []\n already_available = []\n newly_failed = []\n pending_count = 0\n\n for port, model_entry in all_models.items():\n # Check ALL models\n try:\n # Call the model's /v1/models endpoint\n async with httpx.AsyncClient() as client:\n response = await client.get(\n f\"http://localhost:{port}/v1/models\", timeout=5.0\n )\n\n if response.status_code == 200:\n # Model is responding\n # Always check if model is sleeping\n # (not just when marked as sleeping)\n is_sleeping = False\n try:\n sleep_response = await client.get(\n f\"http://localhost:{port}/is_sleeping\", timeout=2.0\n )\n if sleep_response.status_code == 200:\n sleep_data = sleep_response.json()\n is_sleeping = sleep_data.get(\"is_sleeping\", False)\n\n # Update model state based on actual sleep status\n if (\n is_sleeping\n and model_entry.state != ModelState.SLEEPING\n ):\n model_entry.state = ModelState.SLEEPING\n logger.info(f\"Model on port {port} is sleeping\")\n elif (\n not is_sleeping\n and model_entry.state == ModelState.SLEEPING\n ):\n model_entry.state = ModelState.RUNNING\n logger.info(\n f\"Model on port {port} has been woken up\"\n )\n elif not is_sleeping:\n model_entry.state = ModelState.RUNNING\n except Exception:\n # If /is_sleeping endpoint doesn't exist or fails,\n # check current state. If it was sleeping, keep it as\n # sleeping; otherwise assume running\n if model_entry.state != ModelState.SLEEPING:\n model_entry.state = ModelState.RUNNING\n\n # Extract actual model name from response\n models_data = response.json()\n actual_name = None\n if models_data.get(\"data\"):\n actual_name = models_data[\"data\"][0].get(\"id\")\n\n # Check previous status\n was_pending = (\n model_entry.status == RegistrationStatus.PENDING\n )\n was_error = model_entry.status == RegistrationStatus.ERROR\n\n # Verify and activate the model\n if self.registry.verify_and_activate(port, actual_name):\n if was_pending or was_error:\n newly_registered.append(\n actual_name or f\"port_{port}\"\n )\n else:\n already_available.append(\n actual_name or f\"port_{port}\"\n )\n\n # Ensure it's in the router\n if (\n actual_name\n and actual_name not in self.router.backends\n ):\n backend_url = f\"http://localhost:{port}\"\n self.router.add_backend(\n actual_name,\n backend_url,\n {\n \"port\": port,\n \"gpu_ids\": model_entry.gpu_ids,\n },\n )\n logger.debug(\n f\"Model on port {port} verified as available\"\n )\n else:\n # Model not responding properly\n if model_entry.status == RegistrationStatus.AVAILABLE:\n # Was available, now failing\n model_entry.mark_error(f\"HTTP {response.status_code}\")\n newly_failed.append(model_entry.display_name)\n # Remove from router if present\n if model_entry.actual_name in self.router.backends:\n self.router.remove_backend(model_entry.actual_name)\n else:\n pending_count += 1\n\n except Exception as e:\n # Model not accessible\n if model_entry.status == RegistrationStatus.AVAILABLE:\n # Was available, now failing\n model_entry.mark_error(\n str(e)[:100]\n ) # Limit error message length\n newly_failed.append(model_entry.display_name)\n # Remove from router if present\n if (\n model_entry.actual_name\n and model_entry.actual_name in self.router.backends\n ):\n self.router.remove_backend(model_entry.actual_name)\n logger.warning(\n f\"Model on port {port} no longer accessible: {e}\"\n )\n elif model_entry.status == RegistrationStatus.PENDING:\n pending_count += 1\n logger.debug(f\"Model on port {port} still not ready: {e}\")\n\n summary = {\n \"registered\": len(newly_registered),\n \"already_available\": len(already_available),\n \"failed\": len(newly_failed),\n \"pending\": pending_count,\n \"removed\": removed_count,\n \"total\": len(all_models),\n }\n\n return {\n \"status\": \"success\",\n \"summary\": summary,\n \"details\": {\n \"newly_registered\": newly_registered,\n \"already_available\": already_available,\n \"newly_failed\": newly_failed,\n },\n }\n\n if self.config.enable_metrics:\n\n @self.app.get(\"/metrics\")\n async def metrics():\n \"\"\"Prometheus-compatible metrics endpoint.\"\"\"\n metrics_text = []\n metrics_text.append(\n \"# HELP proxy_requests_total Total requests to proxy\"\n )\n metrics_text.append(\"# TYPE proxy_requests_total counter\")\n metrics_text.append(f\"proxy_requests_total {self.total_requests}\")\n\n metrics_text.append(\"# HELP model_requests_total Requests per model\")\n metrics_text.append(\"# TYPE model_requests_total counter\")\n for model, count in self.model_requests.items():\n metrics_text.append(\n f'model_requests_total{{model=\"{model}\"}} {count}'\n )\n\n uptime = (datetime.now() - self.start_time).total_seconds()\n metrics_text.append(\n \"# HELP proxy_uptime_seconds Proxy uptime in seconds\"\n )\n metrics_text.append(\"# TYPE proxy_uptime_seconds gauge\")\n metrics_text.append(f\"proxy_uptime_seconds {uptime}\")\n\n return \"\\n\".join(metrics_text)\n\n async def _forward_request(self, request: Request, endpoint: str):\n \"\"\"\n Forward a request to the appropriate vLLM backend.\n\n Args:\n request: Incoming FastAPI request\n endpoint: Target endpoint path\n\n Returns:\n Response from the backend server\n \"\"\"\n try:\n # Parse request body\n body = await request.body()\n json_body = json.loads(body) if body else {}\n\n # Extract model from request\n model_name = json_body.get(\"model\")\n if not model_name:\n raise HTTPException(\n status_code=400, detail=\"Missing 'model' field in request\"\n )\n\n # Get backend URL for this model\n backend_url = self.router.route_request(model_name)\n if not backend_url:\n raise HTTPException(\n status_code=404, detail=f\"Model '{model_name}' not found\"\n )\n\n # Update request counters\n self.total_requests += 1\n self.model_requests[model_name] = self.model_requests.get(model_name, 0) + 1\n\n # Check if streaming is requested\n stream = json_body.get(\"stream\", False)\n\n # Forward the request\n target_url = f\"{backend_url}{endpoint}\"\n headers = dict(request.headers)\n headers.pop(\"host\", None) # Remove host header\n\n if stream:\n # Handle streaming response\n return StreamingResponse(\n self._stream_response(target_url, headers, body),\n media_type=\"text/event-stream\",\n )\n else:\n # Handle regular response\n response = await self.client.post(\n target_url, headers=headers, content=body\n )\n\n if response.status_code != 200:\n raise HTTPException(\n status_code=response.status_code, detail=response.text\n )\n\n return JSONResponse(\n content=response.json(), status_code=response.status_code\n )\n\n except HTTPException:\n raise\n except Exception as e:\n logger.error(f\"Error forwarding request: {e}\")\n raise HTTPException(status_code=500, detail=str(e))\n\n async def _stream_response(\n self, url: str, headers: Dict, body: bytes\n ) -> AsyncGenerator[bytes, None]:\n \"\"\"\n Stream response from backend server.\n\n Args:\n url: Target URL\n headers: Request headers\n body: Request body\n\n Yields:\n Chunks of response data\n \"\"\"\n try:\n async with self.client.stream(\n \"POST\", url, headers=headers, content=body\n ) as response:\n async for chunk in response.aiter_bytes():\n yield chunk\n except Exception as e:\n logger.error(f\"Error streaming response: {e}\")\n yield f'data: {{\"error\": \"{str(e)}\"}}\\n\\n'.encode()\n\n async def _check_backend_health(self, port: int) -> str:\n \"\"\"\n Check health of a backend server.\n\n Args:\n port: Backend server port\n\n Returns:\n Status string: \"running\", \"error\", or \"unknown\"\n \"\"\"\n try:\n response = await self.client.get(\n f\"http://localhost:{port}/health\", timeout=5.0\n )\n return \"running\" if response.status_code == 200 else \"error\"\n except Exception:\n return \"unknown\"\n\n def run(self):\n \"\"\"Run the proxy server.\"\"\"\n import uvicorn\n\n logger.info(f\"Starting proxy server on {self.config.host}:{self.config.port}\")\n\n uvicorn.run(\n self.app, host=self.config.host, port=self.config.port, log_level=\"info\"\n )\n\n async def shutdown(self):\n \"\"\"Cleanup resources on shutdown.\"\"\"\n await self.client.aclose()\n\n\n# Source: src/vllm_cli/proxy/registry.py\nclass ModelState(Enum):\n \"\"\"Model state enumeration.\"\"\"\n\n RUNNING = \"running\"\n SLEEPING = \"sleeping\"\n STOPPED = \"stopped\"\n STARTING = \"starting\"", "n_imports_parsed": 14, "n_files_resolved": 4, "n_chars_extracted": 25670}, "tests/test_ollama_integration_fixed.py::148": {"resolved_imports": ["src/vllm_cli/models/cache.py", "src/vllm_cli/models/manager.py"], "used_names": ["ModelCache"], "enclosing_function": "test_cache_stats_tracking", "extracted_code": "# Source: src/vllm_cli/models/cache.py\nclass ModelCache:\n \"\"\"\n Cache for model discovery results.\n\n Provides time-based caching of model listings to avoid expensive\n directory scanning operations when model data is accessed frequently.\n \"\"\"\n\n def __init__(self, ttl_seconds: float = 30.0):\n \"\"\"\n Initialize model cache.\n\n Args:\n ttl_seconds: Time-to-live for cached data in seconds\n \"\"\"\n self.ttl_seconds = ttl_seconds\n self._cache: Optional[Tuple[float, List[Dict[str, Any]]]] = None\n self._stats = {\"hits\": 0, \"misses\": 0, \"updates\": 0}\n\n def get_cached_models(self) -> Optional[List[Dict[str, Any]]]:\n \"\"\"\n Get cached model list if still valid.\n\n Returns:\n List of cached models if cache is valid, None if expired or empty\n \"\"\"\n if self._cache is None:\n self._stats[\"misses\"] += 1\n return None\n\n cache_time, cached_data = self._cache\n\n # Check if cache is still valid\n if time.time() - cache_time < self.ttl_seconds:\n self._stats[\"hits\"] += 1\n logger.debug(f\"Cache hit: returning {len(cached_data)} cached models\")\n return cached_data.copy() # Return copy to prevent modification\n else:\n # Cache expired\n self._stats[\"misses\"] += 1\n logger.debug(\"Cache expired\")\n self._cache = None\n return None\n\n def cache_models(self, models: List[Dict[str, Any]]) -> None:\n \"\"\"\n Cache a list of models.\n\n Args:\n models: List of model dictionaries to cache\n \"\"\"\n self._cache = (time.time(), models.copy())\n self._stats[\"updates\"] += 1\n logger.debug(f\"Cached {len(models)} models\")\n\n def clear_cache(self) -> None:\n \"\"\"Clear the model cache.\"\"\"\n self._cache = None\n # Increment misses to reflect that the next access will be a miss\n self._stats[\"misses\"] += 1\n logger.debug(\"Model cache cleared\")\n\n def is_cached(self) -> bool:\n \"\"\"\n Check if there is valid cached data.\n\n Returns:\n True if cache contains valid data, False otherwise\n \"\"\"\n if self._cache is None:\n return False\n\n cache_time, _ = self._cache\n return time.time() - cache_time < self.ttl_seconds\n\n def get_cache_age(self) -> Optional[float]:\n \"\"\"\n Get the age of cached data in seconds.\n\n Returns:\n Age in seconds if cache exists, None if no cache\n \"\"\"\n if self._cache is None:\n return None\n\n cache_time, _ = self._cache\n return time.time() - cache_time\n\n def get_cache_stats(self) -> Dict[str, Any]:\n \"\"\"\n Get cache statistics.\n\n Returns:\n Dictionary with cache performance statistics\n \"\"\"\n total_requests = self._stats[\"hits\"] + self._stats[\"misses\"]\n hit_rate = (\n (self._stats[\"hits\"] / total_requests * 100) if total_requests > 0 else 0\n )\n\n stats = {\n \"hits\": self._stats[\"hits\"],\n \"misses\": self._stats[\"misses\"],\n \"updates\": self._stats[\"updates\"],\n \"total_requests\": total_requests,\n \"hit_rate_percent\": round(hit_rate, 2),\n \"is_cached\": self.is_cached(),\n \"cache_age_seconds\": self.get_cache_age(),\n \"ttl_seconds\": self.ttl_seconds,\n }\n\n if self._cache:\n _, cached_data = self._cache\n stats[\"cached_models_count\"] = len(cached_data)\n else:\n stats[\"cached_models_count\"] = 0\n\n return stats\n\n def get_stats(self) -> Dict[str, Any]:\n \"\"\"\n Alias for get_cache_stats() for backward compatibility.\n\n Returns:\n Dictionary with cache performance statistics\n \"\"\"\n return self.get_cache_stats()\n\n def reset_stats(self) -> None:\n \"\"\"Reset cache statistics.\"\"\"\n self._stats = {\"hits\": 0, \"misses\": 0, \"updates\": 0}\n logger.debug(\"Cache statistics reset\")\n\n def set_ttl(self, ttl_seconds: float) -> None:\n \"\"\"\n Set new TTL for cache.\n\n Args:\n ttl_seconds: New time-to-live in seconds\n \"\"\"\n old_ttl = self.ttl_seconds\n self.ttl_seconds = ttl_seconds\n logger.debug(f\"Cache TTL changed from {old_ttl}s to {ttl_seconds}s\")\n\n def get_cached_model_count(self) -> int:\n \"\"\"\n Get the number of models currently cached.\n\n Returns:\n Number of cached models, 0 if no cache\n \"\"\"\n if self._cache is None:\n return 0\n\n _, cached_data = self._cache\n return len(cached_data)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 4761}, "tests/proxy/test_models.py::44": {"resolved_imports": ["src/vllm_cli/proxy/models.py"], "used_names": ["ModelConfig"], "enclosing_function": "test_model_config_defaults", "extracted_code": "# Source: src/vllm_cli/proxy/models.py\nclass ModelConfig(BaseModel):\n \"\"\"Configuration for a single model in the proxy.\"\"\"\n\n name: str = Field(..., description=\"Model identifier for API requests\")\n model_path: str = Field(..., description=\"Path or HuggingFace model ID\")\n gpu_ids: List[int] = Field(default_factory=list, description=\"GPU IDs to use\")\n port: int = Field(..., description=\"Port for the vLLM server\")\n profile: Optional[str] = Field(None, description=\"vLLM CLI profile to use\")\n config_overrides: Dict[str, Any] = Field(\n default_factory=dict, description=\"Additional vLLM configuration\"\n )\n enabled: bool = Field(True, description=\"Whether model is enabled\")\n loading_priority: Optional[int] = Field(\n None,\n description=\"Loading priority (lower numbers load first). \"\n \"Models with same priority load in parallel. \"\n \"Models with None priority load after all prioritized models.\",\n )", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 967}, "tests/proxy/test_server.py::169": {"resolved_imports": ["src/vllm_cli/proxy/models.py", "src/vllm_cli/proxy/registry.py", "src/vllm_cli/proxy/server.py"], "used_names": [], "enclosing_function": "test_proxy_status_endpoint", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_ollama_support.py::62": {"resolved_imports": ["src/vllm_cli/models/discovery.py", "src/vllm_cli/models/manager.py"], "used_names": ["patch"], "enclosing_function": "test_scan_includes_ollama_models", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/proxy/test_router.py::66": {"resolved_imports": ["src/vllm_cli/proxy/router.py"], "used_names": [], "enclosing_function": "test_route_request_no_match", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_cli_parser.py::162": {"resolved_imports": ["src/vllm_cli/cli/parser.py"], "used_names": ["create_parser"], "enclosing_function": "test_serve_with_shortcut", "extracted_code": "# Source: src/vllm_cli/cli/parser.py\ndef create_parser() -> argparse.ArgumentParser:\n \"\"\"\n Create the main argument parser for vLLM CLI.\n\n Sets up the main parser with all subcommands and their arguments.\n\n Returns:\n Configured ArgumentParser instance\n \"\"\"\n parser = argparse.ArgumentParser(\n prog=\"vllm-cli\",\n description=\"vLLM CLI - Convenient LLM serving tool\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"Examples:\n vllm-cli # Interactive mode\n vllm-cli serve MODEL --profile standard # Serve with profile\n vllm-cli serve MODEL --quantization awq # Serve with AWQ quantization\n vllm-cli serve MODEL --extra-args \"--seed 42\" # With custom vLLM args\n vllm-cli info # System information\n vllm-cli models # List available models\n vllm-cli status # Show active servers\"\"\",\n )\n\n # Global options\n from .. import __version__\n\n parser.add_argument(\n \"--version\", action=\"version\", version=f\"vLLM CLI {__version__}\"\n )\n\n # Create subparsers for commands\n subparsers = parser.add_subparsers(\n dest=\"command\",\n help=\"Available commands\",\n metavar=\"{serve,proxy,info,models,shortcuts,status,stop,dirs}\",\n )\n\n # Add individual command parsers\n _add_serve_parser(subparsers)\n _add_proxy_parser(subparsers)\n _add_info_parser(subparsers)\n _add_models_parser(subparsers)\n _add_shortcuts_parser(subparsers)\n _add_status_parser(subparsers)\n _add_stop_parser(subparsers)\n _add_dirs_parser(subparsers)\n\n return parser", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1705}, "tests/proxy/test_integration.py::280": {"resolved_imports": ["src/vllm_cli/proxy/config.py", "src/vllm_cli/proxy/manager.py", "src/vllm_cli/proxy/models.py", "src/vllm_cli/proxy/server_process.py"], "used_names": ["MagicMock", "ModelConfig", "ProxyConfig", "ProxyManager", "patch"], "enclosing_function": "test_gpu_assignment_integration", "extracted_code": "# Source: src/vllm_cli/proxy/manager.py\nclass ProxyManager:\n \"\"\"\n Manages the lifecycle of multiple vLLM servers and the proxy server.\n \"\"\"\n\n def __init__(self, config: Optional[ProxyConfig] = None):\n \"\"\"\n Initialize the proxy manager.\n\n Args:\n config: Proxy configuration (uses defaults if not provided)\n \"\"\"\n self.proxy_config = config or ProxyConfig()\n self.proxy_process: Optional[ProxyServerProcess] = None\n self.vllm_servers: Dict[str, VLLMServer] = {}\n self.config_manager = ConfigManager()\n\n def _proxy_api_request(\n self,\n method: str,\n endpoint: str,\n json_data: Optional[Dict] = None,\n timeout: float = 5.0,\n ) -> Optional[Any]:\n \"\"\"\n Helper method for making HTTP requests to the proxy API.\n\n Args:\n method: HTTP method (POST, DELETE, GET)\n endpoint: API endpoint path\n json_data: Optional JSON data for request body\n timeout: Request timeout in seconds\n\n Returns:\n Response object if successful, None if failed\n \"\"\"\n try:\n import httpx\n\n url = f\"http://localhost:{self.proxy_config.port}{endpoint}\"\n with httpx.Client() as client:\n if method == \"POST\":\n response = client.post(url, json=json_data, timeout=timeout)\n elif method == \"DELETE\":\n response = client.delete(url, timeout=timeout)\n elif method == \"GET\":\n response = client.get(url, timeout=timeout)\n else:\n logger.error(f\"Unsupported HTTP method: {method}\")\n return None\n\n if response.status_code == 200:\n return response\n else:\n logger.warning(\n f\"API request failed: {method} {endpoint} - \"\n f\"{response.status_code}: {response.text}\"\n )\n return None\n\n except Exception as e:\n logger.warning(f\"API request error: {method} {endpoint} - {e}\")\n return None\n\n def start_proxy(self) -> bool:\n \"\"\"\n Start the proxy server.\n\n Returns:\n True if proxy started successfully\n \"\"\"\n try:\n # Create proxy server process instance\n self.proxy_process = ProxyServerProcess(self.proxy_config)\n\n # Start proxy as a subprocess\n if not self.proxy_process.start():\n logger.error(\"Failed to start proxy server process\")\n return False\n\n # Give it a moment to fully initialize\n time.sleep(2)\n\n # Register all running models with the proxy\n # Note: We'll need to update this to work with subprocess\n # For now, models will register when they start\n\n logger.info(\n f\"Proxy server started on \"\n f\"{self.proxy_config.host}:{self.proxy_config.port}\"\n )\n return True\n\n except Exception as e:\n logger.error(f\"Failed to start proxy server: {e}\")\n return False\n\n def stop_proxy(self):\n \"\"\"Stop the proxy server and all vLLM instances.\"\"\"\n logger.info(\"Stopping proxy server and all model servers...\")\n\n # Stop all vLLM servers\n for model_name in list(self.vllm_servers.keys()):\n self.stop_model(model_name)\n\n # Stop proxy server process\n if self.proxy_process:\n self.proxy_process.stop()\n self.proxy_process = None\n logger.info(\"Proxy server stopped\")\n\n def start_model(self, model_config: ModelConfig) -> bool:\n \"\"\"\n Start a vLLM server for a specific model.\n\n Args:\n model_config: Configuration for the model\n\n Returns:\n True if server started successfully\n \"\"\"\n try:\n # Check if model is already running\n if model_config.name in self.vllm_servers:\n logger.warning(f\"Model '{model_config.name}' is already running\")\n return False\n\n # Build vLLM server configuration\n vllm_config = self._build_vllm_config(model_config)\n\n # Pre-register with proxy if it's running\n if self.proxy_process and self.proxy_process.is_running():\n pre_register_data = {\n \"port\": model_config.port,\n \"gpu_ids\": model_config.gpu_ids,\n \"config_name\": model_config.name,\n }\n\n response = self._proxy_api_request(\n \"POST\", \"/proxy/pre_register\", pre_register_data\n )\n if response:\n logger.info(\n f\"Pre-registered model '{model_config.name}' with proxy\"\n )\n else:\n logger.warning(\n f\"Failed to pre-register model '{model_config.name}' with proxy\"\n )\n\n # Create and start vLLM server\n server = VLLMServer(vllm_config)\n if not server.start():\n logger.error(f\"Failed to start vLLM server for '{model_config.name}'\")\n return False\n\n # Store server reference\n self.vllm_servers[model_config.name] = server\n\n logger.info(\n f\"Started vLLM server process for '{model_config.name}' \"\n f\"on port {model_config.port} using GPUs {model_config.gpu_ids}\"\n )\n\n # Note: Registration with proxy will happen after startup completes\n # Registration happens during wait_and_register_model()\n\n return True\n\n except Exception as e:\n logger.error(f\"Failed to start model '{model_config.name}': {e}\")\n return False\n\n def wait_and_register_model(self, model_config: ModelConfig) -> bool:\n \"\"\"\n Wait for a model to complete startup and trigger proxy refresh.\n\n Args:\n model_config: Configuration for the model\n\n Returns:\n True if model started and registered successfully\n \"\"\"\n if model_config.name not in self.vllm_servers:\n logger.error(f\"Model '{model_config.name}' not found in servers\")\n return False\n\n server = self.vllm_servers[model_config.name]\n\n # Wait for server to complete startup\n if not server.wait_for_startup():\n logger.error(f\"Server '{model_config.name}' failed to complete startup\")\n # Clean up the failed server\n server.stop()\n del self.vllm_servers[model_config.name]\n return False\n\n # Trigger proxy refresh to verify and activate the model\n if self.proxy_process and self.proxy_process.is_running():\n # Call refresh to verify the pre-registered model\n response = self._proxy_api_request(\n \"POST\", \"/proxy/refresh_models\", timeout=10.0\n )\n if response:\n try:\n result = response.json()\n summary = result.get(\"summary\", {})\n if summary.get(\"registered\", 0) > 0:\n logger.info(\n f\"Model '{model_config.name}' successfully activated \"\n f\"on port {model_config.port}\"\n )\n return True\n else:\n logger.warning(\n f\"Model '{model_config.name}' started but \"\n f\"not activated in proxy\"\n )\n return True # Model is running, just not registered\n except Exception as e:\n logger.error(f\"Failed to parse refresh response: {e}\")\n return True # Model is running\n else:\n logger.warning(\n f\"Failed to refresh proxy after starting \"\n f\"model '{model_config.name}'\"\n )\n return True # Model is running even if refresh failed\n\n logger.info(f\"Model '{model_config.name}' is ready\")\n return True\n\n def refresh_model_registrations(self) -> Dict[str, Any]:\n \"\"\"\n Refresh model registrations with the proxy.\n\n Calls the proxy's refresh endpoint to verify all models in the registry.\n\n Returns:\n Dictionary with registration results\n \"\"\"\n if not self.proxy_process or not self.proxy_process.is_running():\n logger.warning(\"Proxy is not running, cannot refresh registrations\")\n return {\"status\": \"error\", \"message\": \"Proxy server is not running\"}\n\n # Call the refresh endpoint\n response = self._proxy_api_request(\n \"POST\", \"/proxy/refresh_models\", timeout=10.0\n )\n\n if response:\n try:\n result = response.json()\n summary = result.get(\"summary\", {})\n logger.info(\n f\"Model registration refresh completed: \"\n f\"{summary.get('registered', 0)} newly registered, \"\n f\"{summary.get('failed', 0)} newly failed, \"\n f\"{summary.get('already_available', 0)} already available, \"\n f\"{summary.get('removed', 0)} removed\"\n )\n return result\n except Exception as e:\n logger.error(f\"Failed to parse refresh response: {e}\")\n return {\"status\": \"error\", \"message\": f\"Failed to parse response: {e}\"}\n else:\n logger.error(\"Failed to refresh model registrations\")\n return {\n \"status\": \"error\",\n \"message\": \"Failed to connect to proxy refresh endpoint\",\n }\n\n def get_proxy_registry_status(self) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get full model registry status from proxy.\n\n Returns:\n Dictionary containing proxy status and all registered models,\n or None if proxy is not running\n \"\"\"\n if not self.proxy_process or not self.proxy_process.is_running():\n logger.warning(\"Proxy is not running, cannot get registry status\")\n return None\n\n response = self._proxy_api_request(\"GET\", \"/proxy/registry\")\n if response:\n try:\n return response.json()\n except Exception as e:\n logger.error(f\"Failed to parse proxy status response: {e}\")\n return None\n return None\n\n def sleep_model(self, model_name: str, level: int = 1) -> bool:\n \"\"\"\n Put a model to sleep, freeing GPU memory but keeping the port.\n Runs asynchronously and returns immediately.\n\n Args:\n model_name: Name of the model to sleep\n level: Sleep level (1=offload weights, 2=discard weights)\n\n Returns:\n True if sleep request was initiated successfully\n \"\"\"\n if model_name not in self.vllm_servers:\n logger.warning(f\"Model '{model_name}' is not running\")\n return False\n\n server = self.vllm_servers[model_name]\n port = server.port\n\n try:\n import threading\n\n import httpx\n\n def sleep_thread():\n try:\n # Use 10 minute timeout for very slow operations\n client = httpx.Client(timeout=600.0)\n logger.info(\n f\"Sending sleep request to model '{model_name}' \"\n f\"(level {level})...\"\n )\n response = client.post(\n f\"http://localhost:{port}/sleep?level={level}\"\n )\n client.close()\n\n if response.status_code == 200:\n logger.info(\n f\"Model '{model_name}' successfully put to sleep \"\n f\"(level {level})\"\n )\n\n # Update proxy registry state\n if self.proxy_process and self.proxy_process.is_running():\n state_data = {\n \"port\": port,\n \"state\": \"sleeping\",\n \"sleep_level\": level,\n }\n self._proxy_api_request(\"POST\", \"/proxy/state\", state_data)\n else:\n logger.error(\n f\"Failed to sleep model '{model_name}': \"\n f\"HTTP {response.status_code}\"\n )\n\n except Exception as e:\n logger.error(f\"Failed to sleep model '{model_name}': {e}\")\n\n # Start in background thread\n thread = threading.Thread(target=sleep_thread, daemon=True)\n thread.start()\n logger.info(f\"Sleep operation initiated for '{model_name}'\")\n return True\n\n except Exception as e:\n logger.error(f\"Failed to initiate sleep for '{model_name}': {e}\")\n return False\n\n def wake_model(self, model_name: str) -> bool:\n \"\"\"\n Wake up a sleeping model.\n Runs asynchronously and returns immediately.\n\n Args:\n model_name: Name of the model to wake\n\n Returns:\n True if wake request was initiated successfully\n \"\"\"\n if model_name not in self.vllm_servers:\n logger.warning(f\"Model '{model_name}' is not running\")\n return False\n\n server = self.vllm_servers[model_name]\n port = server.port\n\n try:\n import threading\n\n import httpx\n\n def wake_thread():\n try:\n # Use 10 minute timeout for very slow operations\n client = httpx.Client(timeout=600.0)\n logger.info(f\"Sending wake-up request to model '{model_name}'...\")\n response = client.post(f\"http://localhost:{port}/wake_up\")\n client.close()\n\n # Accept both 200 (OK) and 202 (Accepted) as success\n if response.status_code in [200, 202]:\n logger.info(f\"Model '{model_name}' successfully woken up\")\n\n # Update proxy registry state\n if self.proxy_process and self.proxy_process.is_running():\n state_data = {\n \"port\": port,\n \"state\": \"running\",\n \"sleep_level\": 0,\n }\n self._proxy_api_request(\"POST\", \"/proxy/state\", state_data)\n else:\n logger.error(\n f\"Failed to wake model '{model_name}': \"\n f\"HTTP {response.status_code}\"\n )\n\n except Exception as e:\n logger.error(f\"Failed to wake model '{model_name}': {e}\")\n\n # Start in background thread\n thread = threading.Thread(target=wake_thread, daemon=True)\n thread.start()\n logger.info(f\"Wake operation initiated for '{model_name}'\")\n return True\n\n except Exception as e:\n logger.error(f\"Failed to initiate wake for '{model_name}': {e}\")\n return False\n\n def is_sleeping(self, model_name: str) -> bool:\n \"\"\"\n Check if a model is sleeping.\n\n Args:\n model_name: Name of the model to check\n\n Returns:\n True if model is sleeping\n \"\"\"\n if model_name not in self.vllm_servers:\n return False\n\n server = self.vllm_servers[model_name]\n port = server.port\n\n try:\n import httpx\n\n client = httpx.Client(timeout=5.0)\n response = client.get(f\"http://localhost:{port}/is_sleeping\")\n client.close()\n\n if response.status_code == 200:\n data = response.json()\n return data.get(\"is_sleeping\", False)\n except Exception:\n pass\n\n return False\n\n def stop_model(self, model_name: str) -> bool:\n \"\"\"\n Stop a vLLM server for a specific model.\n\n Args:\n model_name: Name of the model to stop\n\n Returns:\n True if server stopped successfully\n \"\"\"\n if model_name not in self.vllm_servers:\n logger.warning(f\"Model '{model_name}' is not running\")\n return False\n\n try:\n # Get the port before stopping\n server = self.vllm_servers[model_name]\n port = server.port\n\n # Stop the vLLM server\n server.stop()\n\n # Remove from tracking\n del self.vllm_servers[model_name]\n\n # Unregister from proxy if it's running\n if self.proxy_process and self.proxy_process.is_running():\n # Use the new registry endpoint with port\n if self._proxy_api_request(\"DELETE\", f\"/proxy/models/{port}\"):\n logger.debug(f\"Unregistered model on port {port} from proxy\")\n\n logger.info(f\"Stopped vLLM server for '{model_name}'\")\n return True\n\n except Exception as e:\n logger.error(f\"Failed to stop model '{model_name}': {e}\")\n return False\n\n def unregister_model_from_proxy(self, port: int) -> bool:\n \"\"\"\n Unregister a model from the proxy registry by port.\n This is useful for cleaning up stopped models.\n\n Args:\n port: Port number of the model to unregister\n\n Returns:\n True if successfully unregistered or proxy not running\n \"\"\"\n if self.proxy_process and self.proxy_process.is_running():\n if self._proxy_api_request(\"DELETE\", f\"/proxy/models/{port}\"):\n logger.debug(f\"Unregistered model on port {port} from proxy\")\n return True\n return False\n return True # If proxy not running, consider it success\n\n def start_all_models_no_wait(self) -> int:\n \"\"\"\n Start all model processes without waiting for startup completion.\n\n This method starts all model servers concurrently and returns immediately,\n allowing the caller to monitor startup progress in real-time.\n\n Returns:\n Number of model processes successfully launched\n \"\"\"\n started_count = 0\n for model_config in self.proxy_config.models:\n if model_config.enabled:\n if self.start_model(model_config):\n started_count += 1\n # Small delay to avoid resource conflicts\n time.sleep(0.5)\n\n return started_count\n\n def start_models_with_priorities(self):\n \"\"\"\n Start models sequentially based on loading_priority.\n\n Models are grouped by priority (lower numbers first). Models within\n the same priority group start in parallel. This is a generator that\n yields each priority group after starting its models, allowing the\n UI layer to monitor startup progress with live feedback.\n\n This is useful for GPU-shared deployments where models with low\n gpu-memory-utilization should load first to claim KV cache space.\n\n Yields:\n Dictionary for each priority group:\n - priority: Priority number (or float('inf') for None)\n - priority_label: Human-readable priority label\n - models: List of ModelConfig instances in this group\n - started_models: List of ModelConfig instances that started successfully\n - failed_models: List of model names that failed to start\n - group_index: Current group number (1-indexed)\n - total_groups: Total number of priority groups\n - total_models: Total number of models across all groups\n \"\"\"\n from collections import defaultdict\n\n # Group models by loading_priority\n priority_groups = defaultdict(list)\n for model_config in self.proxy_config.models:\n if model_config.enabled:\n priority = model_config.loading_priority\n # Use a large number for None priority (load last)\n effective_priority = priority if priority is not None else float(\"inf\")\n priority_groups[effective_priority].append(model_config)\n\n # Sort priority groups (ascending order)\n sorted_priorities = sorted(priority_groups.keys())\n\n total_models = sum(len(models) for models in priority_groups.values())\n\n logger.info(\n f\"Starting {total_models} models in {len(sorted_priorities)} \"\n f\"priority group(s)\"\n )\n\n # Process each priority group sequentially\n for priority_idx, priority in enumerate(sorted_priorities, 1):\n models = priority_groups[priority]\n priority_label = (\n f\"Priority {int(priority)}\"\n if priority != float(\"inf\")\n else \"No Priority (Parallel)\"\n )\n\n logger.info(\n f\"Starting priority group {priority_idx}/{len(sorted_priorities)}: \"\n f\"{priority_label} ({len(models)} model(s))\"\n )\n\n # Start all models in this priority group (non-blocking)\n group_started = []\n group_failed = []\n\n for model_config in models:\n if self.start_model(model_config):\n group_started.append(model_config)\n logger.info(\n f\"Started {model_config.name} (port {model_config.port})\"\n )\n # Small delay to avoid resource conflicts\n time.sleep(0.5)\n else:\n group_failed.append(model_config.name)\n logger.error(f\"Failed to start {model_config.name}\")\n\n # Yield this group for UI monitoring (non-blocking)\n yield {\n \"priority\": priority,\n \"priority_label\": priority_label,\n \"models\": models,\n \"started_models\": group_started,\n \"failed_models\": group_failed,\n \"group_index\": priority_idx,\n \"total_groups\": len(sorted_priorities),\n \"total_models\": total_models,\n }\n\n # Control returns here after UI finishes monitoring this group\n\n def _build_vllm_config(self, model_config: ModelConfig) -> Dict[str, Any]:\n \"\"\"\n Build vLLM server configuration from model configuration.\n\n Args:\n model_config: Model configuration\n\n Returns:\n vLLM server configuration dictionary\n \"\"\"\n # Start with profile configuration if specified\n config = {}\n if model_config.profile:\n profile = self.config_manager.get_profile(model_config.profile)\n if profile:\n config = profile.get(\"config\", {}).copy()\n\n # Set model, port, and host\n config[\"model\"] = model_config.model_path\n config[\"port\"] = model_config.port\n config[\"host\"] = self.proxy_config.host # Use host from proxy configuration\n\n # Enable sleep mode for better resource management\n config[\"enable_sleep_mode\"] = True\n\n # Handle GPU assignment\n if model_config.gpu_ids:\n # Set CUDA_VISIBLE_DEVICES via device field\n config[\"device\"] = \",\".join(str(gpu) for gpu in model_config.gpu_ids)\n\n num_gpus = len(model_config.gpu_ids)\n\n # For single GPU assignment, override any parallel settings from profile\n if num_gpus == 1:\n # Remove parallel configuration that conflicts with single GPU\n conflicting_settings = [\n \"tensor_parallel_size\",\n \"pipeline_parallel_size\",\n \"distributed_executor_backend\",\n ]\n\n removed_settings = []\n for setting in conflicting_settings:\n if setting in config:\n removed_settings.append(f\"{setting}={config[setting]}\")\n del config[setting]\n\n # Disable expert parallelism for single GPU\n if config.get(\"enable_expert_parallel\"):\n removed_settings.append(\"enable_expert_parallel=True\")\n config[\"enable_expert_parallel\"] = False\n\n if removed_settings:\n logger.warning(\n f\"Model '{model_config.name}' assigned single GPU. \"\n f\"Overriding profile settings: {', '.join(removed_settings)}\"\n )\n\n elif num_gpus > 1:\n # For multi-GPU, set tensor_parallel_size if not already set\n if \"tensor_parallel_size\" not in config:\n config[\"tensor_parallel_size\"] = num_gpus\n elif config[\"tensor_parallel_size\"] > num_gpus:\n # Adjust if profile expects more GPUs than assigned\n logger.warning(\n f\"Model '{model_config.name}': Adjusting tensor_parallel_size \"\n f\"from {config['tensor_parallel_size']} to {num_gpus} \"\n f\"(assigned GPUs)\"\n )\n config[\"tensor_parallel_size\"] = num_gpus\n\n # Apply any config overrides\n config.update(model_config.config_overrides)\n\n return config\n\n def get_status(self) -> Dict[str, Any]:\n \"\"\"\n Get status of proxy and all model servers.\n\n Returns:\n Status dictionary\n \"\"\"\n status = {\n \"proxy_running\": self.proxy_process and self.proxy_process.is_running(),\n \"proxy_host\": self.proxy_config.host,\n \"proxy_port\": self.proxy_config.port,\n \"models\": [],\n }\n\n for model_name, server in self.vllm_servers.items():\n model_status = {\n \"name\": model_name,\n \"running\": server.is_running(),\n \"port\": server.port,\n \"uptime\": None,\n }\n\n if server.is_running() and server.start_time:\n uptime = time.time() - server.start_time.timestamp()\n model_status[\"uptime\"] = uptime\n\n status[\"models\"].append(model_status)\n\n return status\n\n def reload_model(self, model_name: str) -> bool:\n \"\"\"\n Reload a model (stop and start again).\n\n Args:\n model_name: Name of the model to reload\n\n Returns:\n True if reload successful\n \"\"\"\n # Find the model config\n model_config = None\n for config in self.proxy_config.models:\n if config.name == model_name:\n model_config = config\n break\n\n if not model_config:\n logger.error(f\"Model '{model_name}' not found in configuration\")\n return False\n\n # Stop if running\n if model_name in self.vllm_servers:\n self.stop_model(model_name)\n time.sleep(2) # Wait before restarting\n\n # Start the model\n if not self.start_model(model_config):\n return False\n\n # Wait for startup and register\n return self.wait_and_register_model(model_config)\n\n def allocate_gpus_automatically(self) -> List[ModelConfig]:\n \"\"\"\n Automatically allocate GPUs to models based on available resources.\n\n Returns:\n List of model configurations with GPU allocations\n \"\"\"\n from ..system import get_gpu_info\n\n # Get available GPUs\n gpu_info = get_gpu_info()\n if not gpu_info:\n logger.warning(\"No GPUs available for allocation\")\n return []\n\n num_gpus = len(gpu_info)\n models = self.proxy_config.models\n\n # Simple allocation strategy: distribute GPUs evenly\n allocated_configs = []\n\n if len(models) <= num_gpus:\n # Each model gets at least one GPU\n gpus_per_model = num_gpus // len(models)\n remaining_gpus = num_gpus % len(models)\n\n gpu_index = 0\n for i, model in enumerate(models):\n num_gpus_for_model = gpus_per_model\n if i < remaining_gpus:\n num_gpus_for_model += 1\n\n model.gpu_ids = list(range(gpu_index, gpu_index + num_gpus_for_model))\n gpu_index += num_gpus_for_model\n\n # Allocate port if not specified\n if not model.port:\n model.port = get_next_available_port(8001 + i)\n\n allocated_configs.append(model)\n else:\n # More models than GPUs - some models won't be allocated\n logger.warning(\n f\"More models ({len(models)}) than GPUs ({num_gpus}). \"\n f\"Only first {num_gpus} models will be allocated.\"\n )\n for i in range(num_gpus):\n models[i].gpu_ids = [i]\n if not models[i].port:\n models[i].port = get_next_available_port(8001 + i)\n allocated_configs.append(models[i])\n\n return allocated_configs\n\n def _get_model_config_by_name(self, model_name: str) -> Optional[ModelConfig]:\n \"\"\"\n Get model configuration by model name.\n\n Args:\n model_name: Name of the model\n\n Returns:\n ModelConfig if found, None otherwise\n \"\"\"\n for model_config in self.proxy_config.models:\n if model_config.name == model_name:\n return model_config\n return None\n\n @classmethod\n def from_config_file(cls, config_path: Path) -> \"ProxyManager\":\n \"\"\"\n Create ProxyManager from a configuration file.\n\n Args:\n config_path: Path to configuration file (YAML or JSON)\n\n Returns:\n ProxyManager instance\n \"\"\"\n import json\n\n import yaml\n\n with open(config_path, \"r\") as f:\n if config_path.suffix in [\".yaml\", \".yml\"]:\n config_dict = yaml.safe_load(f)\n else:\n config_dict = json.load(f)\n\n # Parse proxy configuration\n proxy_config = ProxyConfig(**config_dict.get(\"proxy\", {}))\n\n # Parse model configurations\n models = []\n for model_dict in config_dict.get(\"models\", []):\n models.append(ModelConfig(**model_dict))\n proxy_config.models = models\n\n return cls(proxy_config)\n\n\n# Source: src/vllm_cli/proxy/models.py\nclass ModelConfig(BaseModel):\n \"\"\"Configuration for a single model in the proxy.\"\"\"\n\n name: str = Field(..., description=\"Model identifier for API requests\")\n model_path: str = Field(..., description=\"Path or HuggingFace model ID\")\n gpu_ids: List[int] = Field(default_factory=list, description=\"GPU IDs to use\")\n port: int = Field(..., description=\"Port for the vLLM server\")\n profile: Optional[str] = Field(None, description=\"vLLM CLI profile to use\")\n config_overrides: Dict[str, Any] = Field(\n default_factory=dict, description=\"Additional vLLM configuration\"\n )\n enabled: bool = Field(True, description=\"Whether model is enabled\")\n loading_priority: Optional[int] = Field(\n None,\n description=\"Loading priority (lower numbers load first). \"\n \"Models with same priority load in parallel. \"\n \"Models with None priority load after all prioritized models.\",\n )\n\nclass ProxyConfig(BaseModel):\n \"\"\"Configuration for the proxy server.\"\"\"\n\n host: str = Field(\"0.0.0.0\", description=\"Proxy server host\") # nosec B104\n port: int = Field(8000, description=\"Proxy server port\")\n models: List[ModelConfig] = Field(\n default_factory=list, description=\"List of models to serve\"\n )\n enable_cors: bool = Field(True, description=\"Enable CORS headers\")\n enable_metrics: bool = Field(True, description=\"Enable metrics endpoint\")\n log_requests: bool = Field(False, description=\"Log all requests\")", "n_imports_parsed": 9, "n_files_resolved": 4, "n_chars_extracted": 32708}, "tests/test_ollama_integration_fixed.py::106": {"resolved_imports": ["src/vllm_cli/models/cache.py", "src/vllm_cli/models/manager.py"], "used_names": ["ModelCache"], "enclosing_function": "test_cache_ttl_bypass_on_refresh", "extracted_code": "# Source: src/vllm_cli/models/cache.py\nclass ModelCache:\n \"\"\"\n Cache for model discovery results.\n\n Provides time-based caching of model listings to avoid expensive\n directory scanning operations when model data is accessed frequently.\n \"\"\"\n\n def __init__(self, ttl_seconds: float = 30.0):\n \"\"\"\n Initialize model cache.\n\n Args:\n ttl_seconds: Time-to-live for cached data in seconds\n \"\"\"\n self.ttl_seconds = ttl_seconds\n self._cache: Optional[Tuple[float, List[Dict[str, Any]]]] = None\n self._stats = {\"hits\": 0, \"misses\": 0, \"updates\": 0}\n\n def get_cached_models(self) -> Optional[List[Dict[str, Any]]]:\n \"\"\"\n Get cached model list if still valid.\n\n Returns:\n List of cached models if cache is valid, None if expired or empty\n \"\"\"\n if self._cache is None:\n self._stats[\"misses\"] += 1\n return None\n\n cache_time, cached_data = self._cache\n\n # Check if cache is still valid\n if time.time() - cache_time < self.ttl_seconds:\n self._stats[\"hits\"] += 1\n logger.debug(f\"Cache hit: returning {len(cached_data)} cached models\")\n return cached_data.copy() # Return copy to prevent modification\n else:\n # Cache expired\n self._stats[\"misses\"] += 1\n logger.debug(\"Cache expired\")\n self._cache = None\n return None\n\n def cache_models(self, models: List[Dict[str, Any]]) -> None:\n \"\"\"\n Cache a list of models.\n\n Args:\n models: List of model dictionaries to cache\n \"\"\"\n self._cache = (time.time(), models.copy())\n self._stats[\"updates\"] += 1\n logger.debug(f\"Cached {len(models)} models\")\n\n def clear_cache(self) -> None:\n \"\"\"Clear the model cache.\"\"\"\n self._cache = None\n # Increment misses to reflect that the next access will be a miss\n self._stats[\"misses\"] += 1\n logger.debug(\"Model cache cleared\")\n\n def is_cached(self) -> bool:\n \"\"\"\n Check if there is valid cached data.\n\n Returns:\n True if cache contains valid data, False otherwise\n \"\"\"\n if self._cache is None:\n return False\n\n cache_time, _ = self._cache\n return time.time() - cache_time < self.ttl_seconds\n\n def get_cache_age(self) -> Optional[float]:\n \"\"\"\n Get the age of cached data in seconds.\n\n Returns:\n Age in seconds if cache exists, None if no cache\n \"\"\"\n if self._cache is None:\n return None\n\n cache_time, _ = self._cache\n return time.time() - cache_time\n\n def get_cache_stats(self) -> Dict[str, Any]:\n \"\"\"\n Get cache statistics.\n\n Returns:\n Dictionary with cache performance statistics\n \"\"\"\n total_requests = self._stats[\"hits\"] + self._stats[\"misses\"]\n hit_rate = (\n (self._stats[\"hits\"] / total_requests * 100) if total_requests > 0 else 0\n )\n\n stats = {\n \"hits\": self._stats[\"hits\"],\n \"misses\": self._stats[\"misses\"],\n \"updates\": self._stats[\"updates\"],\n \"total_requests\": total_requests,\n \"hit_rate_percent\": round(hit_rate, 2),\n \"is_cached\": self.is_cached(),\n \"cache_age_seconds\": self.get_cache_age(),\n \"ttl_seconds\": self.ttl_seconds,\n }\n\n if self._cache:\n _, cached_data = self._cache\n stats[\"cached_models_count\"] = len(cached_data)\n else:\n stats[\"cached_models_count\"] = 0\n\n return stats\n\n def get_stats(self) -> Dict[str, Any]:\n \"\"\"\n Alias for get_cache_stats() for backward compatibility.\n\n Returns:\n Dictionary with cache performance statistics\n \"\"\"\n return self.get_cache_stats()\n\n def reset_stats(self) -> None:\n \"\"\"Reset cache statistics.\"\"\"\n self._stats = {\"hits\": 0, \"misses\": 0, \"updates\": 0}\n logger.debug(\"Cache statistics reset\")\n\n def set_ttl(self, ttl_seconds: float) -> None:\n \"\"\"\n Set new TTL for cache.\n\n Args:\n ttl_seconds: New time-to-live in seconds\n \"\"\"\n old_ttl = self.ttl_seconds\n self.ttl_seconds = ttl_seconds\n logger.debug(f\"Cache TTL changed from {old_ttl}s to {ttl_seconds}s\")\n\n def get_cached_model_count(self) -> int:\n \"\"\"\n Get the number of models currently cached.\n\n Returns:\n Number of cached models, 0 if no cache\n \"\"\"\n if self._cache is None:\n return 0\n\n _, cached_data = self._cache\n return len(cached_data)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 4761}, "tests/proxy/test_models.py::188": {"resolved_imports": ["src/vllm_cli/proxy/models.py"], "used_names": ["ModelStatus"], "enclosing_function": "test_model_status_creation", "extracted_code": "# Source: src/vllm_cli/proxy/models.py\nclass ModelStatus(BaseModel):\n \"\"\"Status information for a model.\"\"\"\n\n name: str\n model_path: str\n port: int\n gpu_ids: List[int]\n status: str # \"running\", \"starting\", \"stopped\", \"error\"\n registration_status: Optional[str] = None # \"pending\", \"available\", \"error\"\n uptime: Optional[float] = None\n error_message: Optional[str] = None\n request_count: int = 0\n last_request_time: Optional[str] = None", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 470}, "tests/test_ollama_integration_fixed.py::315": {"resolved_imports": ["src/vllm_cli/models/cache.py", "src/vllm_cli/models/manager.py", "src/vllm_cli/models/discovery.py"], "used_names": ["ModelManager", "build_model_dict", "patch"], "enclosing_function": "test_full_ollama_workflow", "extracted_code": "# Source: src/vllm_cli/models/manager.py\nclass ModelManager:\n \"\"\"\n Manages model discovery, caching, and metadata operations.\n\n Provides a high-level interface for model operations including\n listing, searching, and retrieving model information with\n integrated caching for performance.\n \"\"\"\n\n def __init__(self):\n self.cache = ModelCache()\n\n def list_available_models(self, refresh: bool = False) -> List[Dict[str, Any]]:\n \"\"\"\n List all available downloaded models with caching.\n\n Model scanning can be expensive, so results are cached for a short time\n to improve performance when multiple UI components need model data.\n\n Args:\n refresh: Force refresh the model cache, ignoring TTL\n\n Returns:\n List of model dictionaries with keys:\n - name: Full model name (publisher/model)\n - size: Model size in bytes\n - path: Path to model directory\n - type: Model type (model, custom_model)\n - publisher: Model publisher/organization\n - display_name: Human-readable model name\n - metadata: Additional model metadata\n \"\"\"\n # If refresh is forced, clear cache first to ensure fresh data\n if refresh:\n self.cache.clear_cache()\n logger.debug(\"Cache cleared for forced refresh\")\n else:\n # Check cache only if not refreshing\n cached_models = self.cache.get_cached_models()\n if cached_models is not None:\n return cached_models\n\n # Fetch fresh model data\n models = scan_for_models()\n\n # Process and normalize model data\n processed_models = []\n for item in models:\n # Accept all model types from hf-model-tool\n model_types = [\"model\", \"custom_model\", \"ollama_model\", \"gguf_model\"]\n if item.get(\"type\") in model_types:\n # For Ollama/GGUF models, use the item directly (already formatted)\n if item.get(\"type\") in [\"ollama_model\", \"gguf_model\"]:\n processed_models.append(item)\n else:\n model_dict = build_model_dict(item)\n processed_models.append(model_dict)\n\n # Sort models by name\n processed_models.sort(key=lambda x: x[\"name\"])\n\n # Update cache\n self.cache.cache_models(processed_models)\n\n logger.info(f\"Found {len(processed_models)} models\")\n return processed_models\n\n def get_model_details(self, model_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get detailed information about a specific model.\n\n Args:\n model_name: Name of the model to get details for\n\n Returns:\n Dictionary with model details or None if not found\n \"\"\"\n # First, try to find from cached models\n models = self.list_available_models()\n model_info = None\n\n for model in models:\n if model[\"name\"] == model_name or model.get(\"display_name\") == model_name:\n model_info = model\n break\n\n if not model_info:\n logger.warning(f\"Model {model_name} not found\")\n return None\n\n # Build detailed information\n details = {\n \"name\": model_info[\"name\"],\n \"full_name\": model_info[\"name\"],\n \"path\": model_info.get(\"path\", \"\"),\n \"size\": model_info.get(\"size\", 0),\n \"type\": model_info.get(\"type\", \"model\"),\n \"publisher\": model_info.get(\"publisher\", \"unknown\"),\n \"display_name\": model_info.get(\"display_name\", model_name),\n }\n\n # Extract metadata if available\n metadata = model_info.get(\"metadata\", {})\n if metadata:\n details[\"architecture\"] = (\n metadata.get(\"architectures\", [\"unknown\"])[0]\n if metadata.get(\"architectures\")\n else \"unknown\"\n )\n details[\"model_type\"] = metadata.get(\"model_type\", \"unknown\")\n details[\"torch_dtype\"] = metadata.get(\"torch_dtype\", \"unknown\")\n details[\"vocab_size\"] = metadata.get(\"vocab_size\", \"unknown\")\n\n # Add to main details\n details[\"metadata\"] = metadata\n\n # Try to read config.json for more details if path exists\n if details[\"path\"]:\n from .metadata import extract_model_config\n\n config_data = extract_model_config(details[\"path\"])\n if config_data:\n details.update(config_data)\n\n return details\n\n def search_models(self, query: str) -> List[Dict[str, Any]]:\n \"\"\"\n Search for models matching a query.\n\n Args:\n query: Search query string\n\n Returns:\n List of matching models\n \"\"\"\n models = self.list_available_models()\n query_lower = query.lower()\n\n # Filter models matching the query\n matches = []\n for model in models:\n if (\n query_lower in model[\"name\"].lower()\n or query_lower in model.get(\"display_name\", \"\").lower()\n or query_lower in model.get(\"publisher\", \"\").lower()\n ):\n matches.append(model)\n\n return matches\n\n def get_model_count(self) -> int:\n \"\"\"\n Get the total number of available models.\n\n Returns:\n Number of available models\n \"\"\"\n return len(self.list_available_models())\n\n def get_models_by_publisher(self, publisher: str) -> List[Dict[str, Any]]:\n \"\"\"\n Get all models from a specific publisher.\n\n Args:\n publisher: Publisher/organization name\n\n Returns:\n List of models from the publisher\n \"\"\"\n models = self.list_available_models()\n return [\n model\n for model in models\n if model.get(\"publisher\", \"\").lower() == publisher.lower()\n ]\n\n def get_models_by_type(self, model_type: str) -> List[Dict[str, Any]]:\n \"\"\"\n Get all models of a specific type.\n\n Args:\n model_type: Type of model (e.g., 'model', 'custom_model')\n\n Returns:\n List of models of the specified type\n \"\"\"\n models = self.list_available_models()\n return [model for model in models if model.get(\"type\") == model_type]\n\n def refresh_cache(self) -> None:\n \"\"\"Force refresh of the model cache.\"\"\"\n # First, force registry refresh to pick up any changes\n try:\n import os\n from pathlib import Path\n\n from hf_model_tool import get_registry\n\n # Clear all possible cache files\n cache_locations = [\n Path.home() / \".config/hf-model-tool/registry_cache.json\",\n Path.home() / \".cache/hf-model-tool/registry.json\",\n Path.home() / \".hf-model-tool/cache.json\",\n ]\n\n for cache_file in cache_locations:\n if cache_file.exists():\n try:\n os.remove(cache_file)\n logger.debug(f\"Removed cache file: {cache_file}\")\n except Exception as e:\n logger.debug(f\"Could not remove {cache_file}: {e}\")\n\n # Get registry and clear its in-memory cache\n registry = get_registry()\n\n # Clear all in-memory collections\n registry.models.clear()\n registry.custom_models.clear()\n registry.ollama_models.clear()\n registry.gguf_models.clear()\n registry.lora_adapters.clear()\n registry.datasets.clear()\n\n # Reset scan time to force rescan\n registry._last_scan_time = 0\n\n # Force complete rescan without incremental updates\n registry.scan_all(force=True, incremental=False)\n logger.info(\"Forced complete registry refresh\")\n except Exception as e:\n logger.debug(f\"Registry refresh error: {e}\")\n\n # Clear the cache to ensure we don't get stale data\n self.cache.clear_cache()\n logger.debug(\"Cache cleared\")\n\n # Now fetch fresh models - this will populate the cache with new data\n models = self.list_available_models(refresh=True)\n logger.info(f\"Model cache refreshed with {len(models)} models\")\n\n def get_cache_stats(self) -> Dict[str, Any]:\n \"\"\"\n Get cache statistics.\n\n Returns:\n Dictionary with cache statistics\n \"\"\"\n return self.cache.get_cache_stats()\n\n\n# Source: src/vllm_cli/models/discovery.py\ndef build_model_dict(item: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Build a standardized model dictionary from model data.\n\n Takes raw model information from various sources and normalizes\n it into a consistent format.\n\n Args:\n item: Model item data\n\n Returns:\n Standardized model dictionary\n \"\"\"\n publisher = item.get(\"publisher\", \"unknown\")\n display_name = item.get(\"display_name\", item.get(\"name\", \"unknown\"))\n\n # Create proper model name\n if publisher and publisher != \"unknown\":\n model_name = f\"{publisher}/{display_name}\"\n else:\n model_name = display_name\n\n return {\n \"name\": model_name,\n \"size\": item.get(\"size\", 0),\n \"path\": item.get(\"path\", \"\"),\n \"type\": item.get(\"type\", \"model\"),\n \"publisher\": publisher,\n \"display_name\": display_name,\n \"metadata\": item.get(\"metadata\", {}),\n }", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 9607}, "tests/proxy/test_models.py::81": {"resolved_imports": ["src/vllm_cli/proxy/models.py"], "used_names": ["ModelConfig"], "enclosing_function": "test_model_config_serialization", "extracted_code": "# Source: src/vllm_cli/proxy/models.py\nclass ModelConfig(BaseModel):\n \"\"\"Configuration for a single model in the proxy.\"\"\"\n\n name: str = Field(..., description=\"Model identifier for API requests\")\n model_path: str = Field(..., description=\"Path or HuggingFace model ID\")\n gpu_ids: List[int] = Field(default_factory=list, description=\"GPU IDs to use\")\n port: int = Field(..., description=\"Port for the vLLM server\")\n profile: Optional[str] = Field(None, description=\"vLLM CLI profile to use\")\n config_overrides: Dict[str, Any] = Field(\n default_factory=dict, description=\"Additional vLLM configuration\"\n )\n enabled: bool = Field(True, description=\"Whether model is enabled\")\n loading_priority: Optional[int] = Field(\n None,\n description=\"Loading priority (lower numbers load first). \"\n \"Models with same priority load in parallel. \"\n \"Models with None priority load after all prioritized models.\",\n )", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 967}, "tests/test_ollama_support.py::372": {"resolved_imports": ["src/vllm_cli/models/discovery.py", "src/vllm_cli/models/manager.py"], "used_names": [], "enclosing_function": "test_ollama_model_dict_structure", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_config_manager.py::102": {"resolved_imports": ["src/vllm_cli/config/manager.py"], "used_names": ["ConfigManager", "patch", "yaml"], "enclosing_function": "test_get_last_config", "extracted_code": "# Source: src/vllm_cli/config/manager.py\nclass ConfigManager:\n \"\"\"\n Enhanced configuration manager with comprehensive validation support.\n\n This class manages configuration files, profiles, and validation using\n the new validation framework. It provides a clean API for configuration\n operations while ensuring data integrity through comprehensive validation.\n\n Attributes:\n config_dir: Directory for configuration files\n validation_registry: Registry of validation rules\n compatibility_validator: Validator for parameter combinations\n \"\"\"\n\n def __init__(self):\n # Paths for configuration files\n self.config_dir = Path.home() / \".config\" / \"vllm-cli\"\n self.config_file = self.config_dir / \"config.yaml\"\n\n # Ensure config directory exists\n self.config_dir.mkdir(parents=True, exist_ok=True)\n\n # Initialize sub-managers\n self.schema_manager = SchemaManager()\n self.profile_manager = ProfileManager(self.config_dir)\n self.persistence_manager = PersistenceManager()\n self.shortcut_manager = ShortcutManager(self.config_dir)\n\n # Initialize validation system\n self.validation_registry = create_vllm_validation_registry()\n self.compatibility_validator = create_compatibility_validator(\n self.validation_registry\n )\n\n # Load main configuration\n self.config = self._load_config()\n\n def _load_config(self) -> Dict[str, Any]:\n \"\"\"Load main configuration file (legacy YAML support).\"\"\"\n return self.persistence_manager.load_yaml_file(self.config_file)\n\n def _save_config(self) -> None:\n \"\"\"Save main configuration file.\"\"\"\n self.persistence_manager.save_yaml_file(self.config_file, self.config)\n\n def get_argument_info(self, arg_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get detailed information about a specific argument.\"\"\"\n return self.schema_manager.get_argument_info(arg_name)\n\n def get_arguments_by_category(self, category: str) -> List[Dict[str, Any]]:\n \"\"\"Get all arguments belonging to a specific category.\"\"\"\n return self.schema_manager.get_arguments_by_category(category)\n\n def get_category_info(self, category: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get information about a specific category.\"\"\"\n return self.schema_manager.get_category_info(category)\n\n def get_ordered_categories(self) -> List[Tuple[str, Dict[str, Any]]]:\n \"\"\"Get categories ordered by their display order.\"\"\"\n return self.schema_manager.get_ordered_categories()\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n return self.profile_manager.get_all_profiles()\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name with dynamic defaults applied.\"\"\"\n profile = self.profile_manager.get_profile(name)\n if profile and \"config\" in profile:\n # Apply dynamic defaults to the profile configuration\n profile[\"config\"] = self.profile_manager.apply_dynamic_defaults(\n profile[\"config\"]\n )\n return profile\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"Save or update a user profile with validation.\"\"\"\n # Validate profile configuration if present\n if \"config\" in profile:\n is_valid, errors = self.validate_config(profile[\"config\"])\n if not is_valid:\n from ..errors import ProfileError\n\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n return self.profile_manager.save_user_profile(name, profile)\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n return self.profile_manager.delete_user_profile(name)\n\n @property\n def default_profiles(self) -> Dict[str, Any]:\n \"\"\"Get default profiles.\"\"\"\n return self.profile_manager.default_profiles\n\n @property\n def user_profiles(self) -> Dict[str, Any]:\n \"\"\"Get user profiles.\"\"\"\n return self.profile_manager.user_profiles\n\n def validate_config(self, config: Dict[str, Any]) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate a configuration using the new validation framework.\n\n This method uses the comprehensive validation system to check\n configuration values, types, ranges, and dependencies.\n\n Args:\n config: Configuration dictionary to validate\n\n Returns:\n Tuple of (is_valid, list_of_error_messages)\n\n Raises:\n ConfigurationError: If validation system fails\n \"\"\"\n try:\n # Use new validation system\n result = self.validation_registry.validate_config(config)\n\n # Convert validation errors to string messages for backward compatibility\n error_messages = result.get_error_messages()\n\n # Add warnings if any\n if result.warnings:\n for warning in result.warnings:\n logger.warning(f\"Configuration warning: {warning}\")\n\n return result.is_valid(), error_messages\n\n except Exception as e:\n logger.error(f\"Error during configuration validation: {e}\")\n raise ConfigurationError(\n f\"Validation system error: {e}\", error_code=\"VALIDATION_SYSTEM_ERROR\"\n ) from e\n\n def validate_argument_combination(\n self, config: Dict[str, Any]\n ) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate that argument combinations are compatible using the new compatibility validator.\n\n Args:\n config: Configuration dictionary to check for compatibility\n\n Returns:\n Tuple of (is_valid, list_of_warnings_or_errors)\n \"\"\"\n try:\n issues = self.compatibility_validator.validate_compatibility(config)\n\n warnings = []\n errors = []\n\n for issue in issues:\n message = issue[\"message\"]\n if issue[\"severity\"] == \"error\":\n errors.append(message)\n else:\n warnings.append(message)\n\n # Log warnings\n for warning in warnings:\n logger.warning(f\"Configuration compatibility warning: {warning}\")\n\n # Return all issues as warnings for backward compatibility\n # (errors are treated as warnings in the legacy interface)\n all_issues = errors + warnings\n\n return len(errors) == 0, all_issues\n\n except Exception as e:\n logger.error(f\"Error during compatibility validation: {e}\")\n return False, [f\"Compatibility validation error: {e}\"]\n\n def build_cli_args(self, config: Dict[str, Any]) -> List[str]:\n \"\"\"\n Build command-line arguments from a configuration dictionary.\n\n Only includes arguments that are explicitly set in the config.\n Handles special cases like LoRA modules.\n \"\"\"\n args = []\n\n # Special handling for model (positional argument)\n # Check if this is a GGUF/Ollama configuration\n if (\n isinstance(config.get(\"model\"), dict)\n and \"quantization\" in config[\"model\"]\n and config[\"model\"][\"quantization\"] == \"gguf\"\n ):\n # Extract GGUF model config\n gguf_config = config[\"model\"]\n model_path = gguf_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", model_path])\n\n # Set quantization to gguf\n config[\"quantization\"] = \"gguf\"\n\n # Add served-model-name if provided (for Ollama models)\n if \"served_model_name\" in gguf_config:\n config[\"served_model_name\"] = gguf_config[\"served_model_name\"]\n logger.info(\n f\"Configuring GGUF model: {model_path} as {gguf_config['served_model_name']}\"\n )\n else:\n logger.info(f\"Configuring GGUF model: {model_path}\")\n\n # Check if this is a LoRA configuration\n elif (\n isinstance(config.get(\"model\"), dict) and \"lora_modules\" in config[\"model\"]\n ):\n # Extract base model and LoRA config\n lora_config = config[\"model\"]\n base_model = lora_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", base_model])\n\n # Enable LoRA support when modules are present\n args.append(\"--enable-lora\")\n\n # Track maximum rank for all LoRA modules\n max_rank = 16 # Default minimum\n\n # Add LoRA modules\n for lora in lora_config.get(\"lora_modules\", []):\n lora_path = lora.get(\"path\", \"\")\n if lora_path:\n # vLLM expects --lora-modules with name=path format\n lora_name = lora.get(\"name\", \"adapter\")\n args.extend([\"--lora-modules\", f\"{lora_name}={lora_path}\"])\n\n # Track maximum rank\n lora_rank = lora.get(\"rank\", 16)\n max_rank = max(max_rank, lora_rank)\n\n # Add max-lora-rank parameter\n args.extend([\"--max-lora-rank\", str(max_rank)])\n\n elif \"model\" in config:\n args.extend([\"serve\", config[\"model\"]])\n\n # Handle lora_modules if present as a string (from CLI)\n if \"lora_modules\" in config and config[\"lora_modules\"]:\n # Enable LoRA support\n if \"--enable-lora\" not in args:\n args.append(\"--enable-lora\")\n\n # Parse and add LoRA modules\n lora_modules_str = config[\"lora_modules\"]\n if isinstance(lora_modules_str, str):\n # Split by space and add each module\n for module in lora_modules_str.split():\n args.extend([\"--lora-modules\", module])\n\n # Add max-lora-rank if not already added\n # Use a safe default of 64 which should cover most LoRA adapters\n if \"--max-lora-rank\" not in args:\n # Check if max_lora_rank is explicitly set in config\n if \"max_lora_rank\" not in config:\n args.extend([\"--max-lora-rank\", \"64\"])\n\n for arg_name, value in config.items():\n # Skip special keys and None values\n if (\n arg_name in [\"model\", \"name\", \"description\", \"icon\", \"lora_modules\"]\n or value is None\n ):\n continue\n\n arg_info = self.schema_manager.get_argument_info(arg_name)\n if not arg_info:\n logger.warning(f\"Unknown argument in config: {arg_name}\")\n continue\n\n cli_flag = arg_info.get(\"cli_flag\")\n if not cli_flag:\n continue\n\n arg_type = arg_info.get(\"type\")\n\n if arg_type == \"boolean\":\n if value: # Only add flag if True\n args.append(cli_flag)\n elif arg_type in [\"integer\", \"float\", \"string\", \"choice\"]:\n args.extend([cli_flag, str(value)])\n else:\n logger.warning(f\"Unknown argument type for {arg_name}: {arg_type}\")\n\n return args\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n return self.profile_manager.export_profile(profile_name, filepath)\n\n def import_profile(self, filepath: Path, new_name: Optional[str] = None) -> bool:\n \"\"\"Import a profile from a JSON file with comprehensive validation.\"\"\"\n return self.profile_manager.import_profile(\n filepath, new_name, self.validate_config\n )\n\n def get_last_config(self) -> Optional[Dict[str, Any]]:\n \"\"\"Get the last used server configuration.\"\"\"\n return self.config.get(\"last_config\")\n\n def save_last_config(self, config: Dict[str, Any]) -> None:\n \"\"\"Save the last used server configuration.\"\"\"\n self.config[\"last_config\"] = config\n self._save_config()\n\n def get_recent_models(self, limit: int = 5) -> List[str]:\n \"\"\"Get recently used models.\"\"\"\n return self.config.get(\"recent_models\", [])[:limit]\n\n def add_recent_model(self, model: str) -> None:\n \"\"\"Add a model to recent models list.\"\"\"\n recent = self.config.get(\"recent_models\", [])\n if model in recent:\n recent.remove(model)\n recent.insert(0, model)\n self.config[\"recent_models\"] = recent[:10] # Keep only last 10\n self._save_config()\n\n def clear_cache(self) -> None:\n \"\"\"Clear cached data.\"\"\"\n cache_file = self.config_dir / \"cache.json\"\n if cache_file.exists():\n cache_file.unlink()\n self.config.pop(\"last_config\", None)\n self.config.pop(\"recent_models\", None)\n self._save_config()\n logger.info(\"Cache cleared\")\n\n def get_server_defaults(self) -> Dict[str, Any]:\n \"\"\"Get default server settings.\"\"\"\n return self.config.get(\n \"server_defaults\",\n {\n \"default_port\": 8000,\n \"auto_restart\": False,\n \"log_level\": \"info\",\n \"cleanup_on_exit\": True, # Default to cleaning up servers on exit\n },\n )\n\n def save_server_defaults(self, defaults: Dict[str, Any]) -> None:\n \"\"\"Save default server settings.\"\"\"\n self.config[\"server_defaults\"] = defaults\n self._save_config()\n\n def get_ui_preferences(self) -> Dict[str, Any]:\n \"\"\"Get UI preferences including progress bar style and log display settings.\"\"\"\n return self.config.get(\n \"ui_preferences\",\n {\n \"progress_bar_style\": \"blocks\", # Default style\n \"show_gpu_in_monitor\": True,\n \"log_lines_startup\": 50, # Number of log lines to show during startup\n \"log_lines_monitor\": 50, # Number of log lines to show in server monitor\n \"startup_refresh_rate\": 4.0, # Hz for startup log refresh\n \"monitor_refresh_rate\": 1.0, # Hz for monitor log refresh\n },\n )\n\n def save_ui_preferences(self, preferences: Dict[str, Any]) -> None:\n \"\"\"Save UI preferences.\"\"\"\n self.config[\"ui_preferences\"] = preferences\n self._save_config()\n\n # Shortcut management methods\n def get_all_shortcuts(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all shortcuts.\"\"\"\n return self.shortcut_manager.get_all_shortcuts()\n\n def get_shortcut(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific shortcut by name.\"\"\"\n return self.shortcut_manager.get_shortcut(name)\n\n def save_shortcut(self, name: str, shortcut_data: Dict[str, Any]) -> bool:\n \"\"\"Save or update a shortcut.\"\"\"\n return self.shortcut_manager.save_shortcut(name, shortcut_data)\n\n def delete_shortcut(self, name: str) -> bool:\n \"\"\"Delete a shortcut.\"\"\"\n return self.shortcut_manager.delete_shortcut(name)\n\n def list_shortcuts(self) -> List[Dict[str, Any]]:\n \"\"\"List all shortcuts with summary information.\"\"\"\n return self.shortcut_manager.list_shortcuts()\n\n def get_recent_shortcuts(self, limit: int = 5) -> List[Dict[str, Any]]:\n \"\"\"Get recently used shortcuts.\"\"\"\n return self.shortcut_manager.get_recent_shortcuts(limit)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 15704}, "tests/test_config_manager.py::76": {"resolved_imports": ["src/vllm_cli/config/manager.py"], "used_names": ["ConfigManager", "patch", "yaml"], "enclosing_function": "test_save_config", "extracted_code": "# Source: src/vllm_cli/config/manager.py\nclass ConfigManager:\n \"\"\"\n Enhanced configuration manager with comprehensive validation support.\n\n This class manages configuration files, profiles, and validation using\n the new validation framework. It provides a clean API for configuration\n operations while ensuring data integrity through comprehensive validation.\n\n Attributes:\n config_dir: Directory for configuration files\n validation_registry: Registry of validation rules\n compatibility_validator: Validator for parameter combinations\n \"\"\"\n\n def __init__(self):\n # Paths for configuration files\n self.config_dir = Path.home() / \".config\" / \"vllm-cli\"\n self.config_file = self.config_dir / \"config.yaml\"\n\n # Ensure config directory exists\n self.config_dir.mkdir(parents=True, exist_ok=True)\n\n # Initialize sub-managers\n self.schema_manager = SchemaManager()\n self.profile_manager = ProfileManager(self.config_dir)\n self.persistence_manager = PersistenceManager()\n self.shortcut_manager = ShortcutManager(self.config_dir)\n\n # Initialize validation system\n self.validation_registry = create_vllm_validation_registry()\n self.compatibility_validator = create_compatibility_validator(\n self.validation_registry\n )\n\n # Load main configuration\n self.config = self._load_config()\n\n def _load_config(self) -> Dict[str, Any]:\n \"\"\"Load main configuration file (legacy YAML support).\"\"\"\n return self.persistence_manager.load_yaml_file(self.config_file)\n\n def _save_config(self) -> None:\n \"\"\"Save main configuration file.\"\"\"\n self.persistence_manager.save_yaml_file(self.config_file, self.config)\n\n def get_argument_info(self, arg_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get detailed information about a specific argument.\"\"\"\n return self.schema_manager.get_argument_info(arg_name)\n\n def get_arguments_by_category(self, category: str) -> List[Dict[str, Any]]:\n \"\"\"Get all arguments belonging to a specific category.\"\"\"\n return self.schema_manager.get_arguments_by_category(category)\n\n def get_category_info(self, category: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get information about a specific category.\"\"\"\n return self.schema_manager.get_category_info(category)\n\n def get_ordered_categories(self) -> List[Tuple[str, Dict[str, Any]]]:\n \"\"\"Get categories ordered by their display order.\"\"\"\n return self.schema_manager.get_ordered_categories()\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n return self.profile_manager.get_all_profiles()\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name with dynamic defaults applied.\"\"\"\n profile = self.profile_manager.get_profile(name)\n if profile and \"config\" in profile:\n # Apply dynamic defaults to the profile configuration\n profile[\"config\"] = self.profile_manager.apply_dynamic_defaults(\n profile[\"config\"]\n )\n return profile\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"Save or update a user profile with validation.\"\"\"\n # Validate profile configuration if present\n if \"config\" in profile:\n is_valid, errors = self.validate_config(profile[\"config\"])\n if not is_valid:\n from ..errors import ProfileError\n\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n return self.profile_manager.save_user_profile(name, profile)\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n return self.profile_manager.delete_user_profile(name)\n\n @property\n def default_profiles(self) -> Dict[str, Any]:\n \"\"\"Get default profiles.\"\"\"\n return self.profile_manager.default_profiles\n\n @property\n def user_profiles(self) -> Dict[str, Any]:\n \"\"\"Get user profiles.\"\"\"\n return self.profile_manager.user_profiles\n\n def validate_config(self, config: Dict[str, Any]) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate a configuration using the new validation framework.\n\n This method uses the comprehensive validation system to check\n configuration values, types, ranges, and dependencies.\n\n Args:\n config: Configuration dictionary to validate\n\n Returns:\n Tuple of (is_valid, list_of_error_messages)\n\n Raises:\n ConfigurationError: If validation system fails\n \"\"\"\n try:\n # Use new validation system\n result = self.validation_registry.validate_config(config)\n\n # Convert validation errors to string messages for backward compatibility\n error_messages = result.get_error_messages()\n\n # Add warnings if any\n if result.warnings:\n for warning in result.warnings:\n logger.warning(f\"Configuration warning: {warning}\")\n\n return result.is_valid(), error_messages\n\n except Exception as e:\n logger.error(f\"Error during configuration validation: {e}\")\n raise ConfigurationError(\n f\"Validation system error: {e}\", error_code=\"VALIDATION_SYSTEM_ERROR\"\n ) from e\n\n def validate_argument_combination(\n self, config: Dict[str, Any]\n ) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate that argument combinations are compatible using the new compatibility validator.\n\n Args:\n config: Configuration dictionary to check for compatibility\n\n Returns:\n Tuple of (is_valid, list_of_warnings_or_errors)\n \"\"\"\n try:\n issues = self.compatibility_validator.validate_compatibility(config)\n\n warnings = []\n errors = []\n\n for issue in issues:\n message = issue[\"message\"]\n if issue[\"severity\"] == \"error\":\n errors.append(message)\n else:\n warnings.append(message)\n\n # Log warnings\n for warning in warnings:\n logger.warning(f\"Configuration compatibility warning: {warning}\")\n\n # Return all issues as warnings for backward compatibility\n # (errors are treated as warnings in the legacy interface)\n all_issues = errors + warnings\n\n return len(errors) == 0, all_issues\n\n except Exception as e:\n logger.error(f\"Error during compatibility validation: {e}\")\n return False, [f\"Compatibility validation error: {e}\"]\n\n def build_cli_args(self, config: Dict[str, Any]) -> List[str]:\n \"\"\"\n Build command-line arguments from a configuration dictionary.\n\n Only includes arguments that are explicitly set in the config.\n Handles special cases like LoRA modules.\n \"\"\"\n args = []\n\n # Special handling for model (positional argument)\n # Check if this is a GGUF/Ollama configuration\n if (\n isinstance(config.get(\"model\"), dict)\n and \"quantization\" in config[\"model\"]\n and config[\"model\"][\"quantization\"] == \"gguf\"\n ):\n # Extract GGUF model config\n gguf_config = config[\"model\"]\n model_path = gguf_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", model_path])\n\n # Set quantization to gguf\n config[\"quantization\"] = \"gguf\"\n\n # Add served-model-name if provided (for Ollama models)\n if \"served_model_name\" in gguf_config:\n config[\"served_model_name\"] = gguf_config[\"served_model_name\"]\n logger.info(\n f\"Configuring GGUF model: {model_path} as {gguf_config['served_model_name']}\"\n )\n else:\n logger.info(f\"Configuring GGUF model: {model_path}\")\n\n # Check if this is a LoRA configuration\n elif (\n isinstance(config.get(\"model\"), dict) and \"lora_modules\" in config[\"model\"]\n ):\n # Extract base model and LoRA config\n lora_config = config[\"model\"]\n base_model = lora_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", base_model])\n\n # Enable LoRA support when modules are present\n args.append(\"--enable-lora\")\n\n # Track maximum rank for all LoRA modules\n max_rank = 16 # Default minimum\n\n # Add LoRA modules\n for lora in lora_config.get(\"lora_modules\", []):\n lora_path = lora.get(\"path\", \"\")\n if lora_path:\n # vLLM expects --lora-modules with name=path format\n lora_name = lora.get(\"name\", \"adapter\")\n args.extend([\"--lora-modules\", f\"{lora_name}={lora_path}\"])\n\n # Track maximum rank\n lora_rank = lora.get(\"rank\", 16)\n max_rank = max(max_rank, lora_rank)\n\n # Add max-lora-rank parameter\n args.extend([\"--max-lora-rank\", str(max_rank)])\n\n elif \"model\" in config:\n args.extend([\"serve\", config[\"model\"]])\n\n # Handle lora_modules if present as a string (from CLI)\n if \"lora_modules\" in config and config[\"lora_modules\"]:\n # Enable LoRA support\n if \"--enable-lora\" not in args:\n args.append(\"--enable-lora\")\n\n # Parse and add LoRA modules\n lora_modules_str = config[\"lora_modules\"]\n if isinstance(lora_modules_str, str):\n # Split by space and add each module\n for module in lora_modules_str.split():\n args.extend([\"--lora-modules\", module])\n\n # Add max-lora-rank if not already added\n # Use a safe default of 64 which should cover most LoRA adapters\n if \"--max-lora-rank\" not in args:\n # Check if max_lora_rank is explicitly set in config\n if \"max_lora_rank\" not in config:\n args.extend([\"--max-lora-rank\", \"64\"])\n\n for arg_name, value in config.items():\n # Skip special keys and None values\n if (\n arg_name in [\"model\", \"name\", \"description\", \"icon\", \"lora_modules\"]\n or value is None\n ):\n continue\n\n arg_info = self.schema_manager.get_argument_info(arg_name)\n if not arg_info:\n logger.warning(f\"Unknown argument in config: {arg_name}\")\n continue\n\n cli_flag = arg_info.get(\"cli_flag\")\n if not cli_flag:\n continue\n\n arg_type = arg_info.get(\"type\")\n\n if arg_type == \"boolean\":\n if value: # Only add flag if True\n args.append(cli_flag)\n elif arg_type in [\"integer\", \"float\", \"string\", \"choice\"]:\n args.extend([cli_flag, str(value)])\n else:\n logger.warning(f\"Unknown argument type for {arg_name}: {arg_type}\")\n\n return args\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n return self.profile_manager.export_profile(profile_name, filepath)\n\n def import_profile(self, filepath: Path, new_name: Optional[str] = None) -> bool:\n \"\"\"Import a profile from a JSON file with comprehensive validation.\"\"\"\n return self.profile_manager.import_profile(\n filepath, new_name, self.validate_config\n )\n\n def get_last_config(self) -> Optional[Dict[str, Any]]:\n \"\"\"Get the last used server configuration.\"\"\"\n return self.config.get(\"last_config\")\n\n def save_last_config(self, config: Dict[str, Any]) -> None:\n \"\"\"Save the last used server configuration.\"\"\"\n self.config[\"last_config\"] = config\n self._save_config()\n\n def get_recent_models(self, limit: int = 5) -> List[str]:\n \"\"\"Get recently used models.\"\"\"\n return self.config.get(\"recent_models\", [])[:limit]\n\n def add_recent_model(self, model: str) -> None:\n \"\"\"Add a model to recent models list.\"\"\"\n recent = self.config.get(\"recent_models\", [])\n if model in recent:\n recent.remove(model)\n recent.insert(0, model)\n self.config[\"recent_models\"] = recent[:10] # Keep only last 10\n self._save_config()\n\n def clear_cache(self) -> None:\n \"\"\"Clear cached data.\"\"\"\n cache_file = self.config_dir / \"cache.json\"\n if cache_file.exists():\n cache_file.unlink()\n self.config.pop(\"last_config\", None)\n self.config.pop(\"recent_models\", None)\n self._save_config()\n logger.info(\"Cache cleared\")\n\n def get_server_defaults(self) -> Dict[str, Any]:\n \"\"\"Get default server settings.\"\"\"\n return self.config.get(\n \"server_defaults\",\n {\n \"default_port\": 8000,\n \"auto_restart\": False,\n \"log_level\": \"info\",\n \"cleanup_on_exit\": True, # Default to cleaning up servers on exit\n },\n )\n\n def save_server_defaults(self, defaults: Dict[str, Any]) -> None:\n \"\"\"Save default server settings.\"\"\"\n self.config[\"server_defaults\"] = defaults\n self._save_config()\n\n def get_ui_preferences(self) -> Dict[str, Any]:\n \"\"\"Get UI preferences including progress bar style and log display settings.\"\"\"\n return self.config.get(\n \"ui_preferences\",\n {\n \"progress_bar_style\": \"blocks\", # Default style\n \"show_gpu_in_monitor\": True,\n \"log_lines_startup\": 50, # Number of log lines to show during startup\n \"log_lines_monitor\": 50, # Number of log lines to show in server monitor\n \"startup_refresh_rate\": 4.0, # Hz for startup log refresh\n \"monitor_refresh_rate\": 1.0, # Hz for monitor log refresh\n },\n )\n\n def save_ui_preferences(self, preferences: Dict[str, Any]) -> None:\n \"\"\"Save UI preferences.\"\"\"\n self.config[\"ui_preferences\"] = preferences\n self._save_config()\n\n # Shortcut management methods\n def get_all_shortcuts(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all shortcuts.\"\"\"\n return self.shortcut_manager.get_all_shortcuts()\n\n def get_shortcut(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific shortcut by name.\"\"\"\n return self.shortcut_manager.get_shortcut(name)\n\n def save_shortcut(self, name: str, shortcut_data: Dict[str, Any]) -> bool:\n \"\"\"Save or update a shortcut.\"\"\"\n return self.shortcut_manager.save_shortcut(name, shortcut_data)\n\n def delete_shortcut(self, name: str) -> bool:\n \"\"\"Delete a shortcut.\"\"\"\n return self.shortcut_manager.delete_shortcut(name)\n\n def list_shortcuts(self) -> List[Dict[str, Any]]:\n \"\"\"List all shortcuts with summary information.\"\"\"\n return self.shortcut_manager.list_shortcuts()\n\n def get_recent_shortcuts(self, limit: int = 5) -> List[Dict[str, Any]]:\n \"\"\"Get recently used shortcuts.\"\"\"\n return self.shortcut_manager.get_recent_shortcuts(limit)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 15704}, "tests/proxy/test_models.py::43": {"resolved_imports": ["src/vllm_cli/proxy/models.py"], "used_names": ["ModelConfig"], "enclosing_function": "test_model_config_defaults", "extracted_code": "# Source: src/vllm_cli/proxy/models.py\nclass ModelConfig(BaseModel):\n \"\"\"Configuration for a single model in the proxy.\"\"\"\n\n name: str = Field(..., description=\"Model identifier for API requests\")\n model_path: str = Field(..., description=\"Path or HuggingFace model ID\")\n gpu_ids: List[int] = Field(default_factory=list, description=\"GPU IDs to use\")\n port: int = Field(..., description=\"Port for the vLLM server\")\n profile: Optional[str] = Field(None, description=\"vLLM CLI profile to use\")\n config_overrides: Dict[str, Any] = Field(\n default_factory=dict, description=\"Additional vLLM configuration\"\n )\n enabled: bool = Field(True, description=\"Whether model is enabled\")\n loading_priority: Optional[int] = Field(\n None,\n description=\"Loading priority (lower numbers load first). \"\n \"Models with same priority load in parallel. \"\n \"Models with None priority load after all prioritized models.\",\n )", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 967}, "tests/test_server_manager.py::48": {"resolved_imports": ["src/vllm_cli/server/__init__.py", "src/vllm_cli/server/process.py", "src/vllm_cli/server/manager.py"], "used_names": ["VLLMServer"], "enclosing_function": "test_build_command", "extracted_code": "# Source: src/vllm_cli/server/manager.py\nclass VLLMServer:\n \"\"\"\n Manages a vLLM server instance with comprehensive lifecycle control.\n\n This class handles the complete lifecycle of a vLLM server including\n configuration, process management, logging, monitoring, and cleanup.\n It supports both programmatically started servers and external server\n detection and management.\n\n Attributes:\n config: Server configuration dictionary\n model: Model name being served\n port: Port number the server is listening on\n process: Subprocess or external process reference\n log_file: File handle for server logs\n log_queue: Thread-safe queue for log lines\n log_thread: Background thread for log monitoring\n start_time: Timestamp when server was started\n log_path: Path to the server's log file\n \"\"\"\n\n def __init__(self, config: Dict[str, Any]) -> None:\n \"\"\"\n Initialize a vLLM server instance.\n\n Sets up the server configuration, logging infrastructure, and\n prepares the instance for server lifecycle management.\n\n Args:\n config: Server configuration dictionary containing model name,\n port, and other vLLM-specific parameters\n \"\"\"\n self.config: Dict[str, Any] = config\n\n # Extract model name - handle both string and dict (LoRA config) formats\n model_config = config.get(\"model\", \"unknown\")\n if isinstance(model_config, dict):\n # LoRA configuration - extract base model name\n self.model: str = model_config.get(\"model\", \"unknown\")\n else:\n # Regular string model name\n self.model: str = model_config\n\n self.port: int = config.get(\"port\", 8000)\n self.process: Optional[Union[subprocess.Popen, Any]] = None\n self.log_file: Optional[TextIO] = None\n self.log_queue: Queue[str] = Queue()\n self.log_thread: Optional[Thread] = None\n self.start_time: Optional[datetime] = None\n self.log_path: Path\n self._recent_logs: List[str] = []\n\n # Setup logging\n log_dir = Path.home() / \".vllm-cli\" / \"logs\"\n log_dir.mkdir(parents=True, exist_ok=True)\n\n timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n self.log_path = log_dir / f\"vllm_{self.model.replace('/', '_')}_{timestamp}.log\"\n\n def start(self) -> bool:\n \"\"\"\n Start the vLLM server.\n\n Returns:\n True if server started successfully, False otherwise\n \"\"\"\n if self.is_running():\n logger.warning(f\"Server already running for {self.model}\")\n return False\n\n try:\n # Build command - run directly without conda wrapper\n full_cmd = self._build_command()\n\n logger.info(f\"Starting vLLM server with command: {' '.join(full_cmd)}\")\n\n # Open log file for writing\n self.log_file = open(self.log_path, \"w\", buffering=1)\n\n # Start with parent environment\n env = os.environ.copy()\n # Note: No longer forcing PYTHONUNBUFFERED=1, let user control it\n\n # Layer 1: Apply universal environment variables from settings\n config_manager = ConfigManager()\n universal_env = config_manager.config.get(\"universal_environment\", {})\n if universal_env:\n logger.info(\n f\"Applying {len(universal_env)} universal environment variable(s)\"\n )\n for key, value in universal_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting universal {key}={value}\")\n else:\n logger.debug(f\"Setting universal {key}=\")\n\n # Layer 2: Apply profile environment variables (override universal)\n profile_env = self.config.get(\"profile_environment\", {})\n if profile_env:\n logger.info(\n f\"Applying {len(profile_env)} profile environment variable(s)\"\n )\n for key, value in profile_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting profile {key}={value}\")\n else:\n logger.debug(f\"Setting profile {key}=\")\n\n # Handle GPU device selection via CUDA_VISIBLE_DEVICES\n # This overrides any CUDA_VISIBLE_DEVICES from the profile\n if self.config.get(\"device\"):\n device_str = str(self.config[\"device\"])\n env[\"CUDA_VISIBLE_DEVICES\"] = device_str\n logger.info(f\"Setting CUDA_VISIBLE_DEVICES={device_str}\")\n\n # If using specific GPUs, adjust tensor parallel size if needed\n device_list = [d.strip() for d in device_str.split(\",\")]\n num_devices = len(device_list)\n\n # Check if tensor_parallel_size is set and compatible\n if self.config.get(\"tensor_parallel_size\"):\n tp_size = self.config[\"tensor_parallel_size\"]\n if tp_size > num_devices:\n logger.warning(\n f\"tensor_parallel_size ({tp_size}) > number of selected devices ({num_devices}). \"\n f\"Adjusting tensor_parallel_size to {num_devices}\"\n )\n self.config[\"tensor_parallel_size\"] = num_devices\n elif num_devices % tp_size != 0:\n logger.warning(\n f\"Number of GPUs ({num_devices}) is not evenly divisible by \"\n f\"tensor_parallel_size ({tp_size}). This may lead to inefficient GPU utilization. \"\n f\"Consider using tensor_parallel_size of: \"\n f\"{', '.join(str(i) for i in range(1, num_devices + 1) if num_devices % i == 0)}\"\n )\n\n # Add HuggingFace token if configured\n config_manager = ConfigManager()\n hf_token = config_manager.config.get(\"hf_token\")\n if hf_token:\n env[\"HF_TOKEN\"] = hf_token\n env[\"HUGGING_FACE_HUB_TOKEN\"] = hf_token # Some tools use this variant\n logger.info(\"HuggingFace token configured for server\")\n\n # Enable development mode for sleep endpoints if sleep mode is enabled\n if self.config.get(\"enable_sleep_mode\"):\n env[\"VLLM_SERVER_DEV_MODE\"] = \"1\"\n logger.info(\"Sleep mode enabled with development endpoints\")\n\n # Start the process with proper pipe configuration\n # Use start_new_session=True to create a new process group\n # This prevents the child process from receiving Ctrl+C signals\n self.process = subprocess.Popen(\n full_cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n text=True,\n bufsize=0, # Unbuffered\n universal_newlines=True,\n env=env,\n start_new_session=True, # Create new process group to isolate from parent signals\n )\n\n # Start log monitoring thread\n self._start_log_monitor()\n\n # Set start time and add to registry\n self.start_time = datetime.now()\n from .process import add_server\n\n add_server(self)\n\n # Return immediately - let the UI monitor the startup\n logger.info(\n f\"vLLM server process launched for {self.model} on port {self.port}\"\n )\n return True\n\n except Exception as e:\n logger.error(f\"Error starting vLLM server: {e}\")\n return False\n\n def _build_command(self) -> List[str]:\n \"\"\"\n Build the vLLM command from configuration using the schema.\n\n Returns:\n List of command arguments\n \"\"\"\n # Use the new ConfigManager to build CLI args\n config_manager = ConfigManager()\n\n # Start with the vllm command\n cmd = [\"vllm\"]\n\n # Add the arguments built from schema\n cli_args = config_manager.build_cli_args(self.config)\n cmd.extend(cli_args)\n\n # Handle extra_args if present (backward compatibility)\n if self.config.get(\"extra_args\"):\n self._add_extra_args_to_command(cmd)\n\n logger.debug(f\"Built command: {' '.join(cmd)}\")\n return cmd\n\n def _add_extra_args_to_command(self, cmd: List[str]) -> None:\n \"\"\"\n Add extra arguments to the vLLM command.\n\n Args:\n cmd: Command list to extend with extra arguments\n \"\"\"\n try:\n extra_args = shlex.split(self.config[\"extra_args\"])\n if extra_args:\n logger.info(f\"Adding extra arguments: {extra_args}\")\n cmd.extend(extra_args)\n except ValueError as e:\n logger.warning(f\"Failed to parse extra_args: {e}\")\n\n def _start_log_monitor(self) -> None:\n \"\"\"\n Start a thread to monitor log output from the vLLM server process.\n\n Creates a daemon thread that continuously reads stdout/stderr from\n the server process, writes to log files, and queues log lines for\n real-time display in the UI.\n \"\"\"\n self.log_thread = Thread(target=self._log_monitor_worker, daemon=True)\n self.log_thread.start()\n\n def _log_monitor_worker(self) -> None:\n \"\"\"\n Worker function for log monitoring thread.\n\n Continuously reads log output from the server process and handles\n file writing and queue management for UI display.\n \"\"\"\n try:\n self.log_queue.put(\"Starting vLLM server process...\")\n\n while self._should_continue_monitoring():\n if self._process_log_line():\n continue\n else:\n # No line read, check if process still running\n if self.process and self.process.poll() is not None:\n break\n time.sleep(0.01) # Small sleep to prevent busy waiting\n\n except Exception as e:\n logger.error(f\"Error in log monitor: {e}\")\n self.log_queue.put(f\"Log monitoring error: {e}\")\n\n def _should_continue_monitoring(self) -> bool:\n \"\"\"\n Check if log monitoring should continue.\n\n Returns:\n True if monitoring should continue, False otherwise\n \"\"\"\n return (\n self.is_running()\n and self.process\n and hasattr(self.process, \"stdout\")\n and self.process.stdout\n )\n\n def _process_log_line(self) -> bool:\n \"\"\"\n Process a single log line from the server output.\n\n Reads one line from the process stdout, writes it to the log file,\n and adds it to the queue for UI display after filtering and formatting.\n\n Returns:\n True if a line was processed, False if no line was available\n \"\"\"\n if not (self.process and self.process.stdout):\n return False\n\n line = self.process.stdout.readline()\n if not line:\n return False\n\n # Write to log file\n self._write_to_log_file(line)\n\n # Process for UI display\n line_stripped = line.strip()\n if line_stripped and self._should_display_log_line(line_stripped):\n # Truncate overly long lines\n if len(line_stripped) > 200:\n line_stripped = line_stripped[:197] + \"...\"\n\n self.log_queue.put(line_stripped)\n logger.debug(f\"Log captured: {line_stripped[:50]}...\")\n\n return True\n\n def _write_to_log_file(self, line: str) -> None:\n \"\"\"\n Write a log line to the log file.\n\n Args:\n line: Log line to write\n \"\"\"\n if self.log_file and not self.log_file.closed:\n self.log_file.write(line)\n self.log_file.flush()\n\n def _should_display_log_line(self, line: str) -> bool:\n \"\"\"\n Determine if a log line should be displayed in the UI.\n\n Filters out certain system messages that are not useful for users.\n\n Args:\n line: Stripped log line to check\n\n Returns:\n True if the line should be displayed, False otherwise\n \"\"\"\n # Filter out conda activation and system messages\n filtered_messages = [\n \"Activated CUDA\",\n \"Using nvcc from:\",\n \"Cuda compilation tools\",\n ]\n return not any(skip in line for skip in filtered_messages)\n\n def stop(self) -> bool:\n \"\"\"\n Stop the vLLM server.\n\n Returns:\n True if server stopped successfully, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n try:\n # Check if this is an external server\n if hasattr(self.process, \"terminate\"):\n # Normal subprocess\n # Since we created a new session, we need to terminate the entire process group\n try:\n # Get the process group ID (pgid)\n # Since we used start_new_session=True, the pgid is the same as the pid\n pgid = self.process.pid\n\n # Send SIGTERM to the entire process group for graceful shutdown\n logger.info(f\"Sending SIGTERM to process group {pgid}\")\n os.killpg(pgid, signal.SIGTERM)\n\n # Wait for process to terminate\n try:\n self.process.wait(timeout=10)\n logger.info(f\"Process group {pgid} terminated gracefully\")\n except subprocess.TimeoutExpired:\n # Force kill if not terminated\n logger.warning(\n f\"Process group {pgid} did not terminate, sending SIGKILL\"\n )\n os.killpg(pgid, signal.SIGKILL)\n self.process.wait()\n logger.info(f\"Process group {pgid} force killed\")\n\n except ProcessLookupError:\n # Process already dead\n logger.info(\"Process already terminated\")\n except PermissionError as e:\n # Fall back to terminating just the process\n logger.warning(\n f\"Permission denied for process group kill: {e}, falling back to process termination\"\n )\n self.process.terminate()\n try:\n self.process.wait(timeout=10)\n except subprocess.TimeoutExpired:\n self.process.kill()\n self.process.wait()\n elif hasattr(self.process, \"pid\"):\n # External server - kill entire process group or individual process\n try:\n pgid = self.process.pid\n killed = False\n\n # First attempt: try to kill process group\n try:\n os.killpg(pgid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process group {pgid}\")\n killed = True\n except (OSError, ProcessLookupError) as e:\n # Process group kill failed, try individual process\n logger.debug(\n f\"Process group kill failed: {e}, trying individual process\"\n )\n try:\n # Ensure pid is an integer (handle Mock objects)\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process {self.process.pid}\")\n killed = True\n except ProcessLookupError:\n # Process already dead\n logger.info(\n f\"Process {self.process.pid} already terminated\"\n )\n except OSError as e:\n logger.warning(\n f\"Failed to send SIGTERM to {self.process.pid}: {e}\"\n )\n\n if killed:\n # Wait for graceful shutdown\n time.sleep(2)\n\n # Check if still running and force kill if needed\n if self.is_running():\n try:\n os.killpg(pgid, signal.SIGKILL)\n logger.info(f\"Force killed process group {pgid}\")\n except (OSError, ProcessLookupError):\n # Process group kill failed, try individual\n try:\n # Ensure pid is an integer (handle Mock objects in tests)\n if hasattr(self.process, \"pid\"):\n try:\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGKILL)\n logger.info(f\"Force killed process {pid}\")\n except (TypeError, ValueError):\n # PID is not a valid integer (might be Mock)\n pass\n except ProcessLookupError:\n pass # Already dead\n except OSError as e:\n logger.error(\n f\"Failed to force kill {self.process.pid}: {e}\"\n )\n\n except Exception as e:\n logger.error(f\"Unexpected error stopping external server: {e}\")\n\n # Close log file if we have one\n if hasattr(self, \"log_file\") and self.log_file:\n self.log_file.close()\n\n # Remove from registry\n from .process import remove_server\n\n remove_server(self)\n\n logger.info(f\"vLLM server stopped for {self.model}\")\n return True\n\n except Exception as e:\n logger.error(f\"Error stopping vLLM server: {e}\")\n return False\n\n def is_running(self) -> bool:\n \"\"\"\n Check if the server is running.\n\n Returns:\n True if server is running, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n # Check if this is an external server (detected, not started by us)\n if hasattr(self.process, \"poll\"):\n # Normal subprocess\n return self.process.poll() is None\n elif hasattr(self.process, \"pid\"):\n # External server - check if PID still exists\n try:\n import psutil\n\n return psutil.pid_exists(self.process.pid)\n except ImportError:\n # Fallback to os method\n try:\n os.kill(self.process.pid, 0)\n return True\n except (OSError, ProcessLookupError):\n return False\n\n return False\n\n def get_status(self) -> Dict[str, Any]:\n \"\"\"\n Get server status information.\n\n Returns:\n Dictionary with status information\n \"\"\"\n status = {\n \"model\": self.model,\n \"port\": self.port,\n \"running\": self.is_running(),\n \"pid\": self.process.pid if self.process else None,\n \"start_time\": self.start_time.isoformat() if self.start_time else None,\n \"log_path\": str(self.log_path) if self.log_path else None,\n }\n\n if self.is_running() and self.start_time:\n uptime = datetime.now() - self.start_time\n status[\"uptime_seconds\"] = uptime.total_seconds()\n status[\"uptime_str\"] = str(uptime).split(\".\")[0]\n\n return status\n\n def wait_for_startup(self) -> bool:\n \"\"\"\n Wait for the server to complete startup.\n\n Monitors the server logs for startup completion indicators and verifies\n via HTTP endpoint. Will wait indefinitely until either startup completes\n or the process terminates.\n\n Returns:\n True if server started successfully, False if process terminated\n \"\"\"\n import time\n\n logger.info(f\"Waiting for {self.model} server to complete startup...\")\n\n # Track if we've seen startup indicators in logs\n log_indicates_ready = False\n\n while True:\n # Check if server is still running\n if not self.is_running():\n logger.error(\n f\"Server process for {self.model} terminated during startup\"\n )\n return False\n\n # Get recent logs to check for startup completion\n recent_logs = self.get_recent_logs(50)\n\n if recent_logs and not log_indicates_ready:\n # Check for startup completion indicators\n for log in recent_logs:\n log_lower = log.lower()\n # Look for the explicit \"Application startup complete\" message\n if \"application startup complete\" in log_lower:\n logger.debug(f\"Server {self.model} startup detected in logs\")\n log_indicates_ready = True\n break\n\n # Also check for other ready indicators as fallback\n if any(\n indicator in log_lower\n for indicator in [\n \"uvicorn running on\",\n \"started server process\",\n \"server is ready\",\n \"api server started\",\n ]\n ):\n logger.debug(\n f\"Server {self.model} startup detected via ready indicator\"\n )\n log_indicates_ready = True\n break\n\n # If logs indicate ready, verify via HTTP\n if log_indicates_ready:\n # Try to verify server is actually ready via HTTP\n port = self.config.get(\"port\")\n if port:\n try:\n import httpx\n\n with httpx.Client() as client:\n # Try /v1/models endpoint first (most reliable)\n response = client.get(\n f\"http://localhost:{port}/v1/models\", timeout=5.0\n )\n if response.status_code == 200:\n logger.info(\n f\"Server {self.model} startup complete \"\n \"(verified via HTTP)\"\n )\n return True\n except httpx.ConnectError:\n # Server not ready yet, continue waiting\n logger.debug(\n f\"Server {self.model} not accepting connections yet\"\n )\n except Exception as e:\n # Log but continue, might be network issue\n logger.debug(f\"HTTP verification failed: {e}\")\n else:\n # No port configured, trust the logs\n logger.info(\n f\"Server {self.model} startup complete (no port for verification)\"\n )\n return True\n\n # Small sleep to avoid busy waiting\n time.sleep(0.5)\n\n def get_recent_logs(self, n: int = 20) -> List[str]:\n \"\"\"\n Get recent log lines from the server output.\n\n Retrieves the most recent log lines from either the in-memory queue\n or the log file on disk. This method ensures logs are available even\n after the monitoring thread has processed them.\n\n Args:\n n: Number of recent lines to return (default: 20)\n\n Returns:\n List of recent log lines, with the most recent last\n \"\"\"\n # Update recent logs from queue\n self._update_recent_logs_from_queue()\n\n # Return from memory if available\n if self._recent_logs:\n return self._recent_logs[-n:]\n\n # Fallback to reading from file\n return self._read_logs_from_file(n)\n\n def _update_recent_logs_from_queue(self) -> None:\n \"\"\"\n Update the recent logs cache from the log queue.\n\n Drains all available log lines from the queue and adds them\n to the recent logs cache, maintaining a maximum of 100 lines.\n \"\"\"\n temp_logs = []\n\n # Get all available logs from queue (don't block)\n while not self.log_queue.empty():\n try:\n log_line = self.log_queue.get_nowait()\n temp_logs.append(log_line)\n except Empty:\n break\n\n if temp_logs:\n self._recent_logs.extend(temp_logs)\n # Keep only the last 100 logs in memory to prevent unbounded growth\n self._recent_logs = self._recent_logs[-100:]\n\n def _read_logs_from_file(self, n: int) -> List[str]:\n \"\"\"\n Read recent log lines from the log file.\n\n Args:\n n: Number of lines to read\n\n Returns:\n List of log lines from file\n \"\"\"\n if not (self.log_path and self.log_path.exists()):\n return []\n\n try:\n with open(self.log_path, \"r\") as f:\n file_logs = f.readlines()\n if file_logs:\n # Get last n lines, strip them\n logs = [line.strip() for line in file_logs[-n:]]\n # Update recent logs cache\n self._recent_logs = logs[-100:]\n return logs\n except Exception as e:\n logger.debug(f\"Error reading log file: {e}\")\n\n return []\n\n def restart(self) -> bool:\n \"\"\"\n Restart the server with the same configuration.\n\n Returns:\n True if restart successful, False otherwise\n \"\"\"\n logger.info(f\"Restarting vLLM server for {self.model}\")\n\n # Stop if running\n if self.is_running():\n self.stop()\n time.sleep(2) # Wait a bit before restarting\n\n # Start again\n return self.start()\n\n def health_check(self) -> bool:\n \"\"\"\n Perform a health check on the server.\n\n Returns:\n True if server is healthy, False otherwise\n \"\"\"\n if not self.is_running():\n return False\n\n try:\n import requests\n\n # Try to connect to the server\n response = requests.get(f\"http://localhost:{self.port}/health\", timeout=5)\n\n return response.status_code == 200\n\n except Exception:\n # If requests fails, just check process\n return self.is_running()", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 27979}, "tests/proxy/test_integration.py::119": {"resolved_imports": ["src/vllm_cli/proxy/config.py", "src/vllm_cli/proxy/manager.py", "src/vllm_cli/proxy/models.py", "src/vllm_cli/proxy/server_process.py"], "used_names": ["MagicMock", "ProxyConfigManager", "ProxyManager", "patch"], "enclosing_function": "test_proxy_manager_full_lifecycle", "extracted_code": "# Source: src/vllm_cli/proxy/config.py\nclass ProxyConfigManager:\n \"\"\"\n Manages proxy server configuration including persistence and validation.\n \"\"\"\n\n def __init__(self):\n \"\"\"Initialize the proxy configuration manager.\"\"\"\n self.config_dir = Path.home() / \".config\" / \"vllm-cli\"\n # Default configuration file path - used as fallback when no path specified\n # Also maintains backward compatibility with existing configurations\n self.proxy_config_file = self.config_dir / \"proxy_config.yaml\"\n self.proxy_configs_dir = self.config_dir / \"proxy_configs\"\n self.config_dir.mkdir(parents=True, exist_ok=True)\n self.proxy_configs_dir.mkdir(parents=True, exist_ok=True)\n\n def load_config(self, config_path: Optional[Path] = None) -> ProxyConfig:\n \"\"\"\n Load proxy configuration from file.\n\n Args:\n config_path: Path to configuration file (uses default if not provided)\n\n Returns:\n ProxyConfig instance\n \"\"\"\n config_file = config_path or self.proxy_config_file\n\n if not config_file.exists():\n logger.info(f\"No config file found at {config_file}, using defaults\")\n return self.get_default_config()\n\n try:\n with open(config_file, \"r\") as f:\n if config_file.suffix in [\".yaml\", \".yml\"]:\n config_dict = yaml.safe_load(f)\n else:\n config_dict = json.load(f)\n\n return self._parse_config(config_dict)\n\n except Exception as e:\n logger.error(f\"Failed to load config from {config_file}: {e}\")\n return self.get_default_config()\n\n def save_config(self, config: ProxyConfig, config_path: Optional[Path] = None):\n \"\"\"\n Save proxy configuration to file.\n\n Args:\n config: ProxyConfig to save\n config_path: Path to save to (uses default if not provided)\n \"\"\"\n config_file = config_path or self.proxy_config_file\n\n try:\n config_dict = {\n \"proxy\": {\n \"host\": config.host,\n \"port\": config.port,\n \"enable_cors\": config.enable_cors,\n \"enable_metrics\": config.enable_metrics,\n \"log_requests\": config.log_requests,\n },\n \"models\": [\n {\n \"name\": model.name,\n \"model_path\": model.model_path,\n \"gpu_ids\": model.gpu_ids,\n \"port\": model.port,\n \"profile\": model.profile,\n \"config_overrides\": model.config_overrides,\n \"enabled\": model.enabled,\n \"loading_priority\": model.loading_priority,\n }\n for model in config.models\n ],\n }\n\n with open(config_file, \"w\") as f:\n if config_file.suffix in [\".yaml\", \".yml\"]:\n yaml.safe_dump(config_dict, f, default_flow_style=False)\n else:\n json.dump(config_dict, f, indent=2)\n\n logger.info(f\"Saved proxy configuration to {config_file}\")\n\n except Exception as e:\n logger.error(f\"Failed to save config to {config_file}: {e}\")\n\n def save_named_config(self, config: ProxyConfig, name: str):\n \"\"\"\n Save proxy configuration with a specific name.\n\n Args:\n config: ProxyConfig to save\n name: Name for the configuration\n \"\"\"\n # Sanitize name for filesystem\n safe_name = \"\".join(c if c.isalnum() or c in \"_-\" else \"_\" for c in name)\n config_file = self.proxy_configs_dir / f\"{safe_name}.yaml\"\n\n self.save_config(config, config_file)\n logger.info(f\"Saved proxy configuration as '{name}'\")\n\n def load_named_config(self, name: str) -> Optional[ProxyConfig]:\n \"\"\"\n Load a named proxy configuration.\n\n Args:\n name: Name of the configuration to load\n\n Returns:\n ProxyConfig if found, None otherwise\n \"\"\"\n safe_name = \"\".join(c if c.isalnum() or c in \"_-\" else \"_\" for c in name)\n config_file = self.proxy_configs_dir / f\"{safe_name}.yaml\"\n\n if not config_file.exists():\n logger.error(f\"Configuration '{name}' not found\")\n return None\n\n return self.load_config(config_file)\n\n def list_saved_configs(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"\n List all saved proxy configurations.\n\n Returns:\n Dictionary mapping config names to their summaries\n \"\"\"\n configs = {}\n\n # Check new named configs directory\n for config_file in self.proxy_configs_dir.glob(\"*.yaml\"):\n name = config_file.stem\n try:\n config = self.load_config(config_file)\n if config:\n configs[name] = {\n \"file\": str(config_file),\n \"models\": len(config.models),\n \"port\": config.port,\n \"model_names\": [m.name for m in config.models][\n :3\n ], # First 3 models\n }\n except Exception as e:\n logger.warning(f\"Failed to load config {name}: {e}\")\n\n # Also check legacy default location\n if self.proxy_config_file.exists():\n try:\n config = self.load_config(self.proxy_config_file)\n if config:\n configs[\"default\"] = {\n \"file\": str(self.proxy_config_file),\n \"models\": len(config.models),\n \"port\": config.port,\n \"model_names\": [m.name for m in config.models][:3],\n }\n except Exception:\n pass\n\n return configs\n\n def delete_named_config(self, name: str) -> bool:\n \"\"\"\n Delete a named proxy configuration.\n\n Args:\n name: Name of the configuration to delete\n\n Returns:\n True if deleted successfully\n \"\"\"\n safe_name = \"\".join(c if c.isalnum() or c in \"_-\" else \"_\" for c in name)\n config_file = self.proxy_configs_dir / f\"{safe_name}.yaml\"\n\n if config_file.exists():\n try:\n config_file.unlink()\n logger.info(f\"Deleted configuration '{name}'\")\n return True\n except Exception as e:\n logger.error(f\"Failed to delete configuration '{name}': {e}\")\n return False\n else:\n logger.warning(f\"Configuration '{name}' not found\")\n return False\n\n def get_default_config(self) -> ProxyConfig:\n \"\"\"\n Get default proxy configuration.\n\n Returns:\n Default ProxyConfig instance\n \"\"\"\n return ProxyConfig(\n host=\"0.0.0.0\", # nosec B104\n port=8000,\n models=[],\n enable_cors=True,\n enable_metrics=True,\n log_requests=False,\n )\n\n def _parse_config(self, config_dict: Dict[str, Any]) -> ProxyConfig:\n \"\"\"\n Parse configuration dictionary into ProxyConfig.\n\n Args:\n config_dict: Configuration dictionary\n\n Returns:\n ProxyConfig instance\n \"\"\"\n proxy_settings = config_dict.get(\"proxy\", {})\n models_list = config_dict.get(\"models\", [])\n\n models = []\n for model_dict in models_list:\n try:\n models.append(ModelConfig(**model_dict))\n except Exception as e:\n logger.warning(f\"Failed to parse model config: {e}\")\n\n return ProxyConfig(\n host=proxy_settings.get(\"host\", \"0.0.0.0\"), # nosec B104\n port=proxy_settings.get(\"port\", 8000),\n models=models,\n enable_cors=proxy_settings.get(\"enable_cors\", True),\n enable_metrics=proxy_settings.get(\"enable_metrics\", True),\n log_requests=proxy_settings.get(\"log_requests\", False),\n )\n\n def validate_config(self, config: ProxyConfig) -> List[str]:\n \"\"\"\n Validate proxy configuration.\n\n Args:\n config: ProxyConfig to validate\n\n Returns:\n List of validation errors (empty if valid)\n \"\"\"\n errors = []\n\n # Check proxy port\n if not 1 <= config.port <= 65535:\n errors.append(f\"Invalid proxy port: {config.port}\")\n\n # Check for port conflicts\n used_ports = {config.port}\n for model in config.models:\n if model.port in used_ports:\n errors.append(f\"Port {model.port} is used by multiple services\")\n used_ports.add(model.port)\n\n # Check model names are unique\n model_names = [m.name for m in config.models]\n if len(model_names) != len(set(model_names)):\n errors.append(\"Model names must be unique\")\n\n return errors\n\n def create_example_config(self) -> ProxyConfig:\n \"\"\"\n Create an example proxy configuration.\n\n Returns:\n Example ProxyConfig instance\n \"\"\"\n return ProxyConfig(\n host=\"0.0.0.0\", # nosec B104\n port=8000,\n models=[\n ModelConfig(\n name=\"llama-3-8b\",\n model_path=\"meta-llama/Meta-Llama-3-8B-Instruct\",\n gpu_ids=[0],\n port=8001,\n profile=\"standard\",\n enabled=True,\n ),\n ModelConfig(\n name=\"mistral-7b\",\n model_path=\"mistralai/Mistral-7B-Instruct-v0.2\",\n gpu_ids=[1],\n port=8002,\n profile=\"performance\",\n enabled=True,\n ),\n ModelConfig(\n name=\"gemma-2b\",\n model_path=\"google/gemma-2b\",\n gpu_ids=[2],\n port=8003,\n profile=\"memory-optimized\",\n enabled=False, # Disabled by default\n ),\n ],\n enable_cors=True,\n enable_metrics=True,\n log_requests=False,\n )\n\n def export_config(self, config: ProxyConfig, export_path: Path):\n \"\"\"\n Export configuration to a file.\n\n Args:\n config: ProxyConfig to export\n export_path: Path to export to\n \"\"\"\n self.save_config(config, export_path)\n logger.info(f\"Exported configuration to {export_path}\")\n\n def import_config(self, import_path: Path) -> ProxyConfig:\n \"\"\"\n Import configuration from a file.\n\n Args:\n import_path: Path to import from\n\n Returns:\n Imported ProxyConfig instance\n \"\"\"\n config = self.load_config(import_path)\n logger.info(f\"Imported configuration from {import_path}\")\n return config\n\n\n# Source: src/vllm_cli/proxy/manager.py\nclass ProxyManager:\n \"\"\"\n Manages the lifecycle of multiple vLLM servers and the proxy server.\n \"\"\"\n\n def __init__(self, config: Optional[ProxyConfig] = None):\n \"\"\"\n Initialize the proxy manager.\n\n Args:\n config: Proxy configuration (uses defaults if not provided)\n \"\"\"\n self.proxy_config = config or ProxyConfig()\n self.proxy_process: Optional[ProxyServerProcess] = None\n self.vllm_servers: Dict[str, VLLMServer] = {}\n self.config_manager = ConfigManager()\n\n def _proxy_api_request(\n self,\n method: str,\n endpoint: str,\n json_data: Optional[Dict] = None,\n timeout: float = 5.0,\n ) -> Optional[Any]:\n \"\"\"\n Helper method for making HTTP requests to the proxy API.\n\n Args:\n method: HTTP method (POST, DELETE, GET)\n endpoint: API endpoint path\n json_data: Optional JSON data for request body\n timeout: Request timeout in seconds\n\n Returns:\n Response object if successful, None if failed\n \"\"\"\n try:\n import httpx\n\n url = f\"http://localhost:{self.proxy_config.port}{endpoint}\"\n with httpx.Client() as client:\n if method == \"POST\":\n response = client.post(url, json=json_data, timeout=timeout)\n elif method == \"DELETE\":\n response = client.delete(url, timeout=timeout)\n elif method == \"GET\":\n response = client.get(url, timeout=timeout)\n else:\n logger.error(f\"Unsupported HTTP method: {method}\")\n return None\n\n if response.status_code == 200:\n return response\n else:\n logger.warning(\n f\"API request failed: {method} {endpoint} - \"\n f\"{response.status_code}: {response.text}\"\n )\n return None\n\n except Exception as e:\n logger.warning(f\"API request error: {method} {endpoint} - {e}\")\n return None\n\n def start_proxy(self) -> bool:\n \"\"\"\n Start the proxy server.\n\n Returns:\n True if proxy started successfully\n \"\"\"\n try:\n # Create proxy server process instance\n self.proxy_process = ProxyServerProcess(self.proxy_config)\n\n # Start proxy as a subprocess\n if not self.proxy_process.start():\n logger.error(\"Failed to start proxy server process\")\n return False\n\n # Give it a moment to fully initialize\n time.sleep(2)\n\n # Register all running models with the proxy\n # Note: We'll need to update this to work with subprocess\n # For now, models will register when they start\n\n logger.info(\n f\"Proxy server started on \"\n f\"{self.proxy_config.host}:{self.proxy_config.port}\"\n )\n return True\n\n except Exception as e:\n logger.error(f\"Failed to start proxy server: {e}\")\n return False\n\n def stop_proxy(self):\n \"\"\"Stop the proxy server and all vLLM instances.\"\"\"\n logger.info(\"Stopping proxy server and all model servers...\")\n\n # Stop all vLLM servers\n for model_name in list(self.vllm_servers.keys()):\n self.stop_model(model_name)\n\n # Stop proxy server process\n if self.proxy_process:\n self.proxy_process.stop()\n self.proxy_process = None\n logger.info(\"Proxy server stopped\")\n\n def start_model(self, model_config: ModelConfig) -> bool:\n \"\"\"\n Start a vLLM server for a specific model.\n\n Args:\n model_config: Configuration for the model\n\n Returns:\n True if server started successfully\n \"\"\"\n try:\n # Check if model is already running\n if model_config.name in self.vllm_servers:\n logger.warning(f\"Model '{model_config.name}' is already running\")\n return False\n\n # Build vLLM server configuration\n vllm_config = self._build_vllm_config(model_config)\n\n # Pre-register with proxy if it's running\n if self.proxy_process and self.proxy_process.is_running():\n pre_register_data = {\n \"port\": model_config.port,\n \"gpu_ids\": model_config.gpu_ids,\n \"config_name\": model_config.name,\n }\n\n response = self._proxy_api_request(\n \"POST\", \"/proxy/pre_register\", pre_register_data\n )\n if response:\n logger.info(\n f\"Pre-registered model '{model_config.name}' with proxy\"\n )\n else:\n logger.warning(\n f\"Failed to pre-register model '{model_config.name}' with proxy\"\n )\n\n # Create and start vLLM server\n server = VLLMServer(vllm_config)\n if not server.start():\n logger.error(f\"Failed to start vLLM server for '{model_config.name}'\")\n return False\n\n # Store server reference\n self.vllm_servers[model_config.name] = server\n\n logger.info(\n f\"Started vLLM server process for '{model_config.name}' \"\n f\"on port {model_config.port} using GPUs {model_config.gpu_ids}\"\n )\n\n # Note: Registration with proxy will happen after startup completes\n # Registration happens during wait_and_register_model()\n\n return True\n\n except Exception as e:\n logger.error(f\"Failed to start model '{model_config.name}': {e}\")\n return False\n\n def wait_and_register_model(self, model_config: ModelConfig) -> bool:\n \"\"\"\n Wait for a model to complete startup and trigger proxy refresh.\n\n Args:\n model_config: Configuration for the model\n\n Returns:\n True if model started and registered successfully\n \"\"\"\n if model_config.name not in self.vllm_servers:\n logger.error(f\"Model '{model_config.name}' not found in servers\")\n return False\n\n server = self.vllm_servers[model_config.name]\n\n # Wait for server to complete startup\n if not server.wait_for_startup():\n logger.error(f\"Server '{model_config.name}' failed to complete startup\")\n # Clean up the failed server\n server.stop()\n del self.vllm_servers[model_config.name]\n return False\n\n # Trigger proxy refresh to verify and activate the model\n if self.proxy_process and self.proxy_process.is_running():\n # Call refresh to verify the pre-registered model\n response = self._proxy_api_request(\n \"POST\", \"/proxy/refresh_models\", timeout=10.0\n )\n if response:\n try:\n result = response.json()\n summary = result.get(\"summary\", {})\n if summary.get(\"registered\", 0) > 0:\n logger.info(\n f\"Model '{model_config.name}' successfully activated \"\n f\"on port {model_config.port}\"\n )\n return True\n else:\n logger.warning(\n f\"Model '{model_config.name}' started but \"\n f\"not activated in proxy\"\n )\n return True # Model is running, just not registered\n except Exception as e:\n logger.error(f\"Failed to parse refresh response: {e}\")\n return True # Model is running\n else:\n logger.warning(\n f\"Failed to refresh proxy after starting \"\n f\"model '{model_config.name}'\"\n )\n return True # Model is running even if refresh failed\n\n logger.info(f\"Model '{model_config.name}' is ready\")\n return True\n\n def refresh_model_registrations(self) -> Dict[str, Any]:\n \"\"\"\n Refresh model registrations with the proxy.\n\n Calls the proxy's refresh endpoint to verify all models in the registry.\n\n Returns:\n Dictionary with registration results\n \"\"\"\n if not self.proxy_process or not self.proxy_process.is_running():\n logger.warning(\"Proxy is not running, cannot refresh registrations\")\n return {\"status\": \"error\", \"message\": \"Proxy server is not running\"}\n\n # Call the refresh endpoint\n response = self._proxy_api_request(\n \"POST\", \"/proxy/refresh_models\", timeout=10.0\n )\n\n if response:\n try:\n result = response.json()\n summary = result.get(\"summary\", {})\n logger.info(\n f\"Model registration refresh completed: \"\n f\"{summary.get('registered', 0)} newly registered, \"\n f\"{summary.get('failed', 0)} newly failed, \"\n f\"{summary.get('already_available', 0)} already available, \"\n f\"{summary.get('removed', 0)} removed\"\n )\n return result\n except Exception as e:\n logger.error(f\"Failed to parse refresh response: {e}\")\n return {\"status\": \"error\", \"message\": f\"Failed to parse response: {e}\"}\n else:\n logger.error(\"Failed to refresh model registrations\")\n return {\n \"status\": \"error\",\n \"message\": \"Failed to connect to proxy refresh endpoint\",\n }\n\n def get_proxy_registry_status(self) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get full model registry status from proxy.\n\n Returns:\n Dictionary containing proxy status and all registered models,\n or None if proxy is not running\n \"\"\"\n if not self.proxy_process or not self.proxy_process.is_running():\n logger.warning(\"Proxy is not running, cannot get registry status\")\n return None\n\n response = self._proxy_api_request(\"GET\", \"/proxy/registry\")\n if response:\n try:\n return response.json()\n except Exception as e:\n logger.error(f\"Failed to parse proxy status response: {e}\")\n return None\n return None\n\n def sleep_model(self, model_name: str, level: int = 1) -> bool:\n \"\"\"\n Put a model to sleep, freeing GPU memory but keeping the port.\n Runs asynchronously and returns immediately.\n\n Args:\n model_name: Name of the model to sleep\n level: Sleep level (1=offload weights, 2=discard weights)\n\n Returns:\n True if sleep request was initiated successfully\n \"\"\"\n if model_name not in self.vllm_servers:\n logger.warning(f\"Model '{model_name}' is not running\")\n return False\n\n server = self.vllm_servers[model_name]\n port = server.port\n\n try:\n import threading\n\n import httpx\n\n def sleep_thread():\n try:\n # Use 10 minute timeout for very slow operations\n client = httpx.Client(timeout=600.0)\n logger.info(\n f\"Sending sleep request to model '{model_name}' \"\n f\"(level {level})...\"\n )\n response = client.post(\n f\"http://localhost:{port}/sleep?level={level}\"\n )\n client.close()\n\n if response.status_code == 200:\n logger.info(\n f\"Model '{model_name}' successfully put to sleep \"\n f\"(level {level})\"\n )\n\n # Update proxy registry state\n if self.proxy_process and self.proxy_process.is_running():\n state_data = {\n \"port\": port,\n \"state\": \"sleeping\",\n \"sleep_level\": level,\n }\n self._proxy_api_request(\"POST\", \"/proxy/state\", state_data)\n else:\n logger.error(\n f\"Failed to sleep model '{model_name}': \"\n f\"HTTP {response.status_code}\"\n )\n\n except Exception as e:\n logger.error(f\"Failed to sleep model '{model_name}': {e}\")\n\n # Start in background thread\n thread = threading.Thread(target=sleep_thread, daemon=True)\n thread.start()\n logger.info(f\"Sleep operation initiated for '{model_name}'\")\n return True\n\n except Exception as e:\n logger.error(f\"Failed to initiate sleep for '{model_name}': {e}\")\n return False\n\n def wake_model(self, model_name: str) -> bool:\n \"\"\"\n Wake up a sleeping model.\n Runs asynchronously and returns immediately.\n\n Args:\n model_name: Name of the model to wake\n\n Returns:\n True if wake request was initiated successfully\n \"\"\"\n if model_name not in self.vllm_servers:\n logger.warning(f\"Model '{model_name}' is not running\")\n return False\n\n server = self.vllm_servers[model_name]\n port = server.port\n\n try:\n import threading\n\n import httpx\n\n def wake_thread():\n try:\n # Use 10 minute timeout for very slow operations\n client = httpx.Client(timeout=600.0)\n logger.info(f\"Sending wake-up request to model '{model_name}'...\")\n response = client.post(f\"http://localhost:{port}/wake_up\")\n client.close()\n\n # Accept both 200 (OK) and 202 (Accepted) as success\n if response.status_code in [200, 202]:\n logger.info(f\"Model '{model_name}' successfully woken up\")\n\n # Update proxy registry state\n if self.proxy_process and self.proxy_process.is_running():\n state_data = {\n \"port\": port,\n \"state\": \"running\",\n \"sleep_level\": 0,\n }\n self._proxy_api_request(\"POST\", \"/proxy/state\", state_data)\n else:\n logger.error(\n f\"Failed to wake model '{model_name}': \"\n f\"HTTP {response.status_code}\"\n )\n\n except Exception as e:\n logger.error(f\"Failed to wake model '{model_name}': {e}\")\n\n # Start in background thread\n thread = threading.Thread(target=wake_thread, daemon=True)\n thread.start()\n logger.info(f\"Wake operation initiated for '{model_name}'\")\n return True\n\n except Exception as e:\n logger.error(f\"Failed to initiate wake for '{model_name}': {e}\")\n return False\n\n def is_sleeping(self, model_name: str) -> bool:\n \"\"\"\n Check if a model is sleeping.\n\n Args:\n model_name: Name of the model to check\n\n Returns:\n True if model is sleeping\n \"\"\"\n if model_name not in self.vllm_servers:\n return False\n\n server = self.vllm_servers[model_name]\n port = server.port\n\n try:\n import httpx\n\n client = httpx.Client(timeout=5.0)\n response = client.get(f\"http://localhost:{port}/is_sleeping\")\n client.close()\n\n if response.status_code == 200:\n data = response.json()\n return data.get(\"is_sleeping\", False)\n except Exception:\n pass\n\n return False\n\n def stop_model(self, model_name: str) -> bool:\n \"\"\"\n Stop a vLLM server for a specific model.\n\n Args:\n model_name: Name of the model to stop\n\n Returns:\n True if server stopped successfully\n \"\"\"\n if model_name not in self.vllm_servers:\n logger.warning(f\"Model '{model_name}' is not running\")\n return False\n\n try:\n # Get the port before stopping\n server = self.vllm_servers[model_name]\n port = server.port\n\n # Stop the vLLM server\n server.stop()\n\n # Remove from tracking\n del self.vllm_servers[model_name]\n\n # Unregister from proxy if it's running\n if self.proxy_process and self.proxy_process.is_running():\n # Use the new registry endpoint with port\n if self._proxy_api_request(\"DELETE\", f\"/proxy/models/{port}\"):\n logger.debug(f\"Unregistered model on port {port} from proxy\")\n\n logger.info(f\"Stopped vLLM server for '{model_name}'\")\n return True\n\n except Exception as e:\n logger.error(f\"Failed to stop model '{model_name}': {e}\")\n return False\n\n def unregister_model_from_proxy(self, port: int) -> bool:\n \"\"\"\n Unregister a model from the proxy registry by port.\n This is useful for cleaning up stopped models.\n\n Args:\n port: Port number of the model to unregister\n\n Returns:\n True if successfully unregistered or proxy not running\n \"\"\"\n if self.proxy_process and self.proxy_process.is_running():\n if self._proxy_api_request(\"DELETE\", f\"/proxy/models/{port}\"):\n logger.debug(f\"Unregistered model on port {port} from proxy\")\n return True\n return False\n return True # If proxy not running, consider it success\n\n def start_all_models_no_wait(self) -> int:\n \"\"\"\n Start all model processes without waiting for startup completion.\n\n This method starts all model servers concurrently and returns immediately,\n allowing the caller to monitor startup progress in real-time.\n\n Returns:\n Number of model processes successfully launched\n \"\"\"\n started_count = 0\n for model_config in self.proxy_config.models:\n if model_config.enabled:\n if self.start_model(model_config):\n started_count += 1\n # Small delay to avoid resource conflicts\n time.sleep(0.5)\n\n return started_count\n\n def start_models_with_priorities(self):\n \"\"\"\n Start models sequentially based on loading_priority.\n\n Models are grouped by priority (lower numbers first). Models within\n the same priority group start in parallel. This is a generator that\n yields each priority group after starting its models, allowing the\n UI layer to monitor startup progress with live feedback.\n\n This is useful for GPU-shared deployments where models with low\n gpu-memory-utilization should load first to claim KV cache space.\n\n Yields:\n Dictionary for each priority group:\n - priority: Priority number (or float('inf') for None)\n - priority_label: Human-readable priority label\n - models: List of ModelConfig instances in this group\n - started_models: List of ModelConfig instances that started successfully\n - failed_models: List of model names that failed to start\n - group_index: Current group number (1-indexed)\n - total_groups: Total number of priority groups\n - total_models: Total number of models across all groups\n \"\"\"\n from collections import defaultdict\n\n # Group models by loading_priority\n priority_groups = defaultdict(list)\n for model_config in self.proxy_config.models:\n if model_config.enabled:\n priority = model_config.loading_priority\n # Use a large number for None priority (load last)\n effective_priority = priority if priority is not None else float(\"inf\")\n priority_groups[effective_priority].append(model_config)\n\n # Sort priority groups (ascending order)\n sorted_priorities = sorted(priority_groups.keys())\n\n total_models = sum(len(models) for models in priority_groups.values())\n\n logger.info(\n f\"Starting {total_models} models in {len(sorted_priorities)} \"\n f\"priority group(s)\"\n )\n\n # Process each priority group sequentially\n for priority_idx, priority in enumerate(sorted_priorities, 1):\n models = priority_groups[priority]\n priority_label = (\n f\"Priority {int(priority)}\"\n if priority != float(\"inf\")\n else \"No Priority (Parallel)\"\n )\n\n logger.info(\n f\"Starting priority group {priority_idx}/{len(sorted_priorities)}: \"\n f\"{priority_label} ({len(models)} model(s))\"\n )\n\n # Start all models in this priority group (non-blocking)\n group_started = []\n group_failed = []\n\n for model_config in models:\n if self.start_model(model_config):\n group_started.append(model_config)\n logger.info(\n f\"Started {model_config.name} (port {model_config.port})\"\n )\n # Small delay to avoid resource conflicts\n time.sleep(0.5)\n else:\n group_failed.append(model_config.name)\n logger.error(f\"Failed to start {model_config.name}\")\n\n # Yield this group for UI monitoring (non-blocking)\n yield {\n \"priority\": priority,\n \"priority_label\": priority_label,\n \"models\": models,\n \"started_models\": group_started,\n \"failed_models\": group_failed,\n \"group_index\": priority_idx,\n \"total_groups\": len(sorted_priorities),\n \"total_models\": total_models,\n }\n\n # Control returns here after UI finishes monitoring this group\n\n def _build_vllm_config(self, model_config: ModelConfig) -> Dict[str, Any]:\n \"\"\"\n Build vLLM server configuration from model configuration.\n\n Args:\n model_config: Model configuration\n\n Returns:\n vLLM server configuration dictionary\n \"\"\"\n # Start with profile configuration if specified\n config = {}\n if model_config.profile:\n profile = self.config_manager.get_profile(model_config.profile)\n if profile:\n config = profile.get(\"config\", {}).copy()\n\n # Set model, port, and host\n config[\"model\"] = model_config.model_path\n config[\"port\"] = model_config.port\n config[\"host\"] = self.proxy_config.host # Use host from proxy configuration\n\n # Enable sleep mode for better resource management\n config[\"enable_sleep_mode\"] = True\n\n # Handle GPU assignment\n if model_config.gpu_ids:\n # Set CUDA_VISIBLE_DEVICES via device field\n config[\"device\"] = \",\".join(str(gpu) for gpu in model_config.gpu_ids)\n\n num_gpus = len(model_config.gpu_ids)\n\n # For single GPU assignment, override any parallel settings from profile\n if num_gpus == 1:\n # Remove parallel configuration that conflicts with single GPU\n conflicting_settings = [\n \"tensor_parallel_size\",\n \"pipeline_parallel_size\",\n \"distributed_executor_backend\",\n ]\n\n removed_settings = []\n for setting in conflicting_settings:\n if setting in config:\n removed_settings.append(f\"{setting}={config[setting]}\")\n del config[setting]\n\n # Disable expert parallelism for single GPU\n if config.get(\"enable_expert_parallel\"):\n removed_settings.append(\"enable_expert_parallel=True\")\n config[\"enable_expert_parallel\"] = False\n\n if removed_settings:\n logger.warning(\n f\"Model '{model_config.name}' assigned single GPU. \"\n f\"Overriding profile settings: {', '.join(removed_settings)}\"\n )\n\n elif num_gpus > 1:\n # For multi-GPU, set tensor_parallel_size if not already set\n if \"tensor_parallel_size\" not in config:\n config[\"tensor_parallel_size\"] = num_gpus\n elif config[\"tensor_parallel_size\"] > num_gpus:\n # Adjust if profile expects more GPUs than assigned\n logger.warning(\n f\"Model '{model_config.name}': Adjusting tensor_parallel_size \"\n f\"from {config['tensor_parallel_size']} to {num_gpus} \"\n f\"(assigned GPUs)\"\n )\n config[\"tensor_parallel_size\"] = num_gpus\n\n # Apply any config overrides\n config.update(model_config.config_overrides)\n\n return config\n\n def get_status(self) -> Dict[str, Any]:\n \"\"\"\n Get status of proxy and all model servers.\n\n Returns:\n Status dictionary\n \"\"\"\n status = {\n \"proxy_running\": self.proxy_process and self.proxy_process.is_running(),\n \"proxy_host\": self.proxy_config.host,\n \"proxy_port\": self.proxy_config.port,\n \"models\": [],\n }\n\n for model_name, server in self.vllm_servers.items():\n model_status = {\n \"name\": model_name,\n \"running\": server.is_running(),\n \"port\": server.port,\n \"uptime\": None,\n }\n\n if server.is_running() and server.start_time:\n uptime = time.time() - server.start_time.timestamp()\n model_status[\"uptime\"] = uptime\n\n status[\"models\"].append(model_status)\n\n return status\n\n def reload_model(self, model_name: str) -> bool:\n \"\"\"\n Reload a model (stop and start again).\n\n Args:\n model_name: Name of the model to reload\n\n Returns:\n True if reload successful\n \"\"\"\n # Find the model config\n model_config = None\n for config in self.proxy_config.models:\n if config.name == model_name:\n model_config = config\n break\n\n if not model_config:\n logger.error(f\"Model '{model_name}' not found in configuration\")\n return False\n\n # Stop if running\n if model_name in self.vllm_servers:\n self.stop_model(model_name)\n time.sleep(2) # Wait before restarting\n\n # Start the model\n if not self.start_model(model_config):\n return False\n\n # Wait for startup and register\n return self.wait_and_register_model(model_config)\n\n def allocate_gpus_automatically(self) -> List[ModelConfig]:\n \"\"\"\n Automatically allocate GPUs to models based on available resources.\n\n Returns:\n List of model configurations with GPU allocations\n \"\"\"\n from ..system import get_gpu_info\n\n # Get available GPUs\n gpu_info = get_gpu_info()\n if not gpu_info:\n logger.warning(\"No GPUs available for allocation\")\n return []\n\n num_gpus = len(gpu_info)\n models = self.proxy_config.models\n\n # Simple allocation strategy: distribute GPUs evenly\n allocated_configs = []\n\n if len(models) <= num_gpus:\n # Each model gets at least one GPU\n gpus_per_model = num_gpus // len(models)\n remaining_gpus = num_gpus % len(models)\n\n gpu_index = 0\n for i, model in enumerate(models):\n num_gpus_for_model = gpus_per_model\n if i < remaining_gpus:\n num_gpus_for_model += 1\n\n model.gpu_ids = list(range(gpu_index, gpu_index + num_gpus_for_model))\n gpu_index += num_gpus_for_model\n\n # Allocate port if not specified\n if not model.port:\n model.port = get_next_available_port(8001 + i)\n\n allocated_configs.append(model)\n else:\n # More models than GPUs - some models won't be allocated\n logger.warning(\n f\"More models ({len(models)}) than GPUs ({num_gpus}). \"\n f\"Only first {num_gpus} models will be allocated.\"\n )\n for i in range(num_gpus):\n models[i].gpu_ids = [i]\n if not models[i].port:\n models[i].port = get_next_available_port(8001 + i)\n allocated_configs.append(models[i])\n\n return allocated_configs\n\n def _get_model_config_by_name(self, model_name: str) -> Optional[ModelConfig]:\n \"\"\"\n Get model configuration by model name.\n\n Args:\n model_name: Name of the model\n\n Returns:\n ModelConfig if found, None otherwise\n \"\"\"\n for model_config in self.proxy_config.models:\n if model_config.name == model_name:\n return model_config\n return None\n\n @classmethod\n def from_config_file(cls, config_path: Path) -> \"ProxyManager\":\n \"\"\"\n Create ProxyManager from a configuration file.\n\n Args:\n config_path: Path to configuration file (YAML or JSON)\n\n Returns:\n ProxyManager instance\n \"\"\"\n import json\n\n import yaml\n\n with open(config_path, \"r\") as f:\n if config_path.suffix in [\".yaml\", \".yml\"]:\n config_dict = yaml.safe_load(f)\n else:\n config_dict = json.load(f)\n\n # Parse proxy configuration\n proxy_config = ProxyConfig(**config_dict.get(\"proxy\", {}))\n\n # Parse model configurations\n models = []\n for model_dict in config_dict.get(\"models\", []):\n models.append(ModelConfig(**model_dict))\n proxy_config.models = models\n\n return cls(proxy_config)", "n_imports_parsed": 9, "n_files_resolved": 4, "n_chars_extracted": 42411}, "tests/proxy/test_models.py::162": {"resolved_imports": ["src/vllm_cli/proxy/models.py"], "used_names": ["ModelConfig", "ProxyConfig"], "enclosing_function": "test_proxy_config_serialization", "extracted_code": "# Source: src/vllm_cli/proxy/models.py\nclass ModelConfig(BaseModel):\n \"\"\"Configuration for a single model in the proxy.\"\"\"\n\n name: str = Field(..., description=\"Model identifier for API requests\")\n model_path: str = Field(..., description=\"Path or HuggingFace model ID\")\n gpu_ids: List[int] = Field(default_factory=list, description=\"GPU IDs to use\")\n port: int = Field(..., description=\"Port for the vLLM server\")\n profile: Optional[str] = Field(None, description=\"vLLM CLI profile to use\")\n config_overrides: Dict[str, Any] = Field(\n default_factory=dict, description=\"Additional vLLM configuration\"\n )\n enabled: bool = Field(True, description=\"Whether model is enabled\")\n loading_priority: Optional[int] = Field(\n None,\n description=\"Loading priority (lower numbers load first). \"\n \"Models with same priority load in parallel. \"\n \"Models with None priority load after all prioritized models.\",\n )\n\nclass ProxyConfig(BaseModel):\n \"\"\"Configuration for the proxy server.\"\"\"\n\n host: str = Field(\"0.0.0.0\", description=\"Proxy server host\") # nosec B104\n port: int = Field(8000, description=\"Proxy server port\")\n models: List[ModelConfig] = Field(\n default_factory=list, description=\"List of models to serve\"\n )\n enable_cors: bool = Field(True, description=\"Enable CORS headers\")\n enable_metrics: bool = Field(True, description=\"Enable metrics endpoint\")\n log_requests: bool = Field(False, description=\"Log all requests\")", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 1518}, "tests/proxy/test_models.py::32": {"resolved_imports": ["src/vllm_cli/proxy/models.py"], "used_names": ["ModelConfig"], "enclosing_function": "test_model_config_creation", "extracted_code": "# Source: src/vllm_cli/proxy/models.py\nclass ModelConfig(BaseModel):\n \"\"\"Configuration for a single model in the proxy.\"\"\"\n\n name: str = Field(..., description=\"Model identifier for API requests\")\n model_path: str = Field(..., description=\"Path or HuggingFace model ID\")\n gpu_ids: List[int] = Field(default_factory=list, description=\"GPU IDs to use\")\n port: int = Field(..., description=\"Port for the vLLM server\")\n profile: Optional[str] = Field(None, description=\"vLLM CLI profile to use\")\n config_overrides: Dict[str, Any] = Field(\n default_factory=dict, description=\"Additional vLLM configuration\"\n )\n enabled: bool = Field(True, description=\"Whether model is enabled\")\n loading_priority: Optional[int] = Field(\n None,\n description=\"Loading priority (lower numbers load first). \"\n \"Models with same priority load in parallel. \"\n \"Models with None priority load after all prioritized models.\",\n )", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 967}, "tests/test_server_manager.py::172": {"resolved_imports": ["src/vllm_cli/server/__init__.py", "src/vllm_cli/server/process.py", "src/vllm_cli/server/manager.py"], "used_names": ["Mock", "VLLMServer", "datetime", "process"], "enclosing_function": "test_get_status", "extracted_code": "# Source: src/vllm_cli/server/__init__.py\n\nThis package provides comprehensive vLLM server management including\nprocess lifecycle, monitoring, discovery, and utilities.\n\nMain Components:\n- VLLMServer: Core server management class\n- Process management: Server registry and lifecycle\n- Discovery: External server detection\n- Monitoring: Health checks and metrics\n- Utils: Port management and cleanup utilities\n\"\"\"\n\n\n\n# Process management functions\nfrom .process import (\n add_server,\n cleanup_servers_on_exit,\n find_server_by_model,\n find_server_by_port,\n get_active_servers,\n remove_server,\n stop_all_servers,\n)\n\n\n\n# Source: src/vllm_cli/server/manager.py\nclass VLLMServer:\n \"\"\"\n Manages a vLLM server instance with comprehensive lifecycle control.\n\n This class handles the complete lifecycle of a vLLM server including\n configuration, process management, logging, monitoring, and cleanup.\n It supports both programmatically started servers and external server\n detection and management.\n\n Attributes:\n config: Server configuration dictionary\n model: Model name being served\n port: Port number the server is listening on\n process: Subprocess or external process reference\n log_file: File handle for server logs\n log_queue: Thread-safe queue for log lines\n log_thread: Background thread for log monitoring\n start_time: Timestamp when server was started\n log_path: Path to the server's log file\n \"\"\"\n\n def __init__(self, config: Dict[str, Any]) -> None:\n \"\"\"\n Initialize a vLLM server instance.\n\n Sets up the server configuration, logging infrastructure, and\n prepares the instance for server lifecycle management.\n\n Args:\n config: Server configuration dictionary containing model name,\n port, and other vLLM-specific parameters\n \"\"\"\n self.config: Dict[str, Any] = config\n\n # Extract model name - handle both string and dict (LoRA config) formats\n model_config = config.get(\"model\", \"unknown\")\n if isinstance(model_config, dict):\n # LoRA configuration - extract base model name\n self.model: str = model_config.get(\"model\", \"unknown\")\n else:\n # Regular string model name\n self.model: str = model_config\n\n self.port: int = config.get(\"port\", 8000)\n self.process: Optional[Union[subprocess.Popen, Any]] = None\n self.log_file: Optional[TextIO] = None\n self.log_queue: Queue[str] = Queue()\n self.log_thread: Optional[Thread] = None\n self.start_time: Optional[datetime] = None\n self.log_path: Path\n self._recent_logs: List[str] = []\n\n # Setup logging\n log_dir = Path.home() / \".vllm-cli\" / \"logs\"\n log_dir.mkdir(parents=True, exist_ok=True)\n\n timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n self.log_path = log_dir / f\"vllm_{self.model.replace('/', '_')}_{timestamp}.log\"\n\n def start(self) -> bool:\n \"\"\"\n Start the vLLM server.\n\n Returns:\n True if server started successfully, False otherwise\n \"\"\"\n if self.is_running():\n logger.warning(f\"Server already running for {self.model}\")\n return False\n\n try:\n # Build command - run directly without conda wrapper\n full_cmd = self._build_command()\n\n logger.info(f\"Starting vLLM server with command: {' '.join(full_cmd)}\")\n\n # Open log file for writing\n self.log_file = open(self.log_path, \"w\", buffering=1)\n\n # Start with parent environment\n env = os.environ.copy()\n # Note: No longer forcing PYTHONUNBUFFERED=1, let user control it\n\n # Layer 1: Apply universal environment variables from settings\n config_manager = ConfigManager()\n universal_env = config_manager.config.get(\"universal_environment\", {})\n if universal_env:\n logger.info(\n f\"Applying {len(universal_env)} universal environment variable(s)\"\n )\n for key, value in universal_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting universal {key}={value}\")\n else:\n logger.debug(f\"Setting universal {key}=\")\n\n # Layer 2: Apply profile environment variables (override universal)\n profile_env = self.config.get(\"profile_environment\", {})\n if profile_env:\n logger.info(\n f\"Applying {len(profile_env)} profile environment variable(s)\"\n )\n for key, value in profile_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting profile {key}={value}\")\n else:\n logger.debug(f\"Setting profile {key}=\")\n\n # Handle GPU device selection via CUDA_VISIBLE_DEVICES\n # This overrides any CUDA_VISIBLE_DEVICES from the profile\n if self.config.get(\"device\"):\n device_str = str(self.config[\"device\"])\n env[\"CUDA_VISIBLE_DEVICES\"] = device_str\n logger.info(f\"Setting CUDA_VISIBLE_DEVICES={device_str}\")\n\n # If using specific GPUs, adjust tensor parallel size if needed\n device_list = [d.strip() for d in device_str.split(\",\")]\n num_devices = len(device_list)\n\n # Check if tensor_parallel_size is set and compatible\n if self.config.get(\"tensor_parallel_size\"):\n tp_size = self.config[\"tensor_parallel_size\"]\n if tp_size > num_devices:\n logger.warning(\n f\"tensor_parallel_size ({tp_size}) > number of selected devices ({num_devices}). \"\n f\"Adjusting tensor_parallel_size to {num_devices}\"\n )\n self.config[\"tensor_parallel_size\"] = num_devices\n elif num_devices % tp_size != 0:\n logger.warning(\n f\"Number of GPUs ({num_devices}) is not evenly divisible by \"\n f\"tensor_parallel_size ({tp_size}). This may lead to inefficient GPU utilization. \"\n f\"Consider using tensor_parallel_size of: \"\n f\"{', '.join(str(i) for i in range(1, num_devices + 1) if num_devices % i == 0)}\"\n )\n\n # Add HuggingFace token if configured\n config_manager = ConfigManager()\n hf_token = config_manager.config.get(\"hf_token\")\n if hf_token:\n env[\"HF_TOKEN\"] = hf_token\n env[\"HUGGING_FACE_HUB_TOKEN\"] = hf_token # Some tools use this variant\n logger.info(\"HuggingFace token configured for server\")\n\n # Enable development mode for sleep endpoints if sleep mode is enabled\n if self.config.get(\"enable_sleep_mode\"):\n env[\"VLLM_SERVER_DEV_MODE\"] = \"1\"\n logger.info(\"Sleep mode enabled with development endpoints\")\n\n # Start the process with proper pipe configuration\n # Use start_new_session=True to create a new process group\n # This prevents the child process from receiving Ctrl+C signals\n self.process = subprocess.Popen(\n full_cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n text=True,\n bufsize=0, # Unbuffered\n universal_newlines=True,\n env=env,\n start_new_session=True, # Create new process group to isolate from parent signals\n )\n\n # Start log monitoring thread\n self._start_log_monitor()\n\n # Set start time and add to registry\n self.start_time = datetime.now()\n from .process import add_server\n\n add_server(self)\n\n # Return immediately - let the UI monitor the startup\n logger.info(\n f\"vLLM server process launched for {self.model} on port {self.port}\"\n )\n return True\n\n except Exception as e:\n logger.error(f\"Error starting vLLM server: {e}\")\n return False\n\n def _build_command(self) -> List[str]:\n \"\"\"\n Build the vLLM command from configuration using the schema.\n\n Returns:\n List of command arguments\n \"\"\"\n # Use the new ConfigManager to build CLI args\n config_manager = ConfigManager()\n\n # Start with the vllm command\n cmd = [\"vllm\"]\n\n # Add the arguments built from schema\n cli_args = config_manager.build_cli_args(self.config)\n cmd.extend(cli_args)\n\n # Handle extra_args if present (backward compatibility)\n if self.config.get(\"extra_args\"):\n self._add_extra_args_to_command(cmd)\n\n logger.debug(f\"Built command: {' '.join(cmd)}\")\n return cmd\n\n def _add_extra_args_to_command(self, cmd: List[str]) -> None:\n \"\"\"\n Add extra arguments to the vLLM command.\n\n Args:\n cmd: Command list to extend with extra arguments\n \"\"\"\n try:\n extra_args = shlex.split(self.config[\"extra_args\"])\n if extra_args:\n logger.info(f\"Adding extra arguments: {extra_args}\")\n cmd.extend(extra_args)\n except ValueError as e:\n logger.warning(f\"Failed to parse extra_args: {e}\")\n\n def _start_log_monitor(self) -> None:\n \"\"\"\n Start a thread to monitor log output from the vLLM server process.\n\n Creates a daemon thread that continuously reads stdout/stderr from\n the server process, writes to log files, and queues log lines for\n real-time display in the UI.\n \"\"\"\n self.log_thread = Thread(target=self._log_monitor_worker, daemon=True)\n self.log_thread.start()\n\n def _log_monitor_worker(self) -> None:\n \"\"\"\n Worker function for log monitoring thread.\n\n Continuously reads log output from the server process and handles\n file writing and queue management for UI display.\n \"\"\"\n try:\n self.log_queue.put(\"Starting vLLM server process...\")\n\n while self._should_continue_monitoring():\n if self._process_log_line():\n continue\n else:\n # No line read, check if process still running\n if self.process and self.process.poll() is not None:\n break\n time.sleep(0.01) # Small sleep to prevent busy waiting\n\n except Exception as e:\n logger.error(f\"Error in log monitor: {e}\")\n self.log_queue.put(f\"Log monitoring error: {e}\")\n\n def _should_continue_monitoring(self) -> bool:\n \"\"\"\n Check if log monitoring should continue.\n\n Returns:\n True if monitoring should continue, False otherwise\n \"\"\"\n return (\n self.is_running()\n and self.process\n and hasattr(self.process, \"stdout\")\n and self.process.stdout\n )\n\n def _process_log_line(self) -> bool:\n \"\"\"\n Process a single log line from the server output.\n\n Reads one line from the process stdout, writes it to the log file,\n and adds it to the queue for UI display after filtering and formatting.\n\n Returns:\n True if a line was processed, False if no line was available\n \"\"\"\n if not (self.process and self.process.stdout):\n return False\n\n line = self.process.stdout.readline()\n if not line:\n return False\n\n # Write to log file\n self._write_to_log_file(line)\n\n # Process for UI display\n line_stripped = line.strip()\n if line_stripped and self._should_display_log_line(line_stripped):\n # Truncate overly long lines\n if len(line_stripped) > 200:\n line_stripped = line_stripped[:197] + \"...\"\n\n self.log_queue.put(line_stripped)\n logger.debug(f\"Log captured: {line_stripped[:50]}...\")\n\n return True\n\n def _write_to_log_file(self, line: str) -> None:\n \"\"\"\n Write a log line to the log file.\n\n Args:\n line: Log line to write\n \"\"\"\n if self.log_file and not self.log_file.closed:\n self.log_file.write(line)\n self.log_file.flush()\n\n def _should_display_log_line(self, line: str) -> bool:\n \"\"\"\n Determine if a log line should be displayed in the UI.\n\n Filters out certain system messages that are not useful for users.\n\n Args:\n line: Stripped log line to check\n\n Returns:\n True if the line should be displayed, False otherwise\n \"\"\"\n # Filter out conda activation and system messages\n filtered_messages = [\n \"Activated CUDA\",\n \"Using nvcc from:\",\n \"Cuda compilation tools\",\n ]\n return not any(skip in line for skip in filtered_messages)\n\n def stop(self) -> bool:\n \"\"\"\n Stop the vLLM server.\n\n Returns:\n True if server stopped successfully, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n try:\n # Check if this is an external server\n if hasattr(self.process, \"terminate\"):\n # Normal subprocess\n # Since we created a new session, we need to terminate the entire process group\n try:\n # Get the process group ID (pgid)\n # Since we used start_new_session=True, the pgid is the same as the pid\n pgid = self.process.pid\n\n # Send SIGTERM to the entire process group for graceful shutdown\n logger.info(f\"Sending SIGTERM to process group {pgid}\")\n os.killpg(pgid, signal.SIGTERM)\n\n # Wait for process to terminate\n try:\n self.process.wait(timeout=10)\n logger.info(f\"Process group {pgid} terminated gracefully\")\n except subprocess.TimeoutExpired:\n # Force kill if not terminated\n logger.warning(\n f\"Process group {pgid} did not terminate, sending SIGKILL\"\n )\n os.killpg(pgid, signal.SIGKILL)\n self.process.wait()\n logger.info(f\"Process group {pgid} force killed\")\n\n except ProcessLookupError:\n # Process already dead\n logger.info(\"Process already terminated\")\n except PermissionError as e:\n # Fall back to terminating just the process\n logger.warning(\n f\"Permission denied for process group kill: {e}, falling back to process termination\"\n )\n self.process.terminate()\n try:\n self.process.wait(timeout=10)\n except subprocess.TimeoutExpired:\n self.process.kill()\n self.process.wait()\n elif hasattr(self.process, \"pid\"):\n # External server - kill entire process group or individual process\n try:\n pgid = self.process.pid\n killed = False\n\n # First attempt: try to kill process group\n try:\n os.killpg(pgid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process group {pgid}\")\n killed = True\n except (OSError, ProcessLookupError) as e:\n # Process group kill failed, try individual process\n logger.debug(\n f\"Process group kill failed: {e}, trying individual process\"\n )\n try:\n # Ensure pid is an integer (handle Mock objects)\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process {self.process.pid}\")\n killed = True\n except ProcessLookupError:\n # Process already dead\n logger.info(\n f\"Process {self.process.pid} already terminated\"\n )\n except OSError as e:\n logger.warning(\n f\"Failed to send SIGTERM to {self.process.pid}: {e}\"\n )\n\n if killed:\n # Wait for graceful shutdown\n time.sleep(2)\n\n # Check if still running and force kill if needed\n if self.is_running():\n try:\n os.killpg(pgid, signal.SIGKILL)\n logger.info(f\"Force killed process group {pgid}\")\n except (OSError, ProcessLookupError):\n # Process group kill failed, try individual\n try:\n # Ensure pid is an integer (handle Mock objects in tests)\n if hasattr(self.process, \"pid\"):\n try:\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGKILL)\n logger.info(f\"Force killed process {pid}\")\n except (TypeError, ValueError):\n # PID is not a valid integer (might be Mock)\n pass\n except ProcessLookupError:\n pass # Already dead\n except OSError as e:\n logger.error(\n f\"Failed to force kill {self.process.pid}: {e}\"\n )\n\n except Exception as e:\n logger.error(f\"Unexpected error stopping external server: {e}\")\n\n # Close log file if we have one\n if hasattr(self, \"log_file\") and self.log_file:\n self.log_file.close()\n\n # Remove from registry\n from .process import remove_server\n\n remove_server(self)\n\n logger.info(f\"vLLM server stopped for {self.model}\")\n return True\n\n except Exception as e:\n logger.error(f\"Error stopping vLLM server: {e}\")\n return False\n\n def is_running(self) -> bool:\n \"\"\"\n Check if the server is running.\n\n Returns:\n True if server is running, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n # Check if this is an external server (detected, not started by us)\n if hasattr(self.process, \"poll\"):\n # Normal subprocess\n return self.process.poll() is None\n elif hasattr(self.process, \"pid\"):\n # External server - check if PID still exists\n try:\n import psutil\n\n return psutil.pid_exists(self.process.pid)\n except ImportError:\n # Fallback to os method\n try:\n os.kill(self.process.pid, 0)\n return True\n except (OSError, ProcessLookupError):\n return False\n\n return False\n\n def get_status(self) -> Dict[str, Any]:\n \"\"\"\n Get server status information.\n\n Returns:\n Dictionary with status information\n \"\"\"\n status = {\n \"model\": self.model,\n \"port\": self.port,\n \"running\": self.is_running(),\n \"pid\": self.process.pid if self.process else None,\n \"start_time\": self.start_time.isoformat() if self.start_time else None,\n \"log_path\": str(self.log_path) if self.log_path else None,\n }\n\n if self.is_running() and self.start_time:\n uptime = datetime.now() - self.start_time\n status[\"uptime_seconds\"] = uptime.total_seconds()\n status[\"uptime_str\"] = str(uptime).split(\".\")[0]\n\n return status\n\n def wait_for_startup(self) -> bool:\n \"\"\"\n Wait for the server to complete startup.\n\n Monitors the server logs for startup completion indicators and verifies\n via HTTP endpoint. Will wait indefinitely until either startup completes\n or the process terminates.\n\n Returns:\n True if server started successfully, False if process terminated\n \"\"\"\n import time\n\n logger.info(f\"Waiting for {self.model} server to complete startup...\")\n\n # Track if we've seen startup indicators in logs\n log_indicates_ready = False\n\n while True:\n # Check if server is still running\n if not self.is_running():\n logger.error(\n f\"Server process for {self.model} terminated during startup\"\n )\n return False\n\n # Get recent logs to check for startup completion\n recent_logs = self.get_recent_logs(50)\n\n if recent_logs and not log_indicates_ready:\n # Check for startup completion indicators\n for log in recent_logs:\n log_lower = log.lower()\n # Look for the explicit \"Application startup complete\" message\n if \"application startup complete\" in log_lower:\n logger.debug(f\"Server {self.model} startup detected in logs\")\n log_indicates_ready = True\n break\n\n # Also check for other ready indicators as fallback\n if any(\n indicator in log_lower\n for indicator in [\n \"uvicorn running on\",\n \"started server process\",\n \"server is ready\",\n \"api server started\",\n ]\n ):\n logger.debug(\n f\"Server {self.model} startup detected via ready indicator\"\n )\n log_indicates_ready = True\n break\n\n # If logs indicate ready, verify via HTTP\n if log_indicates_ready:\n # Try to verify server is actually ready via HTTP\n port = self.config.get(\"port\")\n if port:\n try:\n import httpx\n\n with httpx.Client() as client:\n # Try /v1/models endpoint first (most reliable)\n response = client.get(\n f\"http://localhost:{port}/v1/models\", timeout=5.0\n )\n if response.status_code == 200:\n logger.info(\n f\"Server {self.model} startup complete \"\n \"(verified via HTTP)\"\n )\n return True\n except httpx.ConnectError:\n # Server not ready yet, continue waiting\n logger.debug(\n f\"Server {self.model} not accepting connections yet\"\n )\n except Exception as e:\n # Log but continue, might be network issue\n logger.debug(f\"HTTP verification failed: {e}\")\n else:\n # No port configured, trust the logs\n logger.info(\n f\"Server {self.model} startup complete (no port for verification)\"\n )\n return True\n\n # Small sleep to avoid busy waiting\n time.sleep(0.5)\n\n def get_recent_logs(self, n: int = 20) -> List[str]:\n \"\"\"\n Get recent log lines from the server output.\n\n Retrieves the most recent log lines from either the in-memory queue\n or the log file on disk. This method ensures logs are available even\n after the monitoring thread has processed them.\n\n Args:\n n: Number of recent lines to return (default: 20)\n\n Returns:\n List of recent log lines, with the most recent last\n \"\"\"\n # Update recent logs from queue\n self._update_recent_logs_from_queue()\n\n # Return from memory if available\n if self._recent_logs:\n return self._recent_logs[-n:]\n\n # Fallback to reading from file\n return self._read_logs_from_file(n)\n\n def _update_recent_logs_from_queue(self) -> None:\n \"\"\"\n Update the recent logs cache from the log queue.\n\n Drains all available log lines from the queue and adds them\n to the recent logs cache, maintaining a maximum of 100 lines.\n \"\"\"\n temp_logs = []\n\n # Get all available logs from queue (don't block)\n while not self.log_queue.empty():\n try:\n log_line = self.log_queue.get_nowait()\n temp_logs.append(log_line)\n except Empty:\n break\n\n if temp_logs:\n self._recent_logs.extend(temp_logs)\n # Keep only the last 100 logs in memory to prevent unbounded growth\n self._recent_logs = self._recent_logs[-100:]\n\n def _read_logs_from_file(self, n: int) -> List[str]:\n \"\"\"\n Read recent log lines from the log file.\n\n Args:\n n: Number of lines to read\n\n Returns:\n List of log lines from file\n \"\"\"\n if not (self.log_path and self.log_path.exists()):\n return []\n\n try:\n with open(self.log_path, \"r\") as f:\n file_logs = f.readlines()\n if file_logs:\n # Get last n lines, strip them\n logs = [line.strip() for line in file_logs[-n:]]\n # Update recent logs cache\n self._recent_logs = logs[-100:]\n return logs\n except Exception as e:\n logger.debug(f\"Error reading log file: {e}\")\n\n return []\n\n def restart(self) -> bool:\n \"\"\"\n Restart the server with the same configuration.\n\n Returns:\n True if restart successful, False otherwise\n \"\"\"\n logger.info(f\"Restarting vLLM server for {self.model}\")\n\n # Stop if running\n if self.is_running():\n self.stop()\n time.sleep(2) # Wait a bit before restarting\n\n # Start again\n return self.start()\n\n def health_check(self) -> bool:\n \"\"\"\n Perform a health check on the server.\n\n Returns:\n True if server is healthy, False otherwise\n \"\"\"\n if not self.is_running():\n return False\n\n try:\n import requests\n\n # Try to connect to the server\n response = requests.get(f\"http://localhost:{self.port}/health\", timeout=5)\n\n return response.status_code == 200\n\n except Exception:\n # If requests fails, just check process\n return self.is_running()", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 28614}, "tests/test_custom_directory_integration.py::233": {"resolved_imports": ["src/vllm_cli/models/manager.py", "src/vllm_cli/models/manifest.py"], "used_names": ["patch"], "enclosing_function": "test_custom_model_selection", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/proxy/test_models.py::144": {"resolved_imports": ["src/vllm_cli/proxy/models.py"], "used_names": ["ProxyConfig"], "enclosing_function": "test_proxy_config_with_empty_models", "extracted_code": "# Source: src/vllm_cli/proxy/models.py\nclass ProxyConfig(BaseModel):\n \"\"\"Configuration for the proxy server.\"\"\"\n\n host: str = Field(\"0.0.0.0\", description=\"Proxy server host\") # nosec B104\n port: int = Field(8000, description=\"Proxy server port\")\n models: List[ModelConfig] = Field(\n default_factory=list, description=\"List of models to serve\"\n )\n enable_cors: bool = Field(True, description=\"Enable CORS headers\")\n enable_metrics: bool = Field(True, description=\"Enable metrics endpoint\")\n log_requests: bool = Field(False, description=\"Log all requests\")", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 588}, "tests/test_profiles.py::41": {"resolved_imports": ["src/vllm_cli/config/profiles.py"], "used_names": ["ProfileManager"], "enclosing_function": "test_load_user_profiles_no_file", "extracted_code": "# Source: src/vllm_cli/config/profiles.py\nclass ProfileManager:\n \"\"\"\n Manages user profiles for vLLM configurations.\n\n Handles creation, retrieval, updating, and deletion of user profiles\n with validation and persistence.\n \"\"\"\n\n def __init__(self, config_dir: Path):\n self.config_dir = config_dir\n self.user_profiles_file = config_dir / \"user_profiles.json\"\n\n # Paths for schema files (packaged with application)\n schema_dir = Path(__file__).parent.parent / \"schemas\"\n self.default_profiles_file = schema_dir / \"default_profiles.json\"\n\n # Load profiles\n self.default_profiles = self._load_default_profiles()\n self.user_profiles = self._load_user_profiles()\n\n def _load_json_file(self, filepath: Path) -> Dict[str, Any]:\n \"\"\"Load a JSON file safely.\"\"\"\n if filepath.exists():\n try:\n with open(filepath, \"r\") as f:\n return json.load(f)\n except Exception as e:\n logger.error(f\"Error loading {filepath}: {e}\")\n return {}\n\n def _save_json_file(self, filepath: Path, data: Dict[str, Any]) -> bool:\n \"\"\"Save data to a JSON file.\"\"\"\n try:\n with open(filepath, \"w\") as f:\n json.dump(data, f, indent=2)\n return True\n except Exception as e:\n logger.error(f\"Error saving {filepath}: {e}\")\n return False\n\n def _load_default_profiles(self) -> Dict[str, Any]:\n \"\"\"Load default built-in profiles.\"\"\"\n profiles = self._load_json_file(self.default_profiles_file)\n return profiles.get(\"profiles\", {})\n\n def _load_user_profiles(self) -> Dict[str, Any]:\n \"\"\"Load user-created custom profiles.\"\"\"\n return self._load_json_file(self.user_profiles_file)\n\n def _save_user_profiles(self) -> bool:\n \"\"\"Save user profiles to file.\"\"\"\n return self._save_json_file(self.user_profiles_file, self.user_profiles)\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n all_profiles = deepcopy(self.default_profiles)\n all_profiles.update(self.user_profiles)\n return all_profiles\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name.\"\"\"\n # Check user profiles first, then default profiles\n if name in self.user_profiles:\n return deepcopy(self.user_profiles[name])\n elif name in self.default_profiles:\n return deepcopy(self.default_profiles[name])\n return None\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"\n Save or update a user profile with validation.\n\n Args:\n name: Profile name\n profile: Profile data to save\n\n Returns:\n True if saved successfully\n\n Raises:\n ProfileError: If profile validation fails or save fails\n \"\"\"\n try:\n # Validate profile structure\n if not isinstance(profile, dict):\n raise ProfileError(\n \"Profile must be a dictionary\",\n profile_name=name,\n error_code=\"INVALID_PROFILE_TYPE\",\n )\n\n # Process LoRA configuration if present\n if \"config\" in profile:\n config = profile[\"config\"]\n\n # Handle LoRA adapters in config\n if \"lora_adapters\" in config:\n # Validate LoRA adapter entries\n lora_adapters = config[\"lora_adapters\"]\n if isinstance(lora_adapters, list):\n # Ensure each adapter has required fields\n for adapter in lora_adapters:\n if not isinstance(adapter, dict):\n continue\n if \"path\" not in adapter and \"name\" in adapter:\n # Try to resolve adapter by name\n adapter[\"path\"] = self._resolve_lora_path(\n adapter[\"name\"]\n )\n\n # Convert to lora_modules format for vLLM\n if lora_adapters:\n config[\"enable_lora\"] = True\n lora_modules = []\n for adapter in lora_adapters:\n if isinstance(adapter, dict):\n name = adapter.get(\"name\", \"adapter\")\n path = adapter.get(\"path\", \"\")\n if path:\n lora_modules.append(f\"{name}={path}\")\n if lora_modules:\n config[\"lora_modules\"] = \" \".join(lora_modules)\n\n # Save the profile\n self.user_profiles[name] = deepcopy(profile)\n\n if not self._save_user_profiles():\n raise ProfileError(\n \"Failed to save profile to disk\",\n profile_name=name,\n error_code=\"PROFILE_SAVE_FAILED\",\n )\n\n logger.info(f\"Successfully saved user profile: {name}\")\n return True\n\n except ProfileError:\n raise\n except Exception as e:\n logger.error(f\"Unexpected error saving profile {name}: {e}\")\n raise ProfileError(\n f\"Unexpected error saving profile: {e}\",\n profile_name=name,\n error_code=\"PROFILE_SAVE_ERROR\",\n ) from e\n\n def _resolve_lora_path(self, adapter_name: str) -> str:\n \"\"\"\n Try to resolve a LoRA adapter path by name.\n\n Args:\n adapter_name: Name of the LoRA adapter\n\n Returns:\n Path to the adapter if found, empty string otherwise\n \"\"\"\n try:\n from ..models import scan_for_lora_adapters\n\n adapters = scan_for_lora_adapters()\n for adapter in adapters:\n if (\n adapter.get(\"name\") == adapter_name\n or adapter.get(\"display_name\") == adapter_name\n ):\n return adapter.get(\"path\", \"\")\n except Exception as e:\n logger.debug(f\"Could not resolve LoRA path for {adapter_name}: {e}\")\n return \"\"\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n if name in self.user_profiles:\n del self.user_profiles[name]\n return self._save_user_profiles()\n return False\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n profile = self.get_profile(profile_name)\n if not profile:\n logger.error(f\"Profile '{profile_name}' not found\")\n return False\n\n export_data = {\"version\": \"1.0\", \"profile\": profile}\n\n try:\n with open(filepath, \"w\") as f:\n json.dump(export_data, f, indent=2)\n logger.info(f\"Profile '{profile_name}' exported to {filepath}\")\n return True\n except Exception as e:\n logger.error(f\"Error exporting profile: {e}\")\n return False\n\n def import_profile(\n self,\n filepath: Path,\n new_name: Optional[str] = None,\n validate_config_func: Optional[Callable] = None,\n ) -> bool:\n \"\"\"\n Import a profile from a JSON file with comprehensive validation.\n\n Args:\n filepath: Path to the profile file\n new_name: Optional new name for the profile\n validate_config_func: Optional function to validate profile config\n\n Returns:\n True if imported successfully\n\n Raises:\n ProfileError: If import fails for any reason\n \"\"\"\n try:\n # Check file exists\n if not filepath.exists():\n raise ProfileError(\n f\"Profile file not found: {filepath}\",\n error_code=\"PROFILE_FILE_NOT_FOUND\",\n )\n\n # Load and parse file\n try:\n with open(filepath, \"r\") as f:\n data = json.load(f)\n except json.JSONDecodeError as e:\n raise ProfileError(\n f\"Invalid JSON in profile file: {e}\",\n error_code=\"PROFILE_INVALID_JSON\",\n ) from e\n\n # Validate file format\n if not isinstance(data, dict) or \"profile\" not in data:\n raise ProfileError(\n \"Invalid profile file format - missing 'profile' key\",\n error_code=\"PROFILE_INVALID_FORMAT\",\n )\n\n profile = data[\"profile\"]\n name = new_name or profile.get(\"name\", filepath.stem)\n\n # Validate profile configuration if function provided\n if validate_config_func and \"config\" in profile:\n is_valid, errors = validate_config_func(profile[\"config\"])\n if not is_valid:\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n # Save the profile\n return self.save_user_profile(name, profile)\n\n except ProfileError:\n raise\n except Exception as e:\n logger.error(f\"Unexpected error importing profile from {filepath}: {e}\")\n raise ProfileError(\n f\"Failed to import profile: {e}\", error_code=\"PROFILE_IMPORT_ERROR\"\n ) from e\n\n def list_profile_names(self) -> Dict[str, List[str]]:\n \"\"\"\n List all profile names categorized by type.\n\n Returns:\n Dictionary with 'default' and 'user' lists of profile names\n \"\"\"\n return {\n \"default\": list(self.default_profiles.keys()),\n \"user\": list(self.user_profiles.keys()),\n }\n\n def profile_exists(self, name: str) -> bool:\n \"\"\"Check if a profile exists (in either default or user profiles).\"\"\"\n return name in self.default_profiles or name in self.user_profiles\n\n def is_user_profile(self, name: str) -> bool:\n \"\"\"Check if a profile is a user-created profile.\"\"\"\n return name in self.user_profiles\n\n def has_user_override(self, name: str) -> bool:\n \"\"\"\n Check if a built-in profile has been overridden by a user profile.\n\n Args:\n name: Profile name to check\n\n Returns:\n True if this is a built-in profile that has a user override\n \"\"\"\n return name in self.default_profiles and name in self.user_profiles\n\n def get_original_default_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get the original default profile without any user overrides.\n\n Args:\n name: Profile name\n\n Returns:\n Original default profile if it exists, None otherwise\n \"\"\"\n if name in self.default_profiles:\n return deepcopy(self.default_profiles[name])\n return None\n\n def reset_to_default(self, name: str) -> bool:\n \"\"\"\n Reset a customized built-in profile to its default settings.\n\n This removes the user override for a built-in profile.\n\n Args:\n name: Profile name to reset\n\n Returns:\n True if reset successfully, False otherwise\n \"\"\"\n # Only reset if this is a built-in profile with a user override\n if self.has_user_override(name):\n return self.delete_user_profile(name)\n return False\n\n def get_profile_count(self) -> Dict[str, int]:\n \"\"\"Get count of profiles by type.\"\"\"\n return {\n \"default\": len(self.default_profiles),\n \"user\": len(self.user_profiles),\n \"total\": len(self.default_profiles) + len(self.user_profiles),\n }\n\n def apply_dynamic_defaults(self, profile_config: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Apply dynamic defaults to a profile configuration.\n\n This function intelligently sets tensor_parallel_size for multi-GPU systems.\n For single GPU systems, it allows vLLM to use its default behavior.\n\n Note: vLLM defaults to using only 1 GPU unless tensor_parallel_size is explicitly set.\n\n Args:\n profile_config: The profile configuration to enhance\n\n Returns:\n Enhanced profile configuration with dynamic defaults applied\n \"\"\"\n config = deepcopy(profile_config)\n\n # Apply dynamic tensor_parallel_size if not specified\n # Note: vLLM defaults to single GPU, so we only set this for multi-GPU systems\n # where tensor parallelism would be beneficial\n if \"tensor_parallel_size\" not in config:\n gpu_count = self._get_gpu_count()\n if gpu_count > 1:\n config[\"tensor_parallel_size\"] = gpu_count\n logger.debug(\n f\"Set tensor_parallel_size to {gpu_count} for multi-GPU system\"\n )\n # For single GPU, let vLLM use its default (no tensor_parallel_size needed)\n\n return config\n\n def _get_gpu_count(self) -> int:\n \"\"\"\n Get the number of available GPUs for tensor parallelism.\n\n Returns:\n Number of GPUs available, defaults to 1 if detection fails\n \"\"\"\n try:\n gpus = get_gpu_info()\n gpu_count = len(gpus) if gpus else 1\n logger.debug(f\"Detected {gpu_count} GPU(s)\")\n return gpu_count\n except Exception as e:\n logger.warning(f\"Failed to detect GPU count, defaulting to 1: {e}\")\n return 1", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 14008}, "tests/test_ollama_support.py::135": {"resolved_imports": ["src/vllm_cli/models/discovery.py", "src/vllm_cli/models/manager.py", "src/vllm_cli/ui/model_manager.py"], "used_names": ["patch", "pytest", "select_model"], "enclosing_function": "test_select_ollama_model_format", "extracted_code": "# Source: src/vllm_cli/ui/model_manager.py\ndef select_model() -> Optional[Any]:\n \"\"\"\n Select a model from available models with provider categorization.\n Can return either a string (model name) or a dict (model with LoRA config).\n \"\"\"\n console.print(\"\\n[bold cyan]Model Selection[/bold cyan]\")\n\n try:\n # First, ask if user wants to use local or remote model\n model_source_choices = [\n \"Select from local models\",\n \"Serve model with LoRA adapters\",\n \"Use a model from HuggingFace Hub (auto-download)\",\n ]\n\n source_choice = unified_prompt(\n \"model_source\",\n \"How would you like to select a model?\",\n model_source_choices,\n allow_back=True,\n )\n\n if not source_choice or source_choice == \"BACK\":\n return None\n\n if source_choice == \"Use a model from HuggingFace Hub (auto-download)\":\n return enter_remote_model()\n\n if source_choice == \"Serve model with LoRA adapters\":\n return select_model_with_lora()\n\n # Continue with local model selection\n console.print(\"\\n[bold cyan]Fetching available models...[/bold cyan]\")\n models = list_available_models()\n\n if not models:\n console.print(\"[yellow]No local models found.[/yellow]\")\n console.print(\"\\nYou can either:\")\n console.print(\" 1. Download models using HuggingFace tools\")\n console.print(\" 2. Go back and select 'Use a model from HuggingFace Hub'\")\n input(\"\\nPress Enter to continue...\")\n return None\n\n # Group models by provider\n providers_dict = {}\n for model in models:\n # Special handling for Ollama models\n if model.get(\"type\") == \"ollama_model\":\n provider = \"ollama\"\n else:\n provider = model.get(\"publisher\", \"unknown\")\n if provider == \"unknown\" or not provider:\n # Try to extract provider from model name\n if \"/\" in model[\"name\"]:\n provider = model[\"name\"].split(\"/\")[0]\n else:\n provider = \"local\"\n\n if provider not in providers_dict:\n providers_dict[provider] = []\n providers_dict[provider].append(model)\n\n # Separate local provider from others\n local_provider = None\n other_providers = []\n\n for provider in providers_dict.keys():\n if provider == \"local\":\n local_provider = provider\n else:\n other_providers.append(provider)\n\n # Sort other providers alphabetically\n other_providers.sort()\n\n # Build provider choices with separation\n provider_choices = []\n\n # Add other providers first\n for provider in other_providers:\n count = len(providers_dict[provider])\n provider_choices.append(\n f\"{provider} ({count} model{'s' if count > 1 else ''})\"\n )\n\n # Add separator and local provider at the bottom if it exists\n if local_provider:\n # Add separator if there are other providers\n if other_providers:\n provider_choices.append(\"─\" * 30)\n count = len(providers_dict[local_provider])\n provider_choices.append(\n f\"{local_provider} ({count} model{'s' if count > 1 else ''})\"\n )\n\n # Count total providers (excluding separator)\n total_providers = len(providers_dict)\n\n selected_provider = unified_prompt(\n \"provider\",\n f\"Select Provider ({total_providers} available)\",\n provider_choices,\n allow_back=True,\n )\n\n if not selected_provider or selected_provider == \"BACK\":\n return None\n\n # Check if separator was selected (shouldn't happen, but handle it)\n if selected_provider.startswith(\"─\"):\n # Retry selection\n return select_model()\n\n # Extract provider name\n provider_name = selected_provider.split(\" (\")[0]\n\n # Now show models for selected provider\n provider_models = providers_dict[provider_name]\n\n # Create model choices for selected provider\n model_choices = []\n for model in provider_models:\n size_str = format_size(model.get(\"size\", 0))\n # Show only the model name without provider if it's already in the name\n display_name = model[\"name\"]\n if display_name.startswith(f\"{provider_name}/\"):\n display_name = display_name[len(provider_name) + 1 :] # noqa: E203\n model_choices.append(f\"{display_name} ({size_str})\")\n\n # Show model selection for the provider\n selected = unified_prompt(\n \"model\",\n f\"Select {provider_name} Model ({len(provider_models)} available)\",\n model_choices,\n allow_back=True,\n )\n\n if not selected or selected == \"BACK\":\n # Go back to provider selection\n return select_model()\n\n # Extract model name and reconstruct full name if needed\n model_display_name = selected.split(\" (\")[0]\n\n # Find the full model and return appropriate identifier\n for model in provider_models:\n check_name = model[\"name\"]\n if check_name.startswith(f\"{provider_name}/\"):\n check_name = check_name[len(provider_name) + 1 :] # noqa: E203\n if check_name == model_display_name or model[\"name\"] == model_display_name:\n # Special handling for Ollama models\n if model.get(\"type\") == \"ollama_model\":\n console.print(\"\\n[yellow]⚠ Warning: Ollama GGUF Model[/yellow]\")\n console.print(\n \"GGUF support in vLLM is experimental and varies by model architecture.\"\n )\n console.print(\n \"\\n[cyan]Important:[/cyan] Not all GGUF models are supported.\"\n )\n console.print(\"\\nFor compatibility information, see:\")\n console.print(\n \" • vLLM-CLI Guide: [cyan]https://github.com/Chen-zexi/vllm-cli/blob/main/docs/ollama-integration.md[/cyan]\"\n )\n console.print(\n \" • vLLM Docs: [cyan]https://docs.vllm.ai/en/latest/models/supported_models.html[/cyan]\"\n )\n\n console.print(\n \"\\n[cyan]Continue with this model? (Y/n):[/cyan] \", end=\"\"\n )\n confirm = input().strip().lower()\n if confirm not in [\"\", \"y\", \"yes\"]:\n return select_model() # Go back to selection\n\n # Return the GGUF file path with all metadata including name\n return {\n \"model\": model[\"path\"],\n \"path\": model[\"path\"], # Include path\n \"served_model_name\": model[\n \"name\"\n ], # Use correct field name for vLLM\n \"type\": \"ollama_model\", # Preserve type\n \"quantization\": \"gguf\",\n \"experimental\": True,\n }\n\n # For custom models, always use path regardless of publisher\n # Custom models are identified by their type\n if model.get(\"type\") == \"custom_model\" and model.get(\"path\"):\n return model[\"path\"]\n\n # For non-HF pattern models (local), also use path\n model_name = model[\"name\"]\n if model.get(\"path\") and (\n \"/\" not in model_name # No HF org/model pattern\n or model_name.startswith(\"/\") # Absolute path\n or model.get(\"publisher\")\n in [\"local\", \"unknown\", None] # Local publisher\n ):\n return model[\"path\"]\n return model[\"name\"]\n\n # Fallback\n return model_display_name\n\n except Exception as e:\n logger.error(f\"Error selecting model: {e}\")\n console.print(f\"[red]Error selecting model: {e}[/red]\")\n return None", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 8433}, "tests/test_validation_simple.py::20": {"resolved_imports": ["src/vllm_cli/validation/base.py", "src/vllm_cli/validation/registry.py", "src/vllm_cli/validation/types.py"], "used_names": ["ValidationError", "ValidationResult"], "enclosing_function": "test_validation_result", "extracted_code": "# Source: src/vllm_cli/validation/base.py\nclass ValidationError(Exception):\n \"\"\"\n Base exception for validation errors.\n\n Attributes:\n field: The field name that failed validation\n value: The value that failed validation\n message: Human-readable error message\n code: Error code for programmatic handling\n \"\"\"\n\n def __init__(\n self, field: str, value: Any, message: str, code: str = \"VALIDATION_ERROR\"\n ):\n self.field = field\n self.value = value\n self.message = message\n self.code = code\n super().__init__(f\"{field}: {message}\")\n\nclass ValidationResult:\n \"\"\"\n Container for validation results.\n\n Allows collecting multiple validation errors and warnings\n while maintaining performance for success cases.\n \"\"\"\n\n def __init__(self):\n self.errors: List[ValidationError] = []\n self.warnings: List[str] = []\n\n def add_error(self, error: ValidationError) -> None:\n \"\"\"Add a validation error.\"\"\"\n self.errors.append(error)\n\n def add_warning(self, warning: str) -> None:\n \"\"\"Add a validation warning.\"\"\"\n self.warnings.append(warning)\n\n def is_valid(self) -> bool:\n \"\"\"Check if validation passed (no errors).\"\"\"\n return len(self.errors) == 0\n\n def get_error_messages(self) -> List[str]:\n \"\"\"Get list of error messages.\"\"\"\n return [str(error) for error in self.errors]\n\n def merge(self, other: \"ValidationResult\") -> None:\n \"\"\"Merge another validation result into this one.\"\"\"\n self.errors.extend(other.errors)\n self.warnings.extend(other.warnings)", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 1650}, "tests/test_custom_directory_integration.py::270": {"resolved_imports": ["src/vllm_cli/models/manager.py", "src/vllm_cli/models/manifest.py", "src/vllm_cli/ui/model_directories.py"], "used_names": ["MagicMock", "ModelDirectoriesUI", "ModelManager", "Path", "patch"], "enclosing_function": "test_end_to_end_custom_model_serving", "extracted_code": "# Source: src/vllm_cli/models/manager.py\nclass ModelManager:\n \"\"\"\n Manages model discovery, caching, and metadata operations.\n\n Provides a high-level interface for model operations including\n listing, searching, and retrieving model information with\n integrated caching for performance.\n \"\"\"\n\n def __init__(self):\n self.cache = ModelCache()\n\n def list_available_models(self, refresh: bool = False) -> List[Dict[str, Any]]:\n \"\"\"\n List all available downloaded models with caching.\n\n Model scanning can be expensive, so results are cached for a short time\n to improve performance when multiple UI components need model data.\n\n Args:\n refresh: Force refresh the model cache, ignoring TTL\n\n Returns:\n List of model dictionaries with keys:\n - name: Full model name (publisher/model)\n - size: Model size in bytes\n - path: Path to model directory\n - type: Model type (model, custom_model)\n - publisher: Model publisher/organization\n - display_name: Human-readable model name\n - metadata: Additional model metadata\n \"\"\"\n # If refresh is forced, clear cache first to ensure fresh data\n if refresh:\n self.cache.clear_cache()\n logger.debug(\"Cache cleared for forced refresh\")\n else:\n # Check cache only if not refreshing\n cached_models = self.cache.get_cached_models()\n if cached_models is not None:\n return cached_models\n\n # Fetch fresh model data\n models = scan_for_models()\n\n # Process and normalize model data\n processed_models = []\n for item in models:\n # Accept all model types from hf-model-tool\n model_types = [\"model\", \"custom_model\", \"ollama_model\", \"gguf_model\"]\n if item.get(\"type\") in model_types:\n # For Ollama/GGUF models, use the item directly (already formatted)\n if item.get(\"type\") in [\"ollama_model\", \"gguf_model\"]:\n processed_models.append(item)\n else:\n model_dict = build_model_dict(item)\n processed_models.append(model_dict)\n\n # Sort models by name\n processed_models.sort(key=lambda x: x[\"name\"])\n\n # Update cache\n self.cache.cache_models(processed_models)\n\n logger.info(f\"Found {len(processed_models)} models\")\n return processed_models\n\n def get_model_details(self, model_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get detailed information about a specific model.\n\n Args:\n model_name: Name of the model to get details for\n\n Returns:\n Dictionary with model details or None if not found\n \"\"\"\n # First, try to find from cached models\n models = self.list_available_models()\n model_info = None\n\n for model in models:\n if model[\"name\"] == model_name or model.get(\"display_name\") == model_name:\n model_info = model\n break\n\n if not model_info:\n logger.warning(f\"Model {model_name} not found\")\n return None\n\n # Build detailed information\n details = {\n \"name\": model_info[\"name\"],\n \"full_name\": model_info[\"name\"],\n \"path\": model_info.get(\"path\", \"\"),\n \"size\": model_info.get(\"size\", 0),\n \"type\": model_info.get(\"type\", \"model\"),\n \"publisher\": model_info.get(\"publisher\", \"unknown\"),\n \"display_name\": model_info.get(\"display_name\", model_name),\n }\n\n # Extract metadata if available\n metadata = model_info.get(\"metadata\", {})\n if metadata:\n details[\"architecture\"] = (\n metadata.get(\"architectures\", [\"unknown\"])[0]\n if metadata.get(\"architectures\")\n else \"unknown\"\n )\n details[\"model_type\"] = metadata.get(\"model_type\", \"unknown\")\n details[\"torch_dtype\"] = metadata.get(\"torch_dtype\", \"unknown\")\n details[\"vocab_size\"] = metadata.get(\"vocab_size\", \"unknown\")\n\n # Add to main details\n details[\"metadata\"] = metadata\n\n # Try to read config.json for more details if path exists\n if details[\"path\"]:\n from .metadata import extract_model_config\n\n config_data = extract_model_config(details[\"path\"])\n if config_data:\n details.update(config_data)\n\n return details\n\n def search_models(self, query: str) -> List[Dict[str, Any]]:\n \"\"\"\n Search for models matching a query.\n\n Args:\n query: Search query string\n\n Returns:\n List of matching models\n \"\"\"\n models = self.list_available_models()\n query_lower = query.lower()\n\n # Filter models matching the query\n matches = []\n for model in models:\n if (\n query_lower in model[\"name\"].lower()\n or query_lower in model.get(\"display_name\", \"\").lower()\n or query_lower in model.get(\"publisher\", \"\").lower()\n ):\n matches.append(model)\n\n return matches\n\n def get_model_count(self) -> int:\n \"\"\"\n Get the total number of available models.\n\n Returns:\n Number of available models\n \"\"\"\n return len(self.list_available_models())\n\n def get_models_by_publisher(self, publisher: str) -> List[Dict[str, Any]]:\n \"\"\"\n Get all models from a specific publisher.\n\n Args:\n publisher: Publisher/organization name\n\n Returns:\n List of models from the publisher\n \"\"\"\n models = self.list_available_models()\n return [\n model\n for model in models\n if model.get(\"publisher\", \"\").lower() == publisher.lower()\n ]\n\n def get_models_by_type(self, model_type: str) -> List[Dict[str, Any]]:\n \"\"\"\n Get all models of a specific type.\n\n Args:\n model_type: Type of model (e.g., 'model', 'custom_model')\n\n Returns:\n List of models of the specified type\n \"\"\"\n models = self.list_available_models()\n return [model for model in models if model.get(\"type\") == model_type]\n\n def refresh_cache(self) -> None:\n \"\"\"Force refresh of the model cache.\"\"\"\n # First, force registry refresh to pick up any changes\n try:\n import os\n from pathlib import Path\n\n from hf_model_tool import get_registry\n\n # Clear all possible cache files\n cache_locations = [\n Path.home() / \".config/hf-model-tool/registry_cache.json\",\n Path.home() / \".cache/hf-model-tool/registry.json\",\n Path.home() / \".hf-model-tool/cache.json\",\n ]\n\n for cache_file in cache_locations:\n if cache_file.exists():\n try:\n os.remove(cache_file)\n logger.debug(f\"Removed cache file: {cache_file}\")\n except Exception as e:\n logger.debug(f\"Could not remove {cache_file}: {e}\")\n\n # Get registry and clear its in-memory cache\n registry = get_registry()\n\n # Clear all in-memory collections\n registry.models.clear()\n registry.custom_models.clear()\n registry.ollama_models.clear()\n registry.gguf_models.clear()\n registry.lora_adapters.clear()\n registry.datasets.clear()\n\n # Reset scan time to force rescan\n registry._last_scan_time = 0\n\n # Force complete rescan without incremental updates\n registry.scan_all(force=True, incremental=False)\n logger.info(\"Forced complete registry refresh\")\n except Exception as e:\n logger.debug(f\"Registry refresh error: {e}\")\n\n # Clear the cache to ensure we don't get stale data\n self.cache.clear_cache()\n logger.debug(\"Cache cleared\")\n\n # Now fetch fresh models - this will populate the cache with new data\n models = self.list_available_models(refresh=True)\n logger.info(f\"Model cache refreshed with {len(models)} models\")\n\n def get_cache_stats(self) -> Dict[str, Any]:\n \"\"\"\n Get cache statistics.\n\n Returns:\n Dictionary with cache statistics\n \"\"\"\n return self.cache.get_cache_stats()\n\n\n# Source: src/vllm_cli/ui/model_directories.py\nclass ModelDirectoriesUI:\n \"\"\"UI component for managing model directories.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize the Model Directories UI.\"\"\"\n self.api = None\n self._init_api()\n\n def _init_api(self):\n \"\"\"Initialize the hf-model-tool API.\"\"\"\n try:\n import sys\n\n # Add hf-model-tool to path if needed\n hf_tool_path = Path(\"/home/chen/hf-model-tool\")\n if hf_tool_path.exists() and str(hf_tool_path) not in sys.path:\n sys.path.insert(0, str(hf_tool_path))\n\n from hf_model_tool.api import HFModelAPI\n\n self.api = HFModelAPI()\n logger.info(\"Successfully initialized hf-model-tool API\")\n except ImportError as e:\n logger.error(f\"Failed to import hf-model-tool API: {e}\")\n self.api = None\n except Exception as e:\n logger.error(f\"Error initializing hf-model-tool API: {e}\")\n self.api = None\n\n def show(self) -> str:\n \"\"\"\n Show the model directories management interface.\n\n Returns:\n Action to take after directory management\n \"\"\"\n if not self.api:\n console.print(\n Panel.fit(\n \"[bold red]Error[/bold red]\\n\"\n \"[yellow]hf-model-tool is not available.[/yellow]\\n\\n\"\n \"Please ensure hf-model-tool is installed or updated:\\n\"\n \" [cyan]pip install --upgrade hf-model-tool[/cyan]\",\n border_style=\"red\",\n )\n )\n input(\"\\nPress Enter to continue...\")\n return \"continue\"\n\n while True:\n # Show header\n console.print(\n Panel.fit(\n \"[bold cyan]Model Directory Management[/bold cyan]\\n\"\n \"[dim]Configure directories for model discovery[/dim]\",\n border_style=\"blue\",\n )\n )\n\n # Display current directories\n self._display_directories()\n\n # Show menu options\n options = [\n \"Add Directory\",\n \"Remove Directory\",\n \"Toggle Ollama Scanning\",\n \"Scan All Directories\",\n \"View Directory Statistics\",\n ]\n\n action = unified_prompt(\n \"model_directories\", \"Directory Management\", options, allow_back=True\n )\n\n if action == \"← Back\" or action == \"BACK\" or not action:\n return \"continue\"\n elif action == \"Add Directory\":\n self._add_directory()\n elif action == \"Remove Directory\":\n self._remove_directory()\n elif action == \"Toggle Ollama Scanning\":\n self._toggle_ollama_scanning()\n elif action == \"Scan All Directories\":\n self._scan_directories()\n elif action == \"View Directory Statistics\":\n self._show_statistics()\n\n def _display_directories(self):\n \"\"\"Display currently configured directories.\"\"\"\n try:\n directories = self.api.list_directories()\n\n # Get Ollama status\n ollama_status = self.api.get_ollama_status()\n ollama_enabled = ollama_status.get(\"scan_enabled\", False)\n\n # Display Ollama scanning status\n if ollama_enabled:\n console.print(\n \"\\n[bold]Ollama Scanning:[/bold] [green]✓ Enabled[/green]\"\n )\n else:\n console.print(\"\\n[bold]Ollama Scanning:[/bold] [red]✗ Disabled[/red]\")\n\n if not directories:\n console.print(\"\\n[yellow]No directories configured.[/yellow]\")\n console.print(\"[dim]Using default locations only.[/dim]\\n\")\n return\n\n # Create table for directories\n table = Table(\n title=\"[bold]Configured Directories[/bold]\",\n show_header=True,\n header_style=\"bold cyan\",\n )\n table.add_column(\"#\", style=\"cyan\", width=3)\n table.add_column(\"Path\", style=\"white\")\n table.add_column(\"Type\", style=\"yellow\", width=15)\n table.add_column(\"Source\", style=\"magenta\", width=15)\n table.add_column(\"Status\", style=\"green\", width=10)\n\n for idx, dir_info in enumerate(directories, 1):\n path = dir_info.get(\"path\", \"\")\n dir_type = dir_info.get(\"type\", \"custom\")\n\n dir_source = dir_info.get(\"source\", \"unknown\")\n\n # Format source for display\n if dir_source == \"default_cache\":\n source_display = \"Default HF\"\n elif dir_source == \"default_ollama\":\n source_display = \"Default Ollama\"\n elif dir_source == \"custom_ollama\":\n source_display = \"Custom Ollama\"\n elif dir_source.startswith(\"custom\"):\n source_display = \"Custom\"\n else:\n source_display = dir_source.capitalize()\n\n # Check if directory exists\n path_obj = Path(path)\n status = (\n \"[green]✓ Valid[/green]\"\n if path_obj.exists()\n else \"[red]✗ Missing[/red]\"\n )\n\n table.add_row(\n str(idx), path, dir_type.capitalize(), source_display, status\n )\n\n console.print(table)\n console.print()\n\n except Exception as e:\n logger.error(f\"Error displaying directories: {e}\")\n console.print(f\"[red]Error loading directories: {e}[/red]\\n\")\n\n def _add_directory(self):\n \"\"\"Add a new directory for model scanning.\"\"\"\n console.print(\"\\n[bold cyan]Add Model Directory[/bold cyan]\")\n\n # Get directory path\n console.print(\"\\nEnter the full path to the directory containing models:\")\n console.print(\"[dim]Example: /home/user/models or ~/my_models[/dim]\")\n path = input(\"Path: \").strip()\n\n if not path:\n console.print(\"[yellow]No path provided, cancelling.[/yellow]\")\n input(\"\\nPress Enter to continue...\")\n return\n\n # Expand user path\n path = str(Path(path).expanduser().resolve())\n\n # Validate directory exists\n path_obj = Path(path)\n if not path_obj.exists():\n # Use unified prompt for confirmation\n create_choices = [\"Yes, create it\", \"No, cancel\"]\n create_choice = unified_prompt(\n \"create_dir\",\n f\"Directory '{path}' does not exist. Create it?\",\n create_choices,\n allow_back=False,\n )\n\n if create_choice == \"Yes, create it\":\n try:\n path_obj.mkdir(parents=True, exist_ok=True)\n console.print(f\"\\n[green]Created directory: {path}[/green]\")\n except Exception as e:\n console.print(f\"\\n[red]Failed to create directory: {e}[/red]\")\n input(\"\\nPress Enter to continue...\")\n return\n else:\n console.print(\"\\n[yellow]Directory must exist. Cancelling.[/yellow]\")\n input(\"\\nPress Enter to continue...\")\n return\n\n # Ask for directory type using unified prompt\n type_choices = [\n \"Auto-detect (recommended)\",\n \"HuggingFace cache\",\n \"Custom models\",\n \"LoRA adapters\",\n \"Ollama models\",\n ]\n\n type_selection = unified_prompt(\n \"dir_type\", \"Select directory type\", type_choices, allow_back=False\n )\n\n type_map = {\n \"Auto-detect (recommended)\": \"auto\",\n \"HuggingFace cache\": \"huggingface\",\n \"Custom models\": \"custom\",\n \"LoRA adapters\": \"lora\",\n \"Ollama models\": \"ollama\",\n }\n dir_type = type_map.get(type_selection, \"auto\")\n\n # Special handling for Ollama directories\n if dir_type == \"ollama\":\n # Check for Ollama structure\n has_manifests = (Path(path) / \"manifests\").exists()\n has_blobs = (Path(path) / \"blobs\").exists()\n\n if not (has_manifests and has_blobs):\n console.print(\n \"\\n[yellow]Warning: Directory doesn't have standard Ollama structure[/yellow]\"\n )\n console.print(f\" Manifests directory: {'✓' if has_manifests else '✗'}\")\n console.print(f\" Blobs directory: {'✓' if has_blobs else '✗'}\")\n\n # Ask if they want to add it anyway\n confirm_choices = [\"Yes, add anyway\", \"No, cancel\"]\n confirm_choice = unified_prompt(\n \"confirm_ollama\",\n \"Add as Ollama directory anyway?\",\n confirm_choices,\n allow_back=False,\n )\n\n if confirm_choice != \"Yes, add anyway\":\n console.print(\"\\n[yellow]Cancelled[/yellow]\")\n input(\"\\nPress Enter to continue...\")\n return\n\n # Add as Ollama directory\n try:\n success = self.api.add_ollama_directory(path)\n if success:\n console.print(\n f\"\\n[green]✓ Successfully added Ollama directory:[/green] {path}\"\n )\n\n # Enable Ollama scanning if not already enabled\n ollama_status = self.api.get_ollama_status()\n if not ollama_status.get(\"scan_enabled\", False):\n console.print(\n \"\\n[yellow]Note: Ollama scanning is currently disabled[/yellow]\"\n )\n enable_choices = [\"Yes, enable now\", \"No, keep disabled\"]\n enable_choice = unified_prompt(\n \"enable_ollama\",\n \"Enable Ollama scanning?\",\n enable_choices,\n allow_back=False,\n )\n\n if enable_choice == \"Yes, enable now\":\n self.api.toggle_ollama_scanning()\n console.print(\"[green]✓ Ollama scanning enabled[/green]\")\n else:\n console.print(\n \"\\n[red]Failed to add Ollama directory (may already exist)[/red]\"\n )\n except Exception as e:\n console.print(f\"\\n[red]Error adding Ollama directory: {e}[/red]\")\n\n input(\"\\nPress Enter to continue...\")\n return\n\n # Add regular directory\n try:\n success = self.api.add_directory(path, dir_type)\n if success:\n console.print(\n f\"\\n[green]✓ Successfully added directory:[/green] {path}\"\n )\n\n # Inform about manifest file\n manifest_path = Path(path) / \"models_manifest.json\"\n console.print(\n Panel.fit(\n \"[bold yellow]Note about Model Manifest:[/bold yellow]\\n\\n\"\n f\"A [cyan]models_manifest.json[/cyan] file will be auto-generated at:\\n\"\n f\"[dim]{manifest_path}[/dim]\\n\\n\"\n \"You can manually edit this file to customize:\\n\"\n \" • Custom display names\\n\"\n \" • Model descriptions\\n\"\n \" • Publisher information\\n\"\n \" • Model categories\\n\\n\"\n \"[dim]The manifest helps organize and customize how models appear.[/dim]\",\n border_style=\"yellow\",\n )\n )\n\n # Offer to scan immediately using unified prompt\n scan_choices = [\"Yes, scan now\", \"No, scan later\"]\n scan_choice = unified_prompt(\n \"scan_now\",\n \"Scan this directory for models now?\",\n scan_choices,\n allow_back=False,\n )\n\n if scan_choice == \"Yes, scan now\":\n self._scan_single_directory(path)\n\n # After scanning, remind about manifest if models were found\n console.print(\n \"\\n[dim]Tip: A models_manifest.json file has been auto-generated.[/dim]\"\n )\n console.print(\n \"[dim]You can edit it to customize how models appear in the serving menu.[/dim]\"\n )\n else:\n console.print(\"\\n[red]Failed to add directory.[/red]\")\n except Exception as e:\n console.print(f\"\\n[red]Error adding directory: {e}[/red]\")\n\n input(\"\\nPress Enter to continue...\")\n\n def _remove_directory(self):\n \"\"\"Remove a directory from scanning.\"\"\"\n directories = self.api.list_directories()\n\n if not directories:\n console.print(\"\\n[yellow]No directories to remove.[/yellow]\")\n input(\"\\nPress Enter to continue...\")\n return\n\n console.print(\"\\n[bold cyan]Remove Directory[/bold cyan]\")\n\n # Build choices list with directory paths\n dir_choices = []\n for dir_info in directories:\n path = dir_info.get(\"path\", \"\")\n dir_type = dir_info.get(\"type\", \"custom\")\n dir_choices.append(f\"{path} [{dir_type}]\")\n\n # Use unified prompt for selection\n selected = unified_prompt(\n \"remove_dir\", \"Select directory to remove\", dir_choices, allow_back=True\n )\n\n if not selected or selected == \"BACK\":\n return\n\n # Extract the path from the selection\n selected_path = selected.split(\" [\")[0] # Remove the [type] suffix\n\n # Find the matching directory\n for dir_info in directories:\n if dir_info.get(\"path\", \"\") == selected_path:\n # Confirm removal using unified prompt\n confirm_choices = [\"Yes, remove this directory\", \"No, keep it\"]\n confirm = unified_prompt(\n \"confirm_remove\",\n f\"Remove {selected_path}?\",\n confirm_choices,\n allow_back=False,\n )\n\n if confirm == \"Yes, remove this directory\":\n try:\n # Check if it's an Ollama directory\n dir_source = dir_info.get(\"source\", \"\")\n if dir_info.get(\"type\") == \"ollama\" and \"ollama\" in dir_source:\n # Remove as Ollama directory\n success = self.api.remove_ollama_directory(selected_path)\n else:\n # Remove as regular directory\n success = self.api.remove_directory(selected_path)\n\n if success:\n console.print(\n f\"\\n[green]✓ Removed directory: {selected_path}[/green]\"\n )\n else:\n console.print(\"\\n[red]Failed to remove directory.[/red]\")\n except Exception as e:\n console.print(f\"\\n[red]Error removing directory: {e}[/red]\")\n else:\n console.print(\"\\n[yellow]Directory not removed.[/yellow]\")\n break\n\n input(\"\\nPress Enter to continue...\")\n\n def _scan_directories(self):\n \"\"\"Scan all configured directories for models.\"\"\"\n console.print(\"\\n[bold cyan]Scanning Directories[/bold cyan]\")\n console.print(\"[dim]This may take a moment for large directories...[/dim]\\n\")\n\n try:\n # Force refresh to get latest data\n assets = self.api.list_assets(force_refresh=True)\n\n # Group by type\n models = [a for a in assets if a.get(\"type\") == \"model\"]\n custom_models = [a for a in assets if a.get(\"type\") == \"custom_model\"]\n lora_adapters = [a for a in assets if a.get(\"type\") == \"lora_adapter\"]\n datasets = [a for a in assets if a.get(\"type\") == \"dataset\"]\n\n # Display summary\n console.print(\"[bold]Scan Results:[/bold]\")\n console.print(f\" Models: [cyan]{len(models)}[/cyan]\")\n console.print(f\" Custom Models: [cyan]{len(custom_models)}[/cyan]\")\n console.print(f\" LoRA Adapters: [cyan]{len(lora_adapters)}[/cyan]\")\n console.print(f\" Datasets: [cyan]{len(datasets)}[/cyan]\")\n console.print(f\" [bold]Total Assets: [green]{len(assets)}[/green][/bold]\")\n\n # Show top models by size\n if models or custom_models:\n all_models = models + custom_models\n all_models.sort(key=lambda x: x.get(\"size\", 0), reverse=True)\n\n console.print(\"\\n[bold]Top Models by Size:[/bold]\")\n for model in all_models[:5]:\n name = model.get(\"display_name\", model.get(\"name\", \"Unknown\"))\n size = model.get(\"size\", 0)\n size_gb = size / (1024**3)\n console.print(f\" • {name}: [yellow]{size_gb:.2f} GB[/yellow]\")\n\n except Exception as e:\n console.print(f\"[red]Error scanning directories: {e}[/red]\")\n\n input(\"\\nPress Enter to continue...\")\n\n def _scan_single_directory(self, path: str):\n \"\"\"Scan a single directory for models.\"\"\"\n console.print(f\"\\n[cyan]Scanning: {path}[/cyan]\")\n\n try:\n assets = self.api.scan_directories([path])\n\n if assets:\n console.print(f\"[green]Found {len(assets)} asset(s):[/green]\")\n for asset in assets[:5]: # Show first 5\n name = asset.get(\"display_name\", asset.get(\"name\", \"Unknown\"))\n asset_type = asset.get(\"type\", \"unknown\")\n console.print(f\" • {name} ([yellow]{asset_type}[/yellow])\")\n if len(assets) > 5:\n console.print(f\" [dim]... and {len(assets) - 5} more[/dim]\")\n else:\n console.print(\"[yellow]No models found in this directory.[/yellow]\")\n\n except Exception as e:\n console.print(f\"[red]Error scanning directory: {e}[/red]\")\n\n def _toggle_ollama_scanning(self):\n \"\"\"Toggle Ollama model scanning on/off.\"\"\"\n console.print(\"\\n[bold cyan]Ollama Model Scanning[/bold cyan]\")\n\n try:\n # Get current status\n ollama_status = self.api.get_ollama_status()\n current_state = ollama_status.get(\"scan_enabled\", False)\n\n # Display current state\n if current_state:\n console.print(\n \"\\nOllama scanning is currently: [green]✓ Enabled[/green]\"\n )\n console.print(\"\\nDefault Ollama directories being scanned:\")\n for dir_path in ollama_status.get(\"default_directories\", []):\n if Path(dir_path).exists():\n console.print(f\" • {dir_path}\")\n else:\n console.print(\"\\nOllama scanning is currently: [red]✗ Disabled[/red]\")\n console.print(\"\\n[dim]Enable to scan Ollama model directories[/dim]\")\n\n # Ask to toggle\n toggle_choices = [\n \"Yes, toggle it\" if current_state else \"Yes, enable it\",\n \"No, keep current setting\",\n ]\n\n toggle_choice = unified_prompt(\n \"toggle_ollama\",\n f\"{'Disable' if current_state else 'Enable'} Ollama scanning?\",\n toggle_choices,\n allow_back=False,\n )\n\n if toggle_choice and toggle_choice.startswith(\"Yes\"):\n new_state = self.api.toggle_ollama_scanning()\n\n if new_state:\n console.print(\"\\n[green]✓ Ollama scanning enabled[/green]\")\n console.print(\n \"[dim]Ollama models will now be included in scans[/dim]\"\n )\n else:\n console.print(\"\\n[yellow]Ollama scanning disabled[/yellow]\")\n console.print(\n \"[dim]Ollama models will be excluded from scans[/dim]\"\n )\n\n # Offer to refresh cache\n refresh_choices = [\"Yes, refresh now\", \"No, refresh later\"]\n refresh_choice = unified_prompt(\n \"refresh_cache\",\n \"Refresh model cache to apply changes?\",\n refresh_choices,\n allow_back=False,\n )\n\n if refresh_choice == \"Yes, refresh now\":\n console.print(\"\\n[cyan]Refreshing model cache...[/cyan]\")\n\n # Import and use model manager to refresh\n try:\n from ..models import get_model_manager\n\n model_manager = get_model_manager()\n model_manager.refresh_cache()\n console.print(\"[green]✓ Model cache refreshed[/green]\")\n except Exception as e:\n console.print(f\"[red]Failed to refresh cache: {e}[/red]\")\n else:\n console.print(\"\\n[yellow]Settings unchanged[/yellow]\")\n\n except Exception as e:\n console.print(f\"\\n[red]Error toggling Ollama scanning: {e}[/red]\")\n\n input(\"\\nPress Enter to continue...\")\n\n def _show_statistics(self):\n \"\"\"Show statistics about managed assets.\"\"\"\n console.print(\"\\n[bold cyan]Asset Statistics[/bold cyan]\\n\")\n\n try:\n stats = self.api.get_statistics()\n\n # Create statistics panels\n panels = []\n\n # Models panel\n model_text = Text()\n model_text.append(\"Models\\n\", style=\"bold yellow\")\n model_text.append(f\"Total: {stats.get('total_models', 0)}\\n\")\n model_text.append(f\"Custom: {stats.get('custom_models', 0)}\\n\")\n model_text.append(f\"LoRA: {stats.get('lora_adapters', 0)}\")\n panels.append(Panel(model_text, border_style=\"yellow\"))\n\n # Storage panel\n storage_text = Text()\n storage_text.append(\"Storage\\n\", style=\"bold cyan\")\n total_size = stats.get(\"total_size\", 0)\n size_gb = total_size / (1024**3)\n storage_text.append(f\"Total: {size_gb:.2f} GB\\n\")\n storage_text.append(f\"Datasets: {stats.get('dataset_count', 0)}\")\n panels.append(Panel(storage_text, border_style=\"cyan\"))\n\n # Directories panel\n dir_text = Text()\n dir_text.append(\"Directories\\n\", style=\"bold green\")\n dir_text.append(f\"Monitored: {stats.get('directories', 0)}\\n\")\n dir_text.append(\"Last scan: Recent\")\n panels.append(Panel(dir_text, border_style=\"green\"))\n\n console.print(Columns(panels))\n\n # Show breakdown by directory if available\n if \"by_directory\" in stats:\n console.print(\"\\n[bold]By Directory:[/bold]\")\n for dir_path, dir_stats in stats[\"by_directory\"].items():\n console.print(f\"\\n [cyan]{dir_path}[/cyan]\")\n console.print(f\" Models: {dir_stats.get('models', 0)}\")\n console.print(\n f\" Size: {dir_stats.get('size', 0) / (1024**3):.2f} GB\"\n )\n\n except Exception as e:\n console.print(f\"[red]Error getting statistics: {e}[/red]\")\n\n input(\"\\nPress Enter to continue...\")", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 32821}, "tests/proxy/test_models.py::42": {"resolved_imports": ["src/vllm_cli/proxy/models.py"], "used_names": ["ModelConfig"], "enclosing_function": "test_model_config_defaults", "extracted_code": "# Source: src/vllm_cli/proxy/models.py\nclass ModelConfig(BaseModel):\n \"\"\"Configuration for a single model in the proxy.\"\"\"\n\n name: str = Field(..., description=\"Model identifier for API requests\")\n model_path: str = Field(..., description=\"Path or HuggingFace model ID\")\n gpu_ids: List[int] = Field(default_factory=list, description=\"GPU IDs to use\")\n port: int = Field(..., description=\"Port for the vLLM server\")\n profile: Optional[str] = Field(None, description=\"vLLM CLI profile to use\")\n config_overrides: Dict[str, Any] = Field(\n default_factory=dict, description=\"Additional vLLM configuration\"\n )\n enabled: bool = Field(True, description=\"Whether model is enabled\")\n loading_priority: Optional[int] = Field(\n None,\n description=\"Loading priority (lower numbers load first). \"\n \"Models with same priority load in parallel. \"\n \"Models with None priority load after all prioritized models.\",\n )", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 967}, "tests/proxy/test_models.py::250": {"resolved_imports": ["src/vllm_cli/proxy/models.py"], "used_names": ["ModelStatus", "ProxyStatus"], "enclosing_function": "test_proxy_status_creation", "extracted_code": "# Source: src/vllm_cli/proxy/models.py\nclass ModelStatus(BaseModel):\n \"\"\"Status information for a model.\"\"\"\n\n name: str\n model_path: str\n port: int\n gpu_ids: List[int]\n status: str # \"running\", \"starting\", \"stopped\", \"error\"\n registration_status: Optional[str] = None # \"pending\", \"available\", \"error\"\n uptime: Optional[float] = None\n error_message: Optional[str] = None\n request_count: int = 0\n last_request_time: Optional[str] = None\n\nclass ProxyStatus(BaseModel):\n \"\"\"Overall proxy server status.\"\"\"\n\n proxy_running: bool\n proxy_port: int\n proxy_host: str\n models: List[ModelStatus]\n total_requests: int = 0\n start_time: Optional[str] = None", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 700}, "tests/proxy/test_server.py::501": {"resolved_imports": ["src/vllm_cli/proxy/models.py", "src/vllm_cli/proxy/registry.py", "src/vllm_cli/proxy/server.py"], "used_names": [], "enclosing_function": "test_get_status_summary", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_ollama_integration_fixed.py::228": {"resolved_imports": ["src/vllm_cli/models/cache.py", "src/vllm_cli/models/manager.py"], "used_names": ["ModelManager", "patch"], "enclosing_function": "test_missing_directories_handling", "extracted_code": "# Source: src/vllm_cli/models/manager.py\nclass ModelManager:\n \"\"\"\n Manages model discovery, caching, and metadata operations.\n\n Provides a high-level interface for model operations including\n listing, searching, and retrieving model information with\n integrated caching for performance.\n \"\"\"\n\n def __init__(self):\n self.cache = ModelCache()\n\n def list_available_models(self, refresh: bool = False) -> List[Dict[str, Any]]:\n \"\"\"\n List all available downloaded models with caching.\n\n Model scanning can be expensive, so results are cached for a short time\n to improve performance when multiple UI components need model data.\n\n Args:\n refresh: Force refresh the model cache, ignoring TTL\n\n Returns:\n List of model dictionaries with keys:\n - name: Full model name (publisher/model)\n - size: Model size in bytes\n - path: Path to model directory\n - type: Model type (model, custom_model)\n - publisher: Model publisher/organization\n - display_name: Human-readable model name\n - metadata: Additional model metadata\n \"\"\"\n # If refresh is forced, clear cache first to ensure fresh data\n if refresh:\n self.cache.clear_cache()\n logger.debug(\"Cache cleared for forced refresh\")\n else:\n # Check cache only if not refreshing\n cached_models = self.cache.get_cached_models()\n if cached_models is not None:\n return cached_models\n\n # Fetch fresh model data\n models = scan_for_models()\n\n # Process and normalize model data\n processed_models = []\n for item in models:\n # Accept all model types from hf-model-tool\n model_types = [\"model\", \"custom_model\", \"ollama_model\", \"gguf_model\"]\n if item.get(\"type\") in model_types:\n # For Ollama/GGUF models, use the item directly (already formatted)\n if item.get(\"type\") in [\"ollama_model\", \"gguf_model\"]:\n processed_models.append(item)\n else:\n model_dict = build_model_dict(item)\n processed_models.append(model_dict)\n\n # Sort models by name\n processed_models.sort(key=lambda x: x[\"name\"])\n\n # Update cache\n self.cache.cache_models(processed_models)\n\n logger.info(f\"Found {len(processed_models)} models\")\n return processed_models\n\n def get_model_details(self, model_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get detailed information about a specific model.\n\n Args:\n model_name: Name of the model to get details for\n\n Returns:\n Dictionary with model details or None if not found\n \"\"\"\n # First, try to find from cached models\n models = self.list_available_models()\n model_info = None\n\n for model in models:\n if model[\"name\"] == model_name or model.get(\"display_name\") == model_name:\n model_info = model\n break\n\n if not model_info:\n logger.warning(f\"Model {model_name} not found\")\n return None\n\n # Build detailed information\n details = {\n \"name\": model_info[\"name\"],\n \"full_name\": model_info[\"name\"],\n \"path\": model_info.get(\"path\", \"\"),\n \"size\": model_info.get(\"size\", 0),\n \"type\": model_info.get(\"type\", \"model\"),\n \"publisher\": model_info.get(\"publisher\", \"unknown\"),\n \"display_name\": model_info.get(\"display_name\", model_name),\n }\n\n # Extract metadata if available\n metadata = model_info.get(\"metadata\", {})\n if metadata:\n details[\"architecture\"] = (\n metadata.get(\"architectures\", [\"unknown\"])[0]\n if metadata.get(\"architectures\")\n else \"unknown\"\n )\n details[\"model_type\"] = metadata.get(\"model_type\", \"unknown\")\n details[\"torch_dtype\"] = metadata.get(\"torch_dtype\", \"unknown\")\n details[\"vocab_size\"] = metadata.get(\"vocab_size\", \"unknown\")\n\n # Add to main details\n details[\"metadata\"] = metadata\n\n # Try to read config.json for more details if path exists\n if details[\"path\"]:\n from .metadata import extract_model_config\n\n config_data = extract_model_config(details[\"path\"])\n if config_data:\n details.update(config_data)\n\n return details\n\n def search_models(self, query: str) -> List[Dict[str, Any]]:\n \"\"\"\n Search for models matching a query.\n\n Args:\n query: Search query string\n\n Returns:\n List of matching models\n \"\"\"\n models = self.list_available_models()\n query_lower = query.lower()\n\n # Filter models matching the query\n matches = []\n for model in models:\n if (\n query_lower in model[\"name\"].lower()\n or query_lower in model.get(\"display_name\", \"\").lower()\n or query_lower in model.get(\"publisher\", \"\").lower()\n ):\n matches.append(model)\n\n return matches\n\n def get_model_count(self) -> int:\n \"\"\"\n Get the total number of available models.\n\n Returns:\n Number of available models\n \"\"\"\n return len(self.list_available_models())\n\n def get_models_by_publisher(self, publisher: str) -> List[Dict[str, Any]]:\n \"\"\"\n Get all models from a specific publisher.\n\n Args:\n publisher: Publisher/organization name\n\n Returns:\n List of models from the publisher\n \"\"\"\n models = self.list_available_models()\n return [\n model\n for model in models\n if model.get(\"publisher\", \"\").lower() == publisher.lower()\n ]\n\n def get_models_by_type(self, model_type: str) -> List[Dict[str, Any]]:\n \"\"\"\n Get all models of a specific type.\n\n Args:\n model_type: Type of model (e.g., 'model', 'custom_model')\n\n Returns:\n List of models of the specified type\n \"\"\"\n models = self.list_available_models()\n return [model for model in models if model.get(\"type\") == model_type]\n\n def refresh_cache(self) -> None:\n \"\"\"Force refresh of the model cache.\"\"\"\n # First, force registry refresh to pick up any changes\n try:\n import os\n from pathlib import Path\n\n from hf_model_tool import get_registry\n\n # Clear all possible cache files\n cache_locations = [\n Path.home() / \".config/hf-model-tool/registry_cache.json\",\n Path.home() / \".cache/hf-model-tool/registry.json\",\n Path.home() / \".hf-model-tool/cache.json\",\n ]\n\n for cache_file in cache_locations:\n if cache_file.exists():\n try:\n os.remove(cache_file)\n logger.debug(f\"Removed cache file: {cache_file}\")\n except Exception as e:\n logger.debug(f\"Could not remove {cache_file}: {e}\")\n\n # Get registry and clear its in-memory cache\n registry = get_registry()\n\n # Clear all in-memory collections\n registry.models.clear()\n registry.custom_models.clear()\n registry.ollama_models.clear()\n registry.gguf_models.clear()\n registry.lora_adapters.clear()\n registry.datasets.clear()\n\n # Reset scan time to force rescan\n registry._last_scan_time = 0\n\n # Force complete rescan without incremental updates\n registry.scan_all(force=True, incremental=False)\n logger.info(\"Forced complete registry refresh\")\n except Exception as e:\n logger.debug(f\"Registry refresh error: {e}\")\n\n # Clear the cache to ensure we don't get stale data\n self.cache.clear_cache()\n logger.debug(\"Cache cleared\")\n\n # Now fetch fresh models - this will populate the cache with new data\n models = self.list_available_models(refresh=True)\n logger.info(f\"Model cache refreshed with {len(models)} models\")\n\n def get_cache_stats(self) -> Dict[str, Any]:\n \"\"\"\n Get cache statistics.\n\n Returns:\n Dictionary with cache statistics\n \"\"\"\n return self.cache.get_cache_stats()", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 8654}, "tests/test_config_manager.py::57": {"resolved_imports": ["src/vllm_cli/config/manager.py"], "used_names": ["ConfigManager", "patch", "yaml"], "enclosing_function": "test_load_existing_config", "extracted_code": "# Source: src/vllm_cli/config/manager.py\nclass ConfigManager:\n \"\"\"\n Enhanced configuration manager with comprehensive validation support.\n\n This class manages configuration files, profiles, and validation using\n the new validation framework. It provides a clean API for configuration\n operations while ensuring data integrity through comprehensive validation.\n\n Attributes:\n config_dir: Directory for configuration files\n validation_registry: Registry of validation rules\n compatibility_validator: Validator for parameter combinations\n \"\"\"\n\n def __init__(self):\n # Paths for configuration files\n self.config_dir = Path.home() / \".config\" / \"vllm-cli\"\n self.config_file = self.config_dir / \"config.yaml\"\n\n # Ensure config directory exists\n self.config_dir.mkdir(parents=True, exist_ok=True)\n\n # Initialize sub-managers\n self.schema_manager = SchemaManager()\n self.profile_manager = ProfileManager(self.config_dir)\n self.persistence_manager = PersistenceManager()\n self.shortcut_manager = ShortcutManager(self.config_dir)\n\n # Initialize validation system\n self.validation_registry = create_vllm_validation_registry()\n self.compatibility_validator = create_compatibility_validator(\n self.validation_registry\n )\n\n # Load main configuration\n self.config = self._load_config()\n\n def _load_config(self) -> Dict[str, Any]:\n \"\"\"Load main configuration file (legacy YAML support).\"\"\"\n return self.persistence_manager.load_yaml_file(self.config_file)\n\n def _save_config(self) -> None:\n \"\"\"Save main configuration file.\"\"\"\n self.persistence_manager.save_yaml_file(self.config_file, self.config)\n\n def get_argument_info(self, arg_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get detailed information about a specific argument.\"\"\"\n return self.schema_manager.get_argument_info(arg_name)\n\n def get_arguments_by_category(self, category: str) -> List[Dict[str, Any]]:\n \"\"\"Get all arguments belonging to a specific category.\"\"\"\n return self.schema_manager.get_arguments_by_category(category)\n\n def get_category_info(self, category: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get information about a specific category.\"\"\"\n return self.schema_manager.get_category_info(category)\n\n def get_ordered_categories(self) -> List[Tuple[str, Dict[str, Any]]]:\n \"\"\"Get categories ordered by their display order.\"\"\"\n return self.schema_manager.get_ordered_categories()\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n return self.profile_manager.get_all_profiles()\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name with dynamic defaults applied.\"\"\"\n profile = self.profile_manager.get_profile(name)\n if profile and \"config\" in profile:\n # Apply dynamic defaults to the profile configuration\n profile[\"config\"] = self.profile_manager.apply_dynamic_defaults(\n profile[\"config\"]\n )\n return profile\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"Save or update a user profile with validation.\"\"\"\n # Validate profile configuration if present\n if \"config\" in profile:\n is_valid, errors = self.validate_config(profile[\"config\"])\n if not is_valid:\n from ..errors import ProfileError\n\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n return self.profile_manager.save_user_profile(name, profile)\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n return self.profile_manager.delete_user_profile(name)\n\n @property\n def default_profiles(self) -> Dict[str, Any]:\n \"\"\"Get default profiles.\"\"\"\n return self.profile_manager.default_profiles\n\n @property\n def user_profiles(self) -> Dict[str, Any]:\n \"\"\"Get user profiles.\"\"\"\n return self.profile_manager.user_profiles\n\n def validate_config(self, config: Dict[str, Any]) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate a configuration using the new validation framework.\n\n This method uses the comprehensive validation system to check\n configuration values, types, ranges, and dependencies.\n\n Args:\n config: Configuration dictionary to validate\n\n Returns:\n Tuple of (is_valid, list_of_error_messages)\n\n Raises:\n ConfigurationError: If validation system fails\n \"\"\"\n try:\n # Use new validation system\n result = self.validation_registry.validate_config(config)\n\n # Convert validation errors to string messages for backward compatibility\n error_messages = result.get_error_messages()\n\n # Add warnings if any\n if result.warnings:\n for warning in result.warnings:\n logger.warning(f\"Configuration warning: {warning}\")\n\n return result.is_valid(), error_messages\n\n except Exception as e:\n logger.error(f\"Error during configuration validation: {e}\")\n raise ConfigurationError(\n f\"Validation system error: {e}\", error_code=\"VALIDATION_SYSTEM_ERROR\"\n ) from e\n\n def validate_argument_combination(\n self, config: Dict[str, Any]\n ) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate that argument combinations are compatible using the new compatibility validator.\n\n Args:\n config: Configuration dictionary to check for compatibility\n\n Returns:\n Tuple of (is_valid, list_of_warnings_or_errors)\n \"\"\"\n try:\n issues = self.compatibility_validator.validate_compatibility(config)\n\n warnings = []\n errors = []\n\n for issue in issues:\n message = issue[\"message\"]\n if issue[\"severity\"] == \"error\":\n errors.append(message)\n else:\n warnings.append(message)\n\n # Log warnings\n for warning in warnings:\n logger.warning(f\"Configuration compatibility warning: {warning}\")\n\n # Return all issues as warnings for backward compatibility\n # (errors are treated as warnings in the legacy interface)\n all_issues = errors + warnings\n\n return len(errors) == 0, all_issues\n\n except Exception as e:\n logger.error(f\"Error during compatibility validation: {e}\")\n return False, [f\"Compatibility validation error: {e}\"]\n\n def build_cli_args(self, config: Dict[str, Any]) -> List[str]:\n \"\"\"\n Build command-line arguments from a configuration dictionary.\n\n Only includes arguments that are explicitly set in the config.\n Handles special cases like LoRA modules.\n \"\"\"\n args = []\n\n # Special handling for model (positional argument)\n # Check if this is a GGUF/Ollama configuration\n if (\n isinstance(config.get(\"model\"), dict)\n and \"quantization\" in config[\"model\"]\n and config[\"model\"][\"quantization\"] == \"gguf\"\n ):\n # Extract GGUF model config\n gguf_config = config[\"model\"]\n model_path = gguf_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", model_path])\n\n # Set quantization to gguf\n config[\"quantization\"] = \"gguf\"\n\n # Add served-model-name if provided (for Ollama models)\n if \"served_model_name\" in gguf_config:\n config[\"served_model_name\"] = gguf_config[\"served_model_name\"]\n logger.info(\n f\"Configuring GGUF model: {model_path} as {gguf_config['served_model_name']}\"\n )\n else:\n logger.info(f\"Configuring GGUF model: {model_path}\")\n\n # Check if this is a LoRA configuration\n elif (\n isinstance(config.get(\"model\"), dict) and \"lora_modules\" in config[\"model\"]\n ):\n # Extract base model and LoRA config\n lora_config = config[\"model\"]\n base_model = lora_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", base_model])\n\n # Enable LoRA support when modules are present\n args.append(\"--enable-lora\")\n\n # Track maximum rank for all LoRA modules\n max_rank = 16 # Default minimum\n\n # Add LoRA modules\n for lora in lora_config.get(\"lora_modules\", []):\n lora_path = lora.get(\"path\", \"\")\n if lora_path:\n # vLLM expects --lora-modules with name=path format\n lora_name = lora.get(\"name\", \"adapter\")\n args.extend([\"--lora-modules\", f\"{lora_name}={lora_path}\"])\n\n # Track maximum rank\n lora_rank = lora.get(\"rank\", 16)\n max_rank = max(max_rank, lora_rank)\n\n # Add max-lora-rank parameter\n args.extend([\"--max-lora-rank\", str(max_rank)])\n\n elif \"model\" in config:\n args.extend([\"serve\", config[\"model\"]])\n\n # Handle lora_modules if present as a string (from CLI)\n if \"lora_modules\" in config and config[\"lora_modules\"]:\n # Enable LoRA support\n if \"--enable-lora\" not in args:\n args.append(\"--enable-lora\")\n\n # Parse and add LoRA modules\n lora_modules_str = config[\"lora_modules\"]\n if isinstance(lora_modules_str, str):\n # Split by space and add each module\n for module in lora_modules_str.split():\n args.extend([\"--lora-modules\", module])\n\n # Add max-lora-rank if not already added\n # Use a safe default of 64 which should cover most LoRA adapters\n if \"--max-lora-rank\" not in args:\n # Check if max_lora_rank is explicitly set in config\n if \"max_lora_rank\" not in config:\n args.extend([\"--max-lora-rank\", \"64\"])\n\n for arg_name, value in config.items():\n # Skip special keys and None values\n if (\n arg_name in [\"model\", \"name\", \"description\", \"icon\", \"lora_modules\"]\n or value is None\n ):\n continue\n\n arg_info = self.schema_manager.get_argument_info(arg_name)\n if not arg_info:\n logger.warning(f\"Unknown argument in config: {arg_name}\")\n continue\n\n cli_flag = arg_info.get(\"cli_flag\")\n if not cli_flag:\n continue\n\n arg_type = arg_info.get(\"type\")\n\n if arg_type == \"boolean\":\n if value: # Only add flag if True\n args.append(cli_flag)\n elif arg_type in [\"integer\", \"float\", \"string\", \"choice\"]:\n args.extend([cli_flag, str(value)])\n else:\n logger.warning(f\"Unknown argument type for {arg_name}: {arg_type}\")\n\n return args\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n return self.profile_manager.export_profile(profile_name, filepath)\n\n def import_profile(self, filepath: Path, new_name: Optional[str] = None) -> bool:\n \"\"\"Import a profile from a JSON file with comprehensive validation.\"\"\"\n return self.profile_manager.import_profile(\n filepath, new_name, self.validate_config\n )\n\n def get_last_config(self) -> Optional[Dict[str, Any]]:\n \"\"\"Get the last used server configuration.\"\"\"\n return self.config.get(\"last_config\")\n\n def save_last_config(self, config: Dict[str, Any]) -> None:\n \"\"\"Save the last used server configuration.\"\"\"\n self.config[\"last_config\"] = config\n self._save_config()\n\n def get_recent_models(self, limit: int = 5) -> List[str]:\n \"\"\"Get recently used models.\"\"\"\n return self.config.get(\"recent_models\", [])[:limit]\n\n def add_recent_model(self, model: str) -> None:\n \"\"\"Add a model to recent models list.\"\"\"\n recent = self.config.get(\"recent_models\", [])\n if model in recent:\n recent.remove(model)\n recent.insert(0, model)\n self.config[\"recent_models\"] = recent[:10] # Keep only last 10\n self._save_config()\n\n def clear_cache(self) -> None:\n \"\"\"Clear cached data.\"\"\"\n cache_file = self.config_dir / \"cache.json\"\n if cache_file.exists():\n cache_file.unlink()\n self.config.pop(\"last_config\", None)\n self.config.pop(\"recent_models\", None)\n self._save_config()\n logger.info(\"Cache cleared\")\n\n def get_server_defaults(self) -> Dict[str, Any]:\n \"\"\"Get default server settings.\"\"\"\n return self.config.get(\n \"server_defaults\",\n {\n \"default_port\": 8000,\n \"auto_restart\": False,\n \"log_level\": \"info\",\n \"cleanup_on_exit\": True, # Default to cleaning up servers on exit\n },\n )\n\n def save_server_defaults(self, defaults: Dict[str, Any]) -> None:\n \"\"\"Save default server settings.\"\"\"\n self.config[\"server_defaults\"] = defaults\n self._save_config()\n\n def get_ui_preferences(self) -> Dict[str, Any]:\n \"\"\"Get UI preferences including progress bar style and log display settings.\"\"\"\n return self.config.get(\n \"ui_preferences\",\n {\n \"progress_bar_style\": \"blocks\", # Default style\n \"show_gpu_in_monitor\": True,\n \"log_lines_startup\": 50, # Number of log lines to show during startup\n \"log_lines_monitor\": 50, # Number of log lines to show in server monitor\n \"startup_refresh_rate\": 4.0, # Hz for startup log refresh\n \"monitor_refresh_rate\": 1.0, # Hz for monitor log refresh\n },\n )\n\n def save_ui_preferences(self, preferences: Dict[str, Any]) -> None:\n \"\"\"Save UI preferences.\"\"\"\n self.config[\"ui_preferences\"] = preferences\n self._save_config()\n\n # Shortcut management methods\n def get_all_shortcuts(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all shortcuts.\"\"\"\n return self.shortcut_manager.get_all_shortcuts()\n\n def get_shortcut(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific shortcut by name.\"\"\"\n return self.shortcut_manager.get_shortcut(name)\n\n def save_shortcut(self, name: str, shortcut_data: Dict[str, Any]) -> bool:\n \"\"\"Save or update a shortcut.\"\"\"\n return self.shortcut_manager.save_shortcut(name, shortcut_data)\n\n def delete_shortcut(self, name: str) -> bool:\n \"\"\"Delete a shortcut.\"\"\"\n return self.shortcut_manager.delete_shortcut(name)\n\n def list_shortcuts(self) -> List[Dict[str, Any]]:\n \"\"\"List all shortcuts with summary information.\"\"\"\n return self.shortcut_manager.list_shortcuts()\n\n def get_recent_shortcuts(self, limit: int = 5) -> List[Dict[str, Any]]:\n \"\"\"Get recently used shortcuts.\"\"\"\n return self.shortcut_manager.get_recent_shortcuts(limit)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 15704}, "tests/proxy/test_router.py::77": {"resolved_imports": ["src/vllm_cli/proxy/router.py"], "used_names": [], "enclosing_function": "test_wildcard_backend", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_cli_parser.py::28": {"resolved_imports": ["src/vllm_cli/cli/parser.py"], "used_names": ["create_parser"], "enclosing_function": "test_serve_command_basic", "extracted_code": "# Source: src/vllm_cli/cli/parser.py\ndef create_parser() -> argparse.ArgumentParser:\n \"\"\"\n Create the main argument parser for vLLM CLI.\n\n Sets up the main parser with all subcommands and their arguments.\n\n Returns:\n Configured ArgumentParser instance\n \"\"\"\n parser = argparse.ArgumentParser(\n prog=\"vllm-cli\",\n description=\"vLLM CLI - Convenient LLM serving tool\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"Examples:\n vllm-cli # Interactive mode\n vllm-cli serve MODEL --profile standard # Serve with profile\n vllm-cli serve MODEL --quantization awq # Serve with AWQ quantization\n vllm-cli serve MODEL --extra-args \"--seed 42\" # With custom vLLM args\n vllm-cli info # System information\n vllm-cli models # List available models\n vllm-cli status # Show active servers\"\"\",\n )\n\n # Global options\n from .. import __version__\n\n parser.add_argument(\n \"--version\", action=\"version\", version=f\"vLLM CLI {__version__}\"\n )\n\n # Create subparsers for commands\n subparsers = parser.add_subparsers(\n dest=\"command\",\n help=\"Available commands\",\n metavar=\"{serve,proxy,info,models,shortcuts,status,stop,dirs}\",\n )\n\n # Add individual command parsers\n _add_serve_parser(subparsers)\n _add_proxy_parser(subparsers)\n _add_info_parser(subparsers)\n _add_models_parser(subparsers)\n _add_shortcuts_parser(subparsers)\n _add_status_parser(subparsers)\n _add_stop_parser(subparsers)\n _add_dirs_parser(subparsers)\n\n return parser", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1705}, "tests/test_custom_directory_integration.py::139": {"resolved_imports": ["src/vllm_cli/models/manager.py", "src/vllm_cli/models/manifest.py", "src/vllm_cli/ui/model_directories.py"], "used_names": ["ModelDirectoriesUI"], "enclosing_function": "test_add_custom_directory", "extracted_code": "# Source: src/vllm_cli/ui/model_directories.py\nclass ModelDirectoriesUI:\n \"\"\"UI component for managing model directories.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize the Model Directories UI.\"\"\"\n self.api = None\n self._init_api()\n\n def _init_api(self):\n \"\"\"Initialize the hf-model-tool API.\"\"\"\n try:\n import sys\n\n # Add hf-model-tool to path if needed\n hf_tool_path = Path(\"/home/chen/hf-model-tool\")\n if hf_tool_path.exists() and str(hf_tool_path) not in sys.path:\n sys.path.insert(0, str(hf_tool_path))\n\n from hf_model_tool.api import HFModelAPI\n\n self.api = HFModelAPI()\n logger.info(\"Successfully initialized hf-model-tool API\")\n except ImportError as e:\n logger.error(f\"Failed to import hf-model-tool API: {e}\")\n self.api = None\n except Exception as e:\n logger.error(f\"Error initializing hf-model-tool API: {e}\")\n self.api = None\n\n def show(self) -> str:\n \"\"\"\n Show the model directories management interface.\n\n Returns:\n Action to take after directory management\n \"\"\"\n if not self.api:\n console.print(\n Panel.fit(\n \"[bold red]Error[/bold red]\\n\"\n \"[yellow]hf-model-tool is not available.[/yellow]\\n\\n\"\n \"Please ensure hf-model-tool is installed or updated:\\n\"\n \" [cyan]pip install --upgrade hf-model-tool[/cyan]\",\n border_style=\"red\",\n )\n )\n input(\"\\nPress Enter to continue...\")\n return \"continue\"\n\n while True:\n # Show header\n console.print(\n Panel.fit(\n \"[bold cyan]Model Directory Management[/bold cyan]\\n\"\n \"[dim]Configure directories for model discovery[/dim]\",\n border_style=\"blue\",\n )\n )\n\n # Display current directories\n self._display_directories()\n\n # Show menu options\n options = [\n \"Add Directory\",\n \"Remove Directory\",\n \"Toggle Ollama Scanning\",\n \"Scan All Directories\",\n \"View Directory Statistics\",\n ]\n\n action = unified_prompt(\n \"model_directories\", \"Directory Management\", options, allow_back=True\n )\n\n if action == \"← Back\" or action == \"BACK\" or not action:\n return \"continue\"\n elif action == \"Add Directory\":\n self._add_directory()\n elif action == \"Remove Directory\":\n self._remove_directory()\n elif action == \"Toggle Ollama Scanning\":\n self._toggle_ollama_scanning()\n elif action == \"Scan All Directories\":\n self._scan_directories()\n elif action == \"View Directory Statistics\":\n self._show_statistics()\n\n def _display_directories(self):\n \"\"\"Display currently configured directories.\"\"\"\n try:\n directories = self.api.list_directories()\n\n # Get Ollama status\n ollama_status = self.api.get_ollama_status()\n ollama_enabled = ollama_status.get(\"scan_enabled\", False)\n\n # Display Ollama scanning status\n if ollama_enabled:\n console.print(\n \"\\n[bold]Ollama Scanning:[/bold] [green]✓ Enabled[/green]\"\n )\n else:\n console.print(\"\\n[bold]Ollama Scanning:[/bold] [red]✗ Disabled[/red]\")\n\n if not directories:\n console.print(\"\\n[yellow]No directories configured.[/yellow]\")\n console.print(\"[dim]Using default locations only.[/dim]\\n\")\n return\n\n # Create table for directories\n table = Table(\n title=\"[bold]Configured Directories[/bold]\",\n show_header=True,\n header_style=\"bold cyan\",\n )\n table.add_column(\"#\", style=\"cyan\", width=3)\n table.add_column(\"Path\", style=\"white\")\n table.add_column(\"Type\", style=\"yellow\", width=15)\n table.add_column(\"Source\", style=\"magenta\", width=15)\n table.add_column(\"Status\", style=\"green\", width=10)\n\n for idx, dir_info in enumerate(directories, 1):\n path = dir_info.get(\"path\", \"\")\n dir_type = dir_info.get(\"type\", \"custom\")\n\n dir_source = dir_info.get(\"source\", \"unknown\")\n\n # Format source for display\n if dir_source == \"default_cache\":\n source_display = \"Default HF\"\n elif dir_source == \"default_ollama\":\n source_display = \"Default Ollama\"\n elif dir_source == \"custom_ollama\":\n source_display = \"Custom Ollama\"\n elif dir_source.startswith(\"custom\"):\n source_display = \"Custom\"\n else:\n source_display = dir_source.capitalize()\n\n # Check if directory exists\n path_obj = Path(path)\n status = (\n \"[green]✓ Valid[/green]\"\n if path_obj.exists()\n else \"[red]✗ Missing[/red]\"\n )\n\n table.add_row(\n str(idx), path, dir_type.capitalize(), source_display, status\n )\n\n console.print(table)\n console.print()\n\n except Exception as e:\n logger.error(f\"Error displaying directories: {e}\")\n console.print(f\"[red]Error loading directories: {e}[/red]\\n\")\n\n def _add_directory(self):\n \"\"\"Add a new directory for model scanning.\"\"\"\n console.print(\"\\n[bold cyan]Add Model Directory[/bold cyan]\")\n\n # Get directory path\n console.print(\"\\nEnter the full path to the directory containing models:\")\n console.print(\"[dim]Example: /home/user/models or ~/my_models[/dim]\")\n path = input(\"Path: \").strip()\n\n if not path:\n console.print(\"[yellow]No path provided, cancelling.[/yellow]\")\n input(\"\\nPress Enter to continue...\")\n return\n\n # Expand user path\n path = str(Path(path).expanduser().resolve())\n\n # Validate directory exists\n path_obj = Path(path)\n if not path_obj.exists():\n # Use unified prompt for confirmation\n create_choices = [\"Yes, create it\", \"No, cancel\"]\n create_choice = unified_prompt(\n \"create_dir\",\n f\"Directory '{path}' does not exist. Create it?\",\n create_choices,\n allow_back=False,\n )\n\n if create_choice == \"Yes, create it\":\n try:\n path_obj.mkdir(parents=True, exist_ok=True)\n console.print(f\"\\n[green]Created directory: {path}[/green]\")\n except Exception as e:\n console.print(f\"\\n[red]Failed to create directory: {e}[/red]\")\n input(\"\\nPress Enter to continue...\")\n return\n else:\n console.print(\"\\n[yellow]Directory must exist. Cancelling.[/yellow]\")\n input(\"\\nPress Enter to continue...\")\n return\n\n # Ask for directory type using unified prompt\n type_choices = [\n \"Auto-detect (recommended)\",\n \"HuggingFace cache\",\n \"Custom models\",\n \"LoRA adapters\",\n \"Ollama models\",\n ]\n\n type_selection = unified_prompt(\n \"dir_type\", \"Select directory type\", type_choices, allow_back=False\n )\n\n type_map = {\n \"Auto-detect (recommended)\": \"auto\",\n \"HuggingFace cache\": \"huggingface\",\n \"Custom models\": \"custom\",\n \"LoRA adapters\": \"lora\",\n \"Ollama models\": \"ollama\",\n }\n dir_type = type_map.get(type_selection, \"auto\")\n\n # Special handling for Ollama directories\n if dir_type == \"ollama\":\n # Check for Ollama structure\n has_manifests = (Path(path) / \"manifests\").exists()\n has_blobs = (Path(path) / \"blobs\").exists()\n\n if not (has_manifests and has_blobs):\n console.print(\n \"\\n[yellow]Warning: Directory doesn't have standard Ollama structure[/yellow]\"\n )\n console.print(f\" Manifests directory: {'✓' if has_manifests else '✗'}\")\n console.print(f\" Blobs directory: {'✓' if has_blobs else '✗'}\")\n\n # Ask if they want to add it anyway\n confirm_choices = [\"Yes, add anyway\", \"No, cancel\"]\n confirm_choice = unified_prompt(\n \"confirm_ollama\",\n \"Add as Ollama directory anyway?\",\n confirm_choices,\n allow_back=False,\n )\n\n if confirm_choice != \"Yes, add anyway\":\n console.print(\"\\n[yellow]Cancelled[/yellow]\")\n input(\"\\nPress Enter to continue...\")\n return\n\n # Add as Ollama directory\n try:\n success = self.api.add_ollama_directory(path)\n if success:\n console.print(\n f\"\\n[green]✓ Successfully added Ollama directory:[/green] {path}\"\n )\n\n # Enable Ollama scanning if not already enabled\n ollama_status = self.api.get_ollama_status()\n if not ollama_status.get(\"scan_enabled\", False):\n console.print(\n \"\\n[yellow]Note: Ollama scanning is currently disabled[/yellow]\"\n )\n enable_choices = [\"Yes, enable now\", \"No, keep disabled\"]\n enable_choice = unified_prompt(\n \"enable_ollama\",\n \"Enable Ollama scanning?\",\n enable_choices,\n allow_back=False,\n )\n\n if enable_choice == \"Yes, enable now\":\n self.api.toggle_ollama_scanning()\n console.print(\"[green]✓ Ollama scanning enabled[/green]\")\n else:\n console.print(\n \"\\n[red]Failed to add Ollama directory (may already exist)[/red]\"\n )\n except Exception as e:\n console.print(f\"\\n[red]Error adding Ollama directory: {e}[/red]\")\n\n input(\"\\nPress Enter to continue...\")\n return\n\n # Add regular directory\n try:\n success = self.api.add_directory(path, dir_type)\n if success:\n console.print(\n f\"\\n[green]✓ Successfully added directory:[/green] {path}\"\n )\n\n # Inform about manifest file\n manifest_path = Path(path) / \"models_manifest.json\"\n console.print(\n Panel.fit(\n \"[bold yellow]Note about Model Manifest:[/bold yellow]\\n\\n\"\n f\"A [cyan]models_manifest.json[/cyan] file will be auto-generated at:\\n\"\n f\"[dim]{manifest_path}[/dim]\\n\\n\"\n \"You can manually edit this file to customize:\\n\"\n \" • Custom display names\\n\"\n \" • Model descriptions\\n\"\n \" • Publisher information\\n\"\n \" • Model categories\\n\\n\"\n \"[dim]The manifest helps organize and customize how models appear.[/dim]\",\n border_style=\"yellow\",\n )\n )\n\n # Offer to scan immediately using unified prompt\n scan_choices = [\"Yes, scan now\", \"No, scan later\"]\n scan_choice = unified_prompt(\n \"scan_now\",\n \"Scan this directory for models now?\",\n scan_choices,\n allow_back=False,\n )\n\n if scan_choice == \"Yes, scan now\":\n self._scan_single_directory(path)\n\n # After scanning, remind about manifest if models were found\n console.print(\n \"\\n[dim]Tip: A models_manifest.json file has been auto-generated.[/dim]\"\n )\n console.print(\n \"[dim]You can edit it to customize how models appear in the serving menu.[/dim]\"\n )\n else:\n console.print(\"\\n[red]Failed to add directory.[/red]\")\n except Exception as e:\n console.print(f\"\\n[red]Error adding directory: {e}[/red]\")\n\n input(\"\\nPress Enter to continue...\")\n\n def _remove_directory(self):\n \"\"\"Remove a directory from scanning.\"\"\"\n directories = self.api.list_directories()\n\n if not directories:\n console.print(\"\\n[yellow]No directories to remove.[/yellow]\")\n input(\"\\nPress Enter to continue...\")\n return\n\n console.print(\"\\n[bold cyan]Remove Directory[/bold cyan]\")\n\n # Build choices list with directory paths\n dir_choices = []\n for dir_info in directories:\n path = dir_info.get(\"path\", \"\")\n dir_type = dir_info.get(\"type\", \"custom\")\n dir_choices.append(f\"{path} [{dir_type}]\")\n\n # Use unified prompt for selection\n selected = unified_prompt(\n \"remove_dir\", \"Select directory to remove\", dir_choices, allow_back=True\n )\n\n if not selected or selected == \"BACK\":\n return\n\n # Extract the path from the selection\n selected_path = selected.split(\" [\")[0] # Remove the [type] suffix\n\n # Find the matching directory\n for dir_info in directories:\n if dir_info.get(\"path\", \"\") == selected_path:\n # Confirm removal using unified prompt\n confirm_choices = [\"Yes, remove this directory\", \"No, keep it\"]\n confirm = unified_prompt(\n \"confirm_remove\",\n f\"Remove {selected_path}?\",\n confirm_choices,\n allow_back=False,\n )\n\n if confirm == \"Yes, remove this directory\":\n try:\n # Check if it's an Ollama directory\n dir_source = dir_info.get(\"source\", \"\")\n if dir_info.get(\"type\") == \"ollama\" and \"ollama\" in dir_source:\n # Remove as Ollama directory\n success = self.api.remove_ollama_directory(selected_path)\n else:\n # Remove as regular directory\n success = self.api.remove_directory(selected_path)\n\n if success:\n console.print(\n f\"\\n[green]✓ Removed directory: {selected_path}[/green]\"\n )\n else:\n console.print(\"\\n[red]Failed to remove directory.[/red]\")\n except Exception as e:\n console.print(f\"\\n[red]Error removing directory: {e}[/red]\")\n else:\n console.print(\"\\n[yellow]Directory not removed.[/yellow]\")\n break\n\n input(\"\\nPress Enter to continue...\")\n\n def _scan_directories(self):\n \"\"\"Scan all configured directories for models.\"\"\"\n console.print(\"\\n[bold cyan]Scanning Directories[/bold cyan]\")\n console.print(\"[dim]This may take a moment for large directories...[/dim]\\n\")\n\n try:\n # Force refresh to get latest data\n assets = self.api.list_assets(force_refresh=True)\n\n # Group by type\n models = [a for a in assets if a.get(\"type\") == \"model\"]\n custom_models = [a for a in assets if a.get(\"type\") == \"custom_model\"]\n lora_adapters = [a for a in assets if a.get(\"type\") == \"lora_adapter\"]\n datasets = [a for a in assets if a.get(\"type\") == \"dataset\"]\n\n # Display summary\n console.print(\"[bold]Scan Results:[/bold]\")\n console.print(f\" Models: [cyan]{len(models)}[/cyan]\")\n console.print(f\" Custom Models: [cyan]{len(custom_models)}[/cyan]\")\n console.print(f\" LoRA Adapters: [cyan]{len(lora_adapters)}[/cyan]\")\n console.print(f\" Datasets: [cyan]{len(datasets)}[/cyan]\")\n console.print(f\" [bold]Total Assets: [green]{len(assets)}[/green][/bold]\")\n\n # Show top models by size\n if models or custom_models:\n all_models = models + custom_models\n all_models.sort(key=lambda x: x.get(\"size\", 0), reverse=True)\n\n console.print(\"\\n[bold]Top Models by Size:[/bold]\")\n for model in all_models[:5]:\n name = model.get(\"display_name\", model.get(\"name\", \"Unknown\"))\n size = model.get(\"size\", 0)\n size_gb = size / (1024**3)\n console.print(f\" • {name}: [yellow]{size_gb:.2f} GB[/yellow]\")\n\n except Exception as e:\n console.print(f\"[red]Error scanning directories: {e}[/red]\")\n\n input(\"\\nPress Enter to continue...\")\n\n def _scan_single_directory(self, path: str):\n \"\"\"Scan a single directory for models.\"\"\"\n console.print(f\"\\n[cyan]Scanning: {path}[/cyan]\")\n\n try:\n assets = self.api.scan_directories([path])\n\n if assets:\n console.print(f\"[green]Found {len(assets)} asset(s):[/green]\")\n for asset in assets[:5]: # Show first 5\n name = asset.get(\"display_name\", asset.get(\"name\", \"Unknown\"))\n asset_type = asset.get(\"type\", \"unknown\")\n console.print(f\" • {name} ([yellow]{asset_type}[/yellow])\")\n if len(assets) > 5:\n console.print(f\" [dim]... and {len(assets) - 5} more[/dim]\")\n else:\n console.print(\"[yellow]No models found in this directory.[/yellow]\")\n\n except Exception as e:\n console.print(f\"[red]Error scanning directory: {e}[/red]\")\n\n def _toggle_ollama_scanning(self):\n \"\"\"Toggle Ollama model scanning on/off.\"\"\"\n console.print(\"\\n[bold cyan]Ollama Model Scanning[/bold cyan]\")\n\n try:\n # Get current status\n ollama_status = self.api.get_ollama_status()\n current_state = ollama_status.get(\"scan_enabled\", False)\n\n # Display current state\n if current_state:\n console.print(\n \"\\nOllama scanning is currently: [green]✓ Enabled[/green]\"\n )\n console.print(\"\\nDefault Ollama directories being scanned:\")\n for dir_path in ollama_status.get(\"default_directories\", []):\n if Path(dir_path).exists():\n console.print(f\" • {dir_path}\")\n else:\n console.print(\"\\nOllama scanning is currently: [red]✗ Disabled[/red]\")\n console.print(\"\\n[dim]Enable to scan Ollama model directories[/dim]\")\n\n # Ask to toggle\n toggle_choices = [\n \"Yes, toggle it\" if current_state else \"Yes, enable it\",\n \"No, keep current setting\",\n ]\n\n toggle_choice = unified_prompt(\n \"toggle_ollama\",\n f\"{'Disable' if current_state else 'Enable'} Ollama scanning?\",\n toggle_choices,\n allow_back=False,\n )\n\n if toggle_choice and toggle_choice.startswith(\"Yes\"):\n new_state = self.api.toggle_ollama_scanning()\n\n if new_state:\n console.print(\"\\n[green]✓ Ollama scanning enabled[/green]\")\n console.print(\n \"[dim]Ollama models will now be included in scans[/dim]\"\n )\n else:\n console.print(\"\\n[yellow]Ollama scanning disabled[/yellow]\")\n console.print(\n \"[dim]Ollama models will be excluded from scans[/dim]\"\n )\n\n # Offer to refresh cache\n refresh_choices = [\"Yes, refresh now\", \"No, refresh later\"]\n refresh_choice = unified_prompt(\n \"refresh_cache\",\n \"Refresh model cache to apply changes?\",\n refresh_choices,\n allow_back=False,\n )\n\n if refresh_choice == \"Yes, refresh now\":\n console.print(\"\\n[cyan]Refreshing model cache...[/cyan]\")\n\n # Import and use model manager to refresh\n try:\n from ..models import get_model_manager\n\n model_manager = get_model_manager()\n model_manager.refresh_cache()\n console.print(\"[green]✓ Model cache refreshed[/green]\")\n except Exception as e:\n console.print(f\"[red]Failed to refresh cache: {e}[/red]\")\n else:\n console.print(\"\\n[yellow]Settings unchanged[/yellow]\")\n\n except Exception as e:\n console.print(f\"\\n[red]Error toggling Ollama scanning: {e}[/red]\")\n\n input(\"\\nPress Enter to continue...\")\n\n def _show_statistics(self):\n \"\"\"Show statistics about managed assets.\"\"\"\n console.print(\"\\n[bold cyan]Asset Statistics[/bold cyan]\\n\")\n\n try:\n stats = self.api.get_statistics()\n\n # Create statistics panels\n panels = []\n\n # Models panel\n model_text = Text()\n model_text.append(\"Models\\n\", style=\"bold yellow\")\n model_text.append(f\"Total: {stats.get('total_models', 0)}\\n\")\n model_text.append(f\"Custom: {stats.get('custom_models', 0)}\\n\")\n model_text.append(f\"LoRA: {stats.get('lora_adapters', 0)}\")\n panels.append(Panel(model_text, border_style=\"yellow\"))\n\n # Storage panel\n storage_text = Text()\n storage_text.append(\"Storage\\n\", style=\"bold cyan\")\n total_size = stats.get(\"total_size\", 0)\n size_gb = total_size / (1024**3)\n storage_text.append(f\"Total: {size_gb:.2f} GB\\n\")\n storage_text.append(f\"Datasets: {stats.get('dataset_count', 0)}\")\n panels.append(Panel(storage_text, border_style=\"cyan\"))\n\n # Directories panel\n dir_text = Text()\n dir_text.append(\"Directories\\n\", style=\"bold green\")\n dir_text.append(f\"Monitored: {stats.get('directories', 0)}\\n\")\n dir_text.append(\"Last scan: Recent\")\n panels.append(Panel(dir_text, border_style=\"green\"))\n\n console.print(Columns(panels))\n\n # Show breakdown by directory if available\n if \"by_directory\" in stats:\n console.print(\"\\n[bold]By Directory:[/bold]\")\n for dir_path, dir_stats in stats[\"by_directory\"].items():\n console.print(f\"\\n [cyan]{dir_path}[/cyan]\")\n console.print(f\" Models: {dir_stats.get('models', 0)}\")\n console.print(\n f\" Size: {dir_stats.get('size', 0) / (1024**3):.2f} GB\"\n )\n\n except Exception as e:\n console.print(f\"[red]Error getting statistics: {e}[/red]\")\n\n input(\"\\nPress Enter to continue...\")", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 24164}, "tests/test_config_manager.py::22": {"resolved_imports": ["src/vllm_cli/config/manager.py"], "used_names": ["ConfigManager", "patch"], "enclosing_function": "test_init_creates_config_dir", "extracted_code": "# Source: src/vllm_cli/config/manager.py\nclass ConfigManager:\n \"\"\"\n Enhanced configuration manager with comprehensive validation support.\n\n This class manages configuration files, profiles, and validation using\n the new validation framework. It provides a clean API for configuration\n operations while ensuring data integrity through comprehensive validation.\n\n Attributes:\n config_dir: Directory for configuration files\n validation_registry: Registry of validation rules\n compatibility_validator: Validator for parameter combinations\n \"\"\"\n\n def __init__(self):\n # Paths for configuration files\n self.config_dir = Path.home() / \".config\" / \"vllm-cli\"\n self.config_file = self.config_dir / \"config.yaml\"\n\n # Ensure config directory exists\n self.config_dir.mkdir(parents=True, exist_ok=True)\n\n # Initialize sub-managers\n self.schema_manager = SchemaManager()\n self.profile_manager = ProfileManager(self.config_dir)\n self.persistence_manager = PersistenceManager()\n self.shortcut_manager = ShortcutManager(self.config_dir)\n\n # Initialize validation system\n self.validation_registry = create_vllm_validation_registry()\n self.compatibility_validator = create_compatibility_validator(\n self.validation_registry\n )\n\n # Load main configuration\n self.config = self._load_config()\n\n def _load_config(self) -> Dict[str, Any]:\n \"\"\"Load main configuration file (legacy YAML support).\"\"\"\n return self.persistence_manager.load_yaml_file(self.config_file)\n\n def _save_config(self) -> None:\n \"\"\"Save main configuration file.\"\"\"\n self.persistence_manager.save_yaml_file(self.config_file, self.config)\n\n def get_argument_info(self, arg_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get detailed information about a specific argument.\"\"\"\n return self.schema_manager.get_argument_info(arg_name)\n\n def get_arguments_by_category(self, category: str) -> List[Dict[str, Any]]:\n \"\"\"Get all arguments belonging to a specific category.\"\"\"\n return self.schema_manager.get_arguments_by_category(category)\n\n def get_category_info(self, category: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get information about a specific category.\"\"\"\n return self.schema_manager.get_category_info(category)\n\n def get_ordered_categories(self) -> List[Tuple[str, Dict[str, Any]]]:\n \"\"\"Get categories ordered by their display order.\"\"\"\n return self.schema_manager.get_ordered_categories()\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n return self.profile_manager.get_all_profiles()\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name with dynamic defaults applied.\"\"\"\n profile = self.profile_manager.get_profile(name)\n if profile and \"config\" in profile:\n # Apply dynamic defaults to the profile configuration\n profile[\"config\"] = self.profile_manager.apply_dynamic_defaults(\n profile[\"config\"]\n )\n return profile\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"Save or update a user profile with validation.\"\"\"\n # Validate profile configuration if present\n if \"config\" in profile:\n is_valid, errors = self.validate_config(profile[\"config\"])\n if not is_valid:\n from ..errors import ProfileError\n\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n return self.profile_manager.save_user_profile(name, profile)\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n return self.profile_manager.delete_user_profile(name)\n\n @property\n def default_profiles(self) -> Dict[str, Any]:\n \"\"\"Get default profiles.\"\"\"\n return self.profile_manager.default_profiles\n\n @property\n def user_profiles(self) -> Dict[str, Any]:\n \"\"\"Get user profiles.\"\"\"\n return self.profile_manager.user_profiles\n\n def validate_config(self, config: Dict[str, Any]) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate a configuration using the new validation framework.\n\n This method uses the comprehensive validation system to check\n configuration values, types, ranges, and dependencies.\n\n Args:\n config: Configuration dictionary to validate\n\n Returns:\n Tuple of (is_valid, list_of_error_messages)\n\n Raises:\n ConfigurationError: If validation system fails\n \"\"\"\n try:\n # Use new validation system\n result = self.validation_registry.validate_config(config)\n\n # Convert validation errors to string messages for backward compatibility\n error_messages = result.get_error_messages()\n\n # Add warnings if any\n if result.warnings:\n for warning in result.warnings:\n logger.warning(f\"Configuration warning: {warning}\")\n\n return result.is_valid(), error_messages\n\n except Exception as e:\n logger.error(f\"Error during configuration validation: {e}\")\n raise ConfigurationError(\n f\"Validation system error: {e}\", error_code=\"VALIDATION_SYSTEM_ERROR\"\n ) from e\n\n def validate_argument_combination(\n self, config: Dict[str, Any]\n ) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate that argument combinations are compatible using the new compatibility validator.\n\n Args:\n config: Configuration dictionary to check for compatibility\n\n Returns:\n Tuple of (is_valid, list_of_warnings_or_errors)\n \"\"\"\n try:\n issues = self.compatibility_validator.validate_compatibility(config)\n\n warnings = []\n errors = []\n\n for issue in issues:\n message = issue[\"message\"]\n if issue[\"severity\"] == \"error\":\n errors.append(message)\n else:\n warnings.append(message)\n\n # Log warnings\n for warning in warnings:\n logger.warning(f\"Configuration compatibility warning: {warning}\")\n\n # Return all issues as warnings for backward compatibility\n # (errors are treated as warnings in the legacy interface)\n all_issues = errors + warnings\n\n return len(errors) == 0, all_issues\n\n except Exception as e:\n logger.error(f\"Error during compatibility validation: {e}\")\n return False, [f\"Compatibility validation error: {e}\"]\n\n def build_cli_args(self, config: Dict[str, Any]) -> List[str]:\n \"\"\"\n Build command-line arguments from a configuration dictionary.\n\n Only includes arguments that are explicitly set in the config.\n Handles special cases like LoRA modules.\n \"\"\"\n args = []\n\n # Special handling for model (positional argument)\n # Check if this is a GGUF/Ollama configuration\n if (\n isinstance(config.get(\"model\"), dict)\n and \"quantization\" in config[\"model\"]\n and config[\"model\"][\"quantization\"] == \"gguf\"\n ):\n # Extract GGUF model config\n gguf_config = config[\"model\"]\n model_path = gguf_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", model_path])\n\n # Set quantization to gguf\n config[\"quantization\"] = \"gguf\"\n\n # Add served-model-name if provided (for Ollama models)\n if \"served_model_name\" in gguf_config:\n config[\"served_model_name\"] = gguf_config[\"served_model_name\"]\n logger.info(\n f\"Configuring GGUF model: {model_path} as {gguf_config['served_model_name']}\"\n )\n else:\n logger.info(f\"Configuring GGUF model: {model_path}\")\n\n # Check if this is a LoRA configuration\n elif (\n isinstance(config.get(\"model\"), dict) and \"lora_modules\" in config[\"model\"]\n ):\n # Extract base model and LoRA config\n lora_config = config[\"model\"]\n base_model = lora_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", base_model])\n\n # Enable LoRA support when modules are present\n args.append(\"--enable-lora\")\n\n # Track maximum rank for all LoRA modules\n max_rank = 16 # Default minimum\n\n # Add LoRA modules\n for lora in lora_config.get(\"lora_modules\", []):\n lora_path = lora.get(\"path\", \"\")\n if lora_path:\n # vLLM expects --lora-modules with name=path format\n lora_name = lora.get(\"name\", \"adapter\")\n args.extend([\"--lora-modules\", f\"{lora_name}={lora_path}\"])\n\n # Track maximum rank\n lora_rank = lora.get(\"rank\", 16)\n max_rank = max(max_rank, lora_rank)\n\n # Add max-lora-rank parameter\n args.extend([\"--max-lora-rank\", str(max_rank)])\n\n elif \"model\" in config:\n args.extend([\"serve\", config[\"model\"]])\n\n # Handle lora_modules if present as a string (from CLI)\n if \"lora_modules\" in config and config[\"lora_modules\"]:\n # Enable LoRA support\n if \"--enable-lora\" not in args:\n args.append(\"--enable-lora\")\n\n # Parse and add LoRA modules\n lora_modules_str = config[\"lora_modules\"]\n if isinstance(lora_modules_str, str):\n # Split by space and add each module\n for module in lora_modules_str.split():\n args.extend([\"--lora-modules\", module])\n\n # Add max-lora-rank if not already added\n # Use a safe default of 64 which should cover most LoRA adapters\n if \"--max-lora-rank\" not in args:\n # Check if max_lora_rank is explicitly set in config\n if \"max_lora_rank\" not in config:\n args.extend([\"--max-lora-rank\", \"64\"])\n\n for arg_name, value in config.items():\n # Skip special keys and None values\n if (\n arg_name in [\"model\", \"name\", \"description\", \"icon\", \"lora_modules\"]\n or value is None\n ):\n continue\n\n arg_info = self.schema_manager.get_argument_info(arg_name)\n if not arg_info:\n logger.warning(f\"Unknown argument in config: {arg_name}\")\n continue\n\n cli_flag = arg_info.get(\"cli_flag\")\n if not cli_flag:\n continue\n\n arg_type = arg_info.get(\"type\")\n\n if arg_type == \"boolean\":\n if value: # Only add flag if True\n args.append(cli_flag)\n elif arg_type in [\"integer\", \"float\", \"string\", \"choice\"]:\n args.extend([cli_flag, str(value)])\n else:\n logger.warning(f\"Unknown argument type for {arg_name}: {arg_type}\")\n\n return args\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n return self.profile_manager.export_profile(profile_name, filepath)\n\n def import_profile(self, filepath: Path, new_name: Optional[str] = None) -> bool:\n \"\"\"Import a profile from a JSON file with comprehensive validation.\"\"\"\n return self.profile_manager.import_profile(\n filepath, new_name, self.validate_config\n )\n\n def get_last_config(self) -> Optional[Dict[str, Any]]:\n \"\"\"Get the last used server configuration.\"\"\"\n return self.config.get(\"last_config\")\n\n def save_last_config(self, config: Dict[str, Any]) -> None:\n \"\"\"Save the last used server configuration.\"\"\"\n self.config[\"last_config\"] = config\n self._save_config()\n\n def get_recent_models(self, limit: int = 5) -> List[str]:\n \"\"\"Get recently used models.\"\"\"\n return self.config.get(\"recent_models\", [])[:limit]\n\n def add_recent_model(self, model: str) -> None:\n \"\"\"Add a model to recent models list.\"\"\"\n recent = self.config.get(\"recent_models\", [])\n if model in recent:\n recent.remove(model)\n recent.insert(0, model)\n self.config[\"recent_models\"] = recent[:10] # Keep only last 10\n self._save_config()\n\n def clear_cache(self) -> None:\n \"\"\"Clear cached data.\"\"\"\n cache_file = self.config_dir / \"cache.json\"\n if cache_file.exists():\n cache_file.unlink()\n self.config.pop(\"last_config\", None)\n self.config.pop(\"recent_models\", None)\n self._save_config()\n logger.info(\"Cache cleared\")\n\n def get_server_defaults(self) -> Dict[str, Any]:\n \"\"\"Get default server settings.\"\"\"\n return self.config.get(\n \"server_defaults\",\n {\n \"default_port\": 8000,\n \"auto_restart\": False,\n \"log_level\": \"info\",\n \"cleanup_on_exit\": True, # Default to cleaning up servers on exit\n },\n )\n\n def save_server_defaults(self, defaults: Dict[str, Any]) -> None:\n \"\"\"Save default server settings.\"\"\"\n self.config[\"server_defaults\"] = defaults\n self._save_config()\n\n def get_ui_preferences(self) -> Dict[str, Any]:\n \"\"\"Get UI preferences including progress bar style and log display settings.\"\"\"\n return self.config.get(\n \"ui_preferences\",\n {\n \"progress_bar_style\": \"blocks\", # Default style\n \"show_gpu_in_monitor\": True,\n \"log_lines_startup\": 50, # Number of log lines to show during startup\n \"log_lines_monitor\": 50, # Number of log lines to show in server monitor\n \"startup_refresh_rate\": 4.0, # Hz for startup log refresh\n \"monitor_refresh_rate\": 1.0, # Hz for monitor log refresh\n },\n )\n\n def save_ui_preferences(self, preferences: Dict[str, Any]) -> None:\n \"\"\"Save UI preferences.\"\"\"\n self.config[\"ui_preferences\"] = preferences\n self._save_config()\n\n # Shortcut management methods\n def get_all_shortcuts(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all shortcuts.\"\"\"\n return self.shortcut_manager.get_all_shortcuts()\n\n def get_shortcut(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific shortcut by name.\"\"\"\n return self.shortcut_manager.get_shortcut(name)\n\n def save_shortcut(self, name: str, shortcut_data: Dict[str, Any]) -> bool:\n \"\"\"Save or update a shortcut.\"\"\"\n return self.shortcut_manager.save_shortcut(name, shortcut_data)\n\n def delete_shortcut(self, name: str) -> bool:\n \"\"\"Delete a shortcut.\"\"\"\n return self.shortcut_manager.delete_shortcut(name)\n\n def list_shortcuts(self) -> List[Dict[str, Any]]:\n \"\"\"List all shortcuts with summary information.\"\"\"\n return self.shortcut_manager.list_shortcuts()\n\n def get_recent_shortcuts(self, limit: int = 5) -> List[Dict[str, Any]]:\n \"\"\"Get recently used shortcuts.\"\"\"\n return self.shortcut_manager.get_recent_shortcuts(limit)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 15704}, "tests/test_config_manager.py::176": {"resolved_imports": ["src/vllm_cli/config/manager.py"], "used_names": ["ConfigManager", "Mock", "patch"], "enclosing_function": "test_validate_config_invalid", "extracted_code": "# Source: src/vllm_cli/config/manager.py\nclass ConfigManager:\n \"\"\"\n Enhanced configuration manager with comprehensive validation support.\n\n This class manages configuration files, profiles, and validation using\n the new validation framework. It provides a clean API for configuration\n operations while ensuring data integrity through comprehensive validation.\n\n Attributes:\n config_dir: Directory for configuration files\n validation_registry: Registry of validation rules\n compatibility_validator: Validator for parameter combinations\n \"\"\"\n\n def __init__(self):\n # Paths for configuration files\n self.config_dir = Path.home() / \".config\" / \"vllm-cli\"\n self.config_file = self.config_dir / \"config.yaml\"\n\n # Ensure config directory exists\n self.config_dir.mkdir(parents=True, exist_ok=True)\n\n # Initialize sub-managers\n self.schema_manager = SchemaManager()\n self.profile_manager = ProfileManager(self.config_dir)\n self.persistence_manager = PersistenceManager()\n self.shortcut_manager = ShortcutManager(self.config_dir)\n\n # Initialize validation system\n self.validation_registry = create_vllm_validation_registry()\n self.compatibility_validator = create_compatibility_validator(\n self.validation_registry\n )\n\n # Load main configuration\n self.config = self._load_config()\n\n def _load_config(self) -> Dict[str, Any]:\n \"\"\"Load main configuration file (legacy YAML support).\"\"\"\n return self.persistence_manager.load_yaml_file(self.config_file)\n\n def _save_config(self) -> None:\n \"\"\"Save main configuration file.\"\"\"\n self.persistence_manager.save_yaml_file(self.config_file, self.config)\n\n def get_argument_info(self, arg_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get detailed information about a specific argument.\"\"\"\n return self.schema_manager.get_argument_info(arg_name)\n\n def get_arguments_by_category(self, category: str) -> List[Dict[str, Any]]:\n \"\"\"Get all arguments belonging to a specific category.\"\"\"\n return self.schema_manager.get_arguments_by_category(category)\n\n def get_category_info(self, category: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get information about a specific category.\"\"\"\n return self.schema_manager.get_category_info(category)\n\n def get_ordered_categories(self) -> List[Tuple[str, Dict[str, Any]]]:\n \"\"\"Get categories ordered by their display order.\"\"\"\n return self.schema_manager.get_ordered_categories()\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n return self.profile_manager.get_all_profiles()\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name with dynamic defaults applied.\"\"\"\n profile = self.profile_manager.get_profile(name)\n if profile and \"config\" in profile:\n # Apply dynamic defaults to the profile configuration\n profile[\"config\"] = self.profile_manager.apply_dynamic_defaults(\n profile[\"config\"]\n )\n return profile\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"Save or update a user profile with validation.\"\"\"\n # Validate profile configuration if present\n if \"config\" in profile:\n is_valid, errors = self.validate_config(profile[\"config\"])\n if not is_valid:\n from ..errors import ProfileError\n\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n return self.profile_manager.save_user_profile(name, profile)\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n return self.profile_manager.delete_user_profile(name)\n\n @property\n def default_profiles(self) -> Dict[str, Any]:\n \"\"\"Get default profiles.\"\"\"\n return self.profile_manager.default_profiles\n\n @property\n def user_profiles(self) -> Dict[str, Any]:\n \"\"\"Get user profiles.\"\"\"\n return self.profile_manager.user_profiles\n\n def validate_config(self, config: Dict[str, Any]) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate a configuration using the new validation framework.\n\n This method uses the comprehensive validation system to check\n configuration values, types, ranges, and dependencies.\n\n Args:\n config: Configuration dictionary to validate\n\n Returns:\n Tuple of (is_valid, list_of_error_messages)\n\n Raises:\n ConfigurationError: If validation system fails\n \"\"\"\n try:\n # Use new validation system\n result = self.validation_registry.validate_config(config)\n\n # Convert validation errors to string messages for backward compatibility\n error_messages = result.get_error_messages()\n\n # Add warnings if any\n if result.warnings:\n for warning in result.warnings:\n logger.warning(f\"Configuration warning: {warning}\")\n\n return result.is_valid(), error_messages\n\n except Exception as e:\n logger.error(f\"Error during configuration validation: {e}\")\n raise ConfigurationError(\n f\"Validation system error: {e}\", error_code=\"VALIDATION_SYSTEM_ERROR\"\n ) from e\n\n def validate_argument_combination(\n self, config: Dict[str, Any]\n ) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate that argument combinations are compatible using the new compatibility validator.\n\n Args:\n config: Configuration dictionary to check for compatibility\n\n Returns:\n Tuple of (is_valid, list_of_warnings_or_errors)\n \"\"\"\n try:\n issues = self.compatibility_validator.validate_compatibility(config)\n\n warnings = []\n errors = []\n\n for issue in issues:\n message = issue[\"message\"]\n if issue[\"severity\"] == \"error\":\n errors.append(message)\n else:\n warnings.append(message)\n\n # Log warnings\n for warning in warnings:\n logger.warning(f\"Configuration compatibility warning: {warning}\")\n\n # Return all issues as warnings for backward compatibility\n # (errors are treated as warnings in the legacy interface)\n all_issues = errors + warnings\n\n return len(errors) == 0, all_issues\n\n except Exception as e:\n logger.error(f\"Error during compatibility validation: {e}\")\n return False, [f\"Compatibility validation error: {e}\"]\n\n def build_cli_args(self, config: Dict[str, Any]) -> List[str]:\n \"\"\"\n Build command-line arguments from a configuration dictionary.\n\n Only includes arguments that are explicitly set in the config.\n Handles special cases like LoRA modules.\n \"\"\"\n args = []\n\n # Special handling for model (positional argument)\n # Check if this is a GGUF/Ollama configuration\n if (\n isinstance(config.get(\"model\"), dict)\n and \"quantization\" in config[\"model\"]\n and config[\"model\"][\"quantization\"] == \"gguf\"\n ):\n # Extract GGUF model config\n gguf_config = config[\"model\"]\n model_path = gguf_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", model_path])\n\n # Set quantization to gguf\n config[\"quantization\"] = \"gguf\"\n\n # Add served-model-name if provided (for Ollama models)\n if \"served_model_name\" in gguf_config:\n config[\"served_model_name\"] = gguf_config[\"served_model_name\"]\n logger.info(\n f\"Configuring GGUF model: {model_path} as {gguf_config['served_model_name']}\"\n )\n else:\n logger.info(f\"Configuring GGUF model: {model_path}\")\n\n # Check if this is a LoRA configuration\n elif (\n isinstance(config.get(\"model\"), dict) and \"lora_modules\" in config[\"model\"]\n ):\n # Extract base model and LoRA config\n lora_config = config[\"model\"]\n base_model = lora_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", base_model])\n\n # Enable LoRA support when modules are present\n args.append(\"--enable-lora\")\n\n # Track maximum rank for all LoRA modules\n max_rank = 16 # Default minimum\n\n # Add LoRA modules\n for lora in lora_config.get(\"lora_modules\", []):\n lora_path = lora.get(\"path\", \"\")\n if lora_path:\n # vLLM expects --lora-modules with name=path format\n lora_name = lora.get(\"name\", \"adapter\")\n args.extend([\"--lora-modules\", f\"{lora_name}={lora_path}\"])\n\n # Track maximum rank\n lora_rank = lora.get(\"rank\", 16)\n max_rank = max(max_rank, lora_rank)\n\n # Add max-lora-rank parameter\n args.extend([\"--max-lora-rank\", str(max_rank)])\n\n elif \"model\" in config:\n args.extend([\"serve\", config[\"model\"]])\n\n # Handle lora_modules if present as a string (from CLI)\n if \"lora_modules\" in config and config[\"lora_modules\"]:\n # Enable LoRA support\n if \"--enable-lora\" not in args:\n args.append(\"--enable-lora\")\n\n # Parse and add LoRA modules\n lora_modules_str = config[\"lora_modules\"]\n if isinstance(lora_modules_str, str):\n # Split by space and add each module\n for module in lora_modules_str.split():\n args.extend([\"--lora-modules\", module])\n\n # Add max-lora-rank if not already added\n # Use a safe default of 64 which should cover most LoRA adapters\n if \"--max-lora-rank\" not in args:\n # Check if max_lora_rank is explicitly set in config\n if \"max_lora_rank\" not in config:\n args.extend([\"--max-lora-rank\", \"64\"])\n\n for arg_name, value in config.items():\n # Skip special keys and None values\n if (\n arg_name in [\"model\", \"name\", \"description\", \"icon\", \"lora_modules\"]\n or value is None\n ):\n continue\n\n arg_info = self.schema_manager.get_argument_info(arg_name)\n if not arg_info:\n logger.warning(f\"Unknown argument in config: {arg_name}\")\n continue\n\n cli_flag = arg_info.get(\"cli_flag\")\n if not cli_flag:\n continue\n\n arg_type = arg_info.get(\"type\")\n\n if arg_type == \"boolean\":\n if value: # Only add flag if True\n args.append(cli_flag)\n elif arg_type in [\"integer\", \"float\", \"string\", \"choice\"]:\n args.extend([cli_flag, str(value)])\n else:\n logger.warning(f\"Unknown argument type for {arg_name}: {arg_type}\")\n\n return args\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n return self.profile_manager.export_profile(profile_name, filepath)\n\n def import_profile(self, filepath: Path, new_name: Optional[str] = None) -> bool:\n \"\"\"Import a profile from a JSON file with comprehensive validation.\"\"\"\n return self.profile_manager.import_profile(\n filepath, new_name, self.validate_config\n )\n\n def get_last_config(self) -> Optional[Dict[str, Any]]:\n \"\"\"Get the last used server configuration.\"\"\"\n return self.config.get(\"last_config\")\n\n def save_last_config(self, config: Dict[str, Any]) -> None:\n \"\"\"Save the last used server configuration.\"\"\"\n self.config[\"last_config\"] = config\n self._save_config()\n\n def get_recent_models(self, limit: int = 5) -> List[str]:\n \"\"\"Get recently used models.\"\"\"\n return self.config.get(\"recent_models\", [])[:limit]\n\n def add_recent_model(self, model: str) -> None:\n \"\"\"Add a model to recent models list.\"\"\"\n recent = self.config.get(\"recent_models\", [])\n if model in recent:\n recent.remove(model)\n recent.insert(0, model)\n self.config[\"recent_models\"] = recent[:10] # Keep only last 10\n self._save_config()\n\n def clear_cache(self) -> None:\n \"\"\"Clear cached data.\"\"\"\n cache_file = self.config_dir / \"cache.json\"\n if cache_file.exists():\n cache_file.unlink()\n self.config.pop(\"last_config\", None)\n self.config.pop(\"recent_models\", None)\n self._save_config()\n logger.info(\"Cache cleared\")\n\n def get_server_defaults(self) -> Dict[str, Any]:\n \"\"\"Get default server settings.\"\"\"\n return self.config.get(\n \"server_defaults\",\n {\n \"default_port\": 8000,\n \"auto_restart\": False,\n \"log_level\": \"info\",\n \"cleanup_on_exit\": True, # Default to cleaning up servers on exit\n },\n )\n\n def save_server_defaults(self, defaults: Dict[str, Any]) -> None:\n \"\"\"Save default server settings.\"\"\"\n self.config[\"server_defaults\"] = defaults\n self._save_config()\n\n def get_ui_preferences(self) -> Dict[str, Any]:\n \"\"\"Get UI preferences including progress bar style and log display settings.\"\"\"\n return self.config.get(\n \"ui_preferences\",\n {\n \"progress_bar_style\": \"blocks\", # Default style\n \"show_gpu_in_monitor\": True,\n \"log_lines_startup\": 50, # Number of log lines to show during startup\n \"log_lines_monitor\": 50, # Number of log lines to show in server monitor\n \"startup_refresh_rate\": 4.0, # Hz for startup log refresh\n \"monitor_refresh_rate\": 1.0, # Hz for monitor log refresh\n },\n )\n\n def save_ui_preferences(self, preferences: Dict[str, Any]) -> None:\n \"\"\"Save UI preferences.\"\"\"\n self.config[\"ui_preferences\"] = preferences\n self._save_config()\n\n # Shortcut management methods\n def get_all_shortcuts(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all shortcuts.\"\"\"\n return self.shortcut_manager.get_all_shortcuts()\n\n def get_shortcut(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific shortcut by name.\"\"\"\n return self.shortcut_manager.get_shortcut(name)\n\n def save_shortcut(self, name: str, shortcut_data: Dict[str, Any]) -> bool:\n \"\"\"Save or update a shortcut.\"\"\"\n return self.shortcut_manager.save_shortcut(name, shortcut_data)\n\n def delete_shortcut(self, name: str) -> bool:\n \"\"\"Delete a shortcut.\"\"\"\n return self.shortcut_manager.delete_shortcut(name)\n\n def list_shortcuts(self) -> List[Dict[str, Any]]:\n \"\"\"List all shortcuts with summary information.\"\"\"\n return self.shortcut_manager.list_shortcuts()\n\n def get_recent_shortcuts(self, limit: int = 5) -> List[Dict[str, Any]]:\n \"\"\"Get recently used shortcuts.\"\"\"\n return self.shortcut_manager.get_recent_shortcuts(limit)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 15704}, "tests/proxy/test_router.py::99": {"resolved_imports": ["src/vllm_cli/proxy/router.py"], "used_names": [], "enclosing_function": "test_get_backends", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_validation_simple.py::24": {"resolved_imports": ["src/vllm_cli/validation/base.py", "src/vllm_cli/validation/registry.py", "src/vllm_cli/validation/types.py"], "used_names": ["ValidationError", "ValidationResult"], "enclosing_function": "test_validation_result", "extracted_code": "# Source: src/vllm_cli/validation/base.py\nclass ValidationError(Exception):\n \"\"\"\n Base exception for validation errors.\n\n Attributes:\n field: The field name that failed validation\n value: The value that failed validation\n message: Human-readable error message\n code: Error code for programmatic handling\n \"\"\"\n\n def __init__(\n self, field: str, value: Any, message: str, code: str = \"VALIDATION_ERROR\"\n ):\n self.field = field\n self.value = value\n self.message = message\n self.code = code\n super().__init__(f\"{field}: {message}\")\n\nclass ValidationResult:\n \"\"\"\n Container for validation results.\n\n Allows collecting multiple validation errors and warnings\n while maintaining performance for success cases.\n \"\"\"\n\n def __init__(self):\n self.errors: List[ValidationError] = []\n self.warnings: List[str] = []\n\n def add_error(self, error: ValidationError) -> None:\n \"\"\"Add a validation error.\"\"\"\n self.errors.append(error)\n\n def add_warning(self, warning: str) -> None:\n \"\"\"Add a validation warning.\"\"\"\n self.warnings.append(warning)\n\n def is_valid(self) -> bool:\n \"\"\"Check if validation passed (no errors).\"\"\"\n return len(self.errors) == 0\n\n def get_error_messages(self) -> List[str]:\n \"\"\"Get list of error messages.\"\"\"\n return [str(error) for error in self.errors]\n\n def merge(self, other: \"ValidationResult\") -> None:\n \"\"\"Merge another validation result into this one.\"\"\"\n self.errors.extend(other.errors)\n self.warnings.extend(other.warnings)", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 1650}, "tests/test_cli_parser.py::98": {"resolved_imports": ["src/vllm_cli/cli/parser.py"], "used_names": ["create_parser"], "enclosing_function": "test_models_command_with_details", "extracted_code": "# Source: src/vllm_cli/cli/parser.py\ndef create_parser() -> argparse.ArgumentParser:\n \"\"\"\n Create the main argument parser for vLLM CLI.\n\n Sets up the main parser with all subcommands and their arguments.\n\n Returns:\n Configured ArgumentParser instance\n \"\"\"\n parser = argparse.ArgumentParser(\n prog=\"vllm-cli\",\n description=\"vLLM CLI - Convenient LLM serving tool\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"Examples:\n vllm-cli # Interactive mode\n vllm-cli serve MODEL --profile standard # Serve with profile\n vllm-cli serve MODEL --quantization awq # Serve with AWQ quantization\n vllm-cli serve MODEL --extra-args \"--seed 42\" # With custom vLLM args\n vllm-cli info # System information\n vllm-cli models # List available models\n vllm-cli status # Show active servers\"\"\",\n )\n\n # Global options\n from .. import __version__\n\n parser.add_argument(\n \"--version\", action=\"version\", version=f\"vLLM CLI {__version__}\"\n )\n\n # Create subparsers for commands\n subparsers = parser.add_subparsers(\n dest=\"command\",\n help=\"Available commands\",\n metavar=\"{serve,proxy,info,models,shortcuts,status,stop,dirs}\",\n )\n\n # Add individual command parsers\n _add_serve_parser(subparsers)\n _add_proxy_parser(subparsers)\n _add_info_parser(subparsers)\n _add_models_parser(subparsers)\n _add_shortcuts_parser(subparsers)\n _add_status_parser(subparsers)\n _add_stop_parser(subparsers)\n _add_dirs_parser(subparsers)\n\n return parser", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1705}, "tests/test_profiles.py::87": {"resolved_imports": ["src/vllm_cli/config/profiles.py"], "used_names": ["ProfileManager"], "enclosing_function": "test_update_existing_profile", "extracted_code": "# Source: src/vllm_cli/config/profiles.py\nclass ProfileManager:\n \"\"\"\n Manages user profiles for vLLM configurations.\n\n Handles creation, retrieval, updating, and deletion of user profiles\n with validation and persistence.\n \"\"\"\n\n def __init__(self, config_dir: Path):\n self.config_dir = config_dir\n self.user_profiles_file = config_dir / \"user_profiles.json\"\n\n # Paths for schema files (packaged with application)\n schema_dir = Path(__file__).parent.parent / \"schemas\"\n self.default_profiles_file = schema_dir / \"default_profiles.json\"\n\n # Load profiles\n self.default_profiles = self._load_default_profiles()\n self.user_profiles = self._load_user_profiles()\n\n def _load_json_file(self, filepath: Path) -> Dict[str, Any]:\n \"\"\"Load a JSON file safely.\"\"\"\n if filepath.exists():\n try:\n with open(filepath, \"r\") as f:\n return json.load(f)\n except Exception as e:\n logger.error(f\"Error loading {filepath}: {e}\")\n return {}\n\n def _save_json_file(self, filepath: Path, data: Dict[str, Any]) -> bool:\n \"\"\"Save data to a JSON file.\"\"\"\n try:\n with open(filepath, \"w\") as f:\n json.dump(data, f, indent=2)\n return True\n except Exception as e:\n logger.error(f\"Error saving {filepath}: {e}\")\n return False\n\n def _load_default_profiles(self) -> Dict[str, Any]:\n \"\"\"Load default built-in profiles.\"\"\"\n profiles = self._load_json_file(self.default_profiles_file)\n return profiles.get(\"profiles\", {})\n\n def _load_user_profiles(self) -> Dict[str, Any]:\n \"\"\"Load user-created custom profiles.\"\"\"\n return self._load_json_file(self.user_profiles_file)\n\n def _save_user_profiles(self) -> bool:\n \"\"\"Save user profiles to file.\"\"\"\n return self._save_json_file(self.user_profiles_file, self.user_profiles)\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n all_profiles = deepcopy(self.default_profiles)\n all_profiles.update(self.user_profiles)\n return all_profiles\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name.\"\"\"\n # Check user profiles first, then default profiles\n if name in self.user_profiles:\n return deepcopy(self.user_profiles[name])\n elif name in self.default_profiles:\n return deepcopy(self.default_profiles[name])\n return None\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"\n Save or update a user profile with validation.\n\n Args:\n name: Profile name\n profile: Profile data to save\n\n Returns:\n True if saved successfully\n\n Raises:\n ProfileError: If profile validation fails or save fails\n \"\"\"\n try:\n # Validate profile structure\n if not isinstance(profile, dict):\n raise ProfileError(\n \"Profile must be a dictionary\",\n profile_name=name,\n error_code=\"INVALID_PROFILE_TYPE\",\n )\n\n # Process LoRA configuration if present\n if \"config\" in profile:\n config = profile[\"config\"]\n\n # Handle LoRA adapters in config\n if \"lora_adapters\" in config:\n # Validate LoRA adapter entries\n lora_adapters = config[\"lora_adapters\"]\n if isinstance(lora_adapters, list):\n # Ensure each adapter has required fields\n for adapter in lora_adapters:\n if not isinstance(adapter, dict):\n continue\n if \"path\" not in adapter and \"name\" in adapter:\n # Try to resolve adapter by name\n adapter[\"path\"] = self._resolve_lora_path(\n adapter[\"name\"]\n )\n\n # Convert to lora_modules format for vLLM\n if lora_adapters:\n config[\"enable_lora\"] = True\n lora_modules = []\n for adapter in lora_adapters:\n if isinstance(adapter, dict):\n name = adapter.get(\"name\", \"adapter\")\n path = adapter.get(\"path\", \"\")\n if path:\n lora_modules.append(f\"{name}={path}\")\n if lora_modules:\n config[\"lora_modules\"] = \" \".join(lora_modules)\n\n # Save the profile\n self.user_profiles[name] = deepcopy(profile)\n\n if not self._save_user_profiles():\n raise ProfileError(\n \"Failed to save profile to disk\",\n profile_name=name,\n error_code=\"PROFILE_SAVE_FAILED\",\n )\n\n logger.info(f\"Successfully saved user profile: {name}\")\n return True\n\n except ProfileError:\n raise\n except Exception as e:\n logger.error(f\"Unexpected error saving profile {name}: {e}\")\n raise ProfileError(\n f\"Unexpected error saving profile: {e}\",\n profile_name=name,\n error_code=\"PROFILE_SAVE_ERROR\",\n ) from e\n\n def _resolve_lora_path(self, adapter_name: str) -> str:\n \"\"\"\n Try to resolve a LoRA adapter path by name.\n\n Args:\n adapter_name: Name of the LoRA adapter\n\n Returns:\n Path to the adapter if found, empty string otherwise\n \"\"\"\n try:\n from ..models import scan_for_lora_adapters\n\n adapters = scan_for_lora_adapters()\n for adapter in adapters:\n if (\n adapter.get(\"name\") == adapter_name\n or adapter.get(\"display_name\") == adapter_name\n ):\n return adapter.get(\"path\", \"\")\n except Exception as e:\n logger.debug(f\"Could not resolve LoRA path for {adapter_name}: {e}\")\n return \"\"\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n if name in self.user_profiles:\n del self.user_profiles[name]\n return self._save_user_profiles()\n return False\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n profile = self.get_profile(profile_name)\n if not profile:\n logger.error(f\"Profile '{profile_name}' not found\")\n return False\n\n export_data = {\"version\": \"1.0\", \"profile\": profile}\n\n try:\n with open(filepath, \"w\") as f:\n json.dump(export_data, f, indent=2)\n logger.info(f\"Profile '{profile_name}' exported to {filepath}\")\n return True\n except Exception as e:\n logger.error(f\"Error exporting profile: {e}\")\n return False\n\n def import_profile(\n self,\n filepath: Path,\n new_name: Optional[str] = None,\n validate_config_func: Optional[Callable] = None,\n ) -> bool:\n \"\"\"\n Import a profile from a JSON file with comprehensive validation.\n\n Args:\n filepath: Path to the profile file\n new_name: Optional new name for the profile\n validate_config_func: Optional function to validate profile config\n\n Returns:\n True if imported successfully\n\n Raises:\n ProfileError: If import fails for any reason\n \"\"\"\n try:\n # Check file exists\n if not filepath.exists():\n raise ProfileError(\n f\"Profile file not found: {filepath}\",\n error_code=\"PROFILE_FILE_NOT_FOUND\",\n )\n\n # Load and parse file\n try:\n with open(filepath, \"r\") as f:\n data = json.load(f)\n except json.JSONDecodeError as e:\n raise ProfileError(\n f\"Invalid JSON in profile file: {e}\",\n error_code=\"PROFILE_INVALID_JSON\",\n ) from e\n\n # Validate file format\n if not isinstance(data, dict) or \"profile\" not in data:\n raise ProfileError(\n \"Invalid profile file format - missing 'profile' key\",\n error_code=\"PROFILE_INVALID_FORMAT\",\n )\n\n profile = data[\"profile\"]\n name = new_name or profile.get(\"name\", filepath.stem)\n\n # Validate profile configuration if function provided\n if validate_config_func and \"config\" in profile:\n is_valid, errors = validate_config_func(profile[\"config\"])\n if not is_valid:\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n # Save the profile\n return self.save_user_profile(name, profile)\n\n except ProfileError:\n raise\n except Exception as e:\n logger.error(f\"Unexpected error importing profile from {filepath}: {e}\")\n raise ProfileError(\n f\"Failed to import profile: {e}\", error_code=\"PROFILE_IMPORT_ERROR\"\n ) from e\n\n def list_profile_names(self) -> Dict[str, List[str]]:\n \"\"\"\n List all profile names categorized by type.\n\n Returns:\n Dictionary with 'default' and 'user' lists of profile names\n \"\"\"\n return {\n \"default\": list(self.default_profiles.keys()),\n \"user\": list(self.user_profiles.keys()),\n }\n\n def profile_exists(self, name: str) -> bool:\n \"\"\"Check if a profile exists (in either default or user profiles).\"\"\"\n return name in self.default_profiles or name in self.user_profiles\n\n def is_user_profile(self, name: str) -> bool:\n \"\"\"Check if a profile is a user-created profile.\"\"\"\n return name in self.user_profiles\n\n def has_user_override(self, name: str) -> bool:\n \"\"\"\n Check if a built-in profile has been overridden by a user profile.\n\n Args:\n name: Profile name to check\n\n Returns:\n True if this is a built-in profile that has a user override\n \"\"\"\n return name in self.default_profiles and name in self.user_profiles\n\n def get_original_default_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get the original default profile without any user overrides.\n\n Args:\n name: Profile name\n\n Returns:\n Original default profile if it exists, None otherwise\n \"\"\"\n if name in self.default_profiles:\n return deepcopy(self.default_profiles[name])\n return None\n\n def reset_to_default(self, name: str) -> bool:\n \"\"\"\n Reset a customized built-in profile to its default settings.\n\n This removes the user override for a built-in profile.\n\n Args:\n name: Profile name to reset\n\n Returns:\n True if reset successfully, False otherwise\n \"\"\"\n # Only reset if this is a built-in profile with a user override\n if self.has_user_override(name):\n return self.delete_user_profile(name)\n return False\n\n def get_profile_count(self) -> Dict[str, int]:\n \"\"\"Get count of profiles by type.\"\"\"\n return {\n \"default\": len(self.default_profiles),\n \"user\": len(self.user_profiles),\n \"total\": len(self.default_profiles) + len(self.user_profiles),\n }\n\n def apply_dynamic_defaults(self, profile_config: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Apply dynamic defaults to a profile configuration.\n\n This function intelligently sets tensor_parallel_size for multi-GPU systems.\n For single GPU systems, it allows vLLM to use its default behavior.\n\n Note: vLLM defaults to using only 1 GPU unless tensor_parallel_size is explicitly set.\n\n Args:\n profile_config: The profile configuration to enhance\n\n Returns:\n Enhanced profile configuration with dynamic defaults applied\n \"\"\"\n config = deepcopy(profile_config)\n\n # Apply dynamic tensor_parallel_size if not specified\n # Note: vLLM defaults to single GPU, so we only set this for multi-GPU systems\n # where tensor parallelism would be beneficial\n if \"tensor_parallel_size\" not in config:\n gpu_count = self._get_gpu_count()\n if gpu_count > 1:\n config[\"tensor_parallel_size\"] = gpu_count\n logger.debug(\n f\"Set tensor_parallel_size to {gpu_count} for multi-GPU system\"\n )\n # For single GPU, let vLLM use its default (no tensor_parallel_size needed)\n\n return config\n\n def _get_gpu_count(self) -> int:\n \"\"\"\n Get the number of available GPUs for tensor parallelism.\n\n Returns:\n Number of GPUs available, defaults to 1 if detection fails\n \"\"\"\n try:\n gpus = get_gpu_info()\n gpu_count = len(gpus) if gpus else 1\n logger.debug(f\"Detected {gpu_count} GPU(s)\")\n return gpu_count\n except Exception as e:\n logger.warning(f\"Failed to detect GPU count, defaulting to 1: {e}\")\n return 1", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 14008}, "tests/test_ollama_support.py::31": {"resolved_imports": ["src/vllm_cli/models/discovery.py", "src/vllm_cli/models/manager.py"], "used_names": ["build_model_dict"], "enclosing_function": "test_build_model_dict_with_ollama", "extracted_code": "# Source: src/vllm_cli/models/discovery.py\ndef build_model_dict(item: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Build a standardized model dictionary from model data.\n\n Takes raw model information from various sources and normalizes\n it into a consistent format.\n\n Args:\n item: Model item data\n\n Returns:\n Standardized model dictionary\n \"\"\"\n publisher = item.get(\"publisher\", \"unknown\")\n display_name = item.get(\"display_name\", item.get(\"name\", \"unknown\"))\n\n # Create proper model name\n if publisher and publisher != \"unknown\":\n model_name = f\"{publisher}/{display_name}\"\n else:\n model_name = display_name\n\n return {\n \"name\": model_name,\n \"size\": item.get(\"size\", 0),\n \"path\": item.get(\"path\", \"\"),\n \"type\": item.get(\"type\", \"model\"),\n \"publisher\": publisher,\n \"display_name\": display_name,\n \"metadata\": item.get(\"metadata\", {}),\n }", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 950}, "tests/test_model_manager.py::15": {"resolved_imports": ["src/vllm_cli/models/cache.py", "src/vllm_cli/models/manager.py"], "used_names": ["ModelCache", "ModelManager"], "enclosing_function": "test_init", "extracted_code": "# Source: src/vllm_cli/models/cache.py\nclass ModelCache:\n \"\"\"\n Cache for model discovery results.\n\n Provides time-based caching of model listings to avoid expensive\n directory scanning operations when model data is accessed frequently.\n \"\"\"\n\n def __init__(self, ttl_seconds: float = 30.0):\n \"\"\"\n Initialize model cache.\n\n Args:\n ttl_seconds: Time-to-live for cached data in seconds\n \"\"\"\n self.ttl_seconds = ttl_seconds\n self._cache: Optional[Tuple[float, List[Dict[str, Any]]]] = None\n self._stats = {\"hits\": 0, \"misses\": 0, \"updates\": 0}\n\n def get_cached_models(self) -> Optional[List[Dict[str, Any]]]:\n \"\"\"\n Get cached model list if still valid.\n\n Returns:\n List of cached models if cache is valid, None if expired or empty\n \"\"\"\n if self._cache is None:\n self._stats[\"misses\"] += 1\n return None\n\n cache_time, cached_data = self._cache\n\n # Check if cache is still valid\n if time.time() - cache_time < self.ttl_seconds:\n self._stats[\"hits\"] += 1\n logger.debug(f\"Cache hit: returning {len(cached_data)} cached models\")\n return cached_data.copy() # Return copy to prevent modification\n else:\n # Cache expired\n self._stats[\"misses\"] += 1\n logger.debug(\"Cache expired\")\n self._cache = None\n return None\n\n def cache_models(self, models: List[Dict[str, Any]]) -> None:\n \"\"\"\n Cache a list of models.\n\n Args:\n models: List of model dictionaries to cache\n \"\"\"\n self._cache = (time.time(), models.copy())\n self._stats[\"updates\"] += 1\n logger.debug(f\"Cached {len(models)} models\")\n\n def clear_cache(self) -> None:\n \"\"\"Clear the model cache.\"\"\"\n self._cache = None\n # Increment misses to reflect that the next access will be a miss\n self._stats[\"misses\"] += 1\n logger.debug(\"Model cache cleared\")\n\n def is_cached(self) -> bool:\n \"\"\"\n Check if there is valid cached data.\n\n Returns:\n True if cache contains valid data, False otherwise\n \"\"\"\n if self._cache is None:\n return False\n\n cache_time, _ = self._cache\n return time.time() - cache_time < self.ttl_seconds\n\n def get_cache_age(self) -> Optional[float]:\n \"\"\"\n Get the age of cached data in seconds.\n\n Returns:\n Age in seconds if cache exists, None if no cache\n \"\"\"\n if self._cache is None:\n return None\n\n cache_time, _ = self._cache\n return time.time() - cache_time\n\n def get_cache_stats(self) -> Dict[str, Any]:\n \"\"\"\n Get cache statistics.\n\n Returns:\n Dictionary with cache performance statistics\n \"\"\"\n total_requests = self._stats[\"hits\"] + self._stats[\"misses\"]\n hit_rate = (\n (self._stats[\"hits\"] / total_requests * 100) if total_requests > 0 else 0\n )\n\n stats = {\n \"hits\": self._stats[\"hits\"],\n \"misses\": self._stats[\"misses\"],\n \"updates\": self._stats[\"updates\"],\n \"total_requests\": total_requests,\n \"hit_rate_percent\": round(hit_rate, 2),\n \"is_cached\": self.is_cached(),\n \"cache_age_seconds\": self.get_cache_age(),\n \"ttl_seconds\": self.ttl_seconds,\n }\n\n if self._cache:\n _, cached_data = self._cache\n stats[\"cached_models_count\"] = len(cached_data)\n else:\n stats[\"cached_models_count\"] = 0\n\n return stats\n\n def get_stats(self) -> Dict[str, Any]:\n \"\"\"\n Alias for get_cache_stats() for backward compatibility.\n\n Returns:\n Dictionary with cache performance statistics\n \"\"\"\n return self.get_cache_stats()\n\n def reset_stats(self) -> None:\n \"\"\"Reset cache statistics.\"\"\"\n self._stats = {\"hits\": 0, \"misses\": 0, \"updates\": 0}\n logger.debug(\"Cache statistics reset\")\n\n def set_ttl(self, ttl_seconds: float) -> None:\n \"\"\"\n Set new TTL for cache.\n\n Args:\n ttl_seconds: New time-to-live in seconds\n \"\"\"\n old_ttl = self.ttl_seconds\n self.ttl_seconds = ttl_seconds\n logger.debug(f\"Cache TTL changed from {old_ttl}s to {ttl_seconds}s\")\n\n def get_cached_model_count(self) -> int:\n \"\"\"\n Get the number of models currently cached.\n\n Returns:\n Number of cached models, 0 if no cache\n \"\"\"\n if self._cache is None:\n return 0\n\n _, cached_data = self._cache\n return len(cached_data)\n\n\n# Source: src/vllm_cli/models/manager.py\nclass ModelManager:\n \"\"\"\n Manages model discovery, caching, and metadata operations.\n\n Provides a high-level interface for model operations including\n listing, searching, and retrieving model information with\n integrated caching for performance.\n \"\"\"\n\n def __init__(self):\n self.cache = ModelCache()\n\n def list_available_models(self, refresh: bool = False) -> List[Dict[str, Any]]:\n \"\"\"\n List all available downloaded models with caching.\n\n Model scanning can be expensive, so results are cached for a short time\n to improve performance when multiple UI components need model data.\n\n Args:\n refresh: Force refresh the model cache, ignoring TTL\n\n Returns:\n List of model dictionaries with keys:\n - name: Full model name (publisher/model)\n - size: Model size in bytes\n - path: Path to model directory\n - type: Model type (model, custom_model)\n - publisher: Model publisher/organization\n - display_name: Human-readable model name\n - metadata: Additional model metadata\n \"\"\"\n # If refresh is forced, clear cache first to ensure fresh data\n if refresh:\n self.cache.clear_cache()\n logger.debug(\"Cache cleared for forced refresh\")\n else:\n # Check cache only if not refreshing\n cached_models = self.cache.get_cached_models()\n if cached_models is not None:\n return cached_models\n\n # Fetch fresh model data\n models = scan_for_models()\n\n # Process and normalize model data\n processed_models = []\n for item in models:\n # Accept all model types from hf-model-tool\n model_types = [\"model\", \"custom_model\", \"ollama_model\", \"gguf_model\"]\n if item.get(\"type\") in model_types:\n # For Ollama/GGUF models, use the item directly (already formatted)\n if item.get(\"type\") in [\"ollama_model\", \"gguf_model\"]:\n processed_models.append(item)\n else:\n model_dict = build_model_dict(item)\n processed_models.append(model_dict)\n\n # Sort models by name\n processed_models.sort(key=lambda x: x[\"name\"])\n\n # Update cache\n self.cache.cache_models(processed_models)\n\n logger.info(f\"Found {len(processed_models)} models\")\n return processed_models\n\n def get_model_details(self, model_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get detailed information about a specific model.\n\n Args:\n model_name: Name of the model to get details for\n\n Returns:\n Dictionary with model details or None if not found\n \"\"\"\n # First, try to find from cached models\n models = self.list_available_models()\n model_info = None\n\n for model in models:\n if model[\"name\"] == model_name or model.get(\"display_name\") == model_name:\n model_info = model\n break\n\n if not model_info:\n logger.warning(f\"Model {model_name} not found\")\n return None\n\n # Build detailed information\n details = {\n \"name\": model_info[\"name\"],\n \"full_name\": model_info[\"name\"],\n \"path\": model_info.get(\"path\", \"\"),\n \"size\": model_info.get(\"size\", 0),\n \"type\": model_info.get(\"type\", \"model\"),\n \"publisher\": model_info.get(\"publisher\", \"unknown\"),\n \"display_name\": model_info.get(\"display_name\", model_name),\n }\n\n # Extract metadata if available\n metadata = model_info.get(\"metadata\", {})\n if metadata:\n details[\"architecture\"] = (\n metadata.get(\"architectures\", [\"unknown\"])[0]\n if metadata.get(\"architectures\")\n else \"unknown\"\n )\n details[\"model_type\"] = metadata.get(\"model_type\", \"unknown\")\n details[\"torch_dtype\"] = metadata.get(\"torch_dtype\", \"unknown\")\n details[\"vocab_size\"] = metadata.get(\"vocab_size\", \"unknown\")\n\n # Add to main details\n details[\"metadata\"] = metadata\n\n # Try to read config.json for more details if path exists\n if details[\"path\"]:\n from .metadata import extract_model_config\n\n config_data = extract_model_config(details[\"path\"])\n if config_data:\n details.update(config_data)\n\n return details\n\n def search_models(self, query: str) -> List[Dict[str, Any]]:\n \"\"\"\n Search for models matching a query.\n\n Args:\n query: Search query string\n\n Returns:\n List of matching models\n \"\"\"\n models = self.list_available_models()\n query_lower = query.lower()\n\n # Filter models matching the query\n matches = []\n for model in models:\n if (\n query_lower in model[\"name\"].lower()\n or query_lower in model.get(\"display_name\", \"\").lower()\n or query_lower in model.get(\"publisher\", \"\").lower()\n ):\n matches.append(model)\n\n return matches\n\n def get_model_count(self) -> int:\n \"\"\"\n Get the total number of available models.\n\n Returns:\n Number of available models\n \"\"\"\n return len(self.list_available_models())\n\n def get_models_by_publisher(self, publisher: str) -> List[Dict[str, Any]]:\n \"\"\"\n Get all models from a specific publisher.\n\n Args:\n publisher: Publisher/organization name\n\n Returns:\n List of models from the publisher\n \"\"\"\n models = self.list_available_models()\n return [\n model\n for model in models\n if model.get(\"publisher\", \"\").lower() == publisher.lower()\n ]\n\n def get_models_by_type(self, model_type: str) -> List[Dict[str, Any]]:\n \"\"\"\n Get all models of a specific type.\n\n Args:\n model_type: Type of model (e.g., 'model', 'custom_model')\n\n Returns:\n List of models of the specified type\n \"\"\"\n models = self.list_available_models()\n return [model for model in models if model.get(\"type\") == model_type]\n\n def refresh_cache(self) -> None:\n \"\"\"Force refresh of the model cache.\"\"\"\n # First, force registry refresh to pick up any changes\n try:\n import os\n from pathlib import Path\n\n from hf_model_tool import get_registry\n\n # Clear all possible cache files\n cache_locations = [\n Path.home() / \".config/hf-model-tool/registry_cache.json\",\n Path.home() / \".cache/hf-model-tool/registry.json\",\n Path.home() / \".hf-model-tool/cache.json\",\n ]\n\n for cache_file in cache_locations:\n if cache_file.exists():\n try:\n os.remove(cache_file)\n logger.debug(f\"Removed cache file: {cache_file}\")\n except Exception as e:\n logger.debug(f\"Could not remove {cache_file}: {e}\")\n\n # Get registry and clear its in-memory cache\n registry = get_registry()\n\n # Clear all in-memory collections\n registry.models.clear()\n registry.custom_models.clear()\n registry.ollama_models.clear()\n registry.gguf_models.clear()\n registry.lora_adapters.clear()\n registry.datasets.clear()\n\n # Reset scan time to force rescan\n registry._last_scan_time = 0\n\n # Force complete rescan without incremental updates\n registry.scan_all(force=True, incremental=False)\n logger.info(\"Forced complete registry refresh\")\n except Exception as e:\n logger.debug(f\"Registry refresh error: {e}\")\n\n # Clear the cache to ensure we don't get stale data\n self.cache.clear_cache()\n logger.debug(\"Cache cleared\")\n\n # Now fetch fresh models - this will populate the cache with new data\n models = self.list_available_models(refresh=True)\n logger.info(f\"Model cache refreshed with {len(models)} models\")\n\n def get_cache_stats(self) -> Dict[str, Any]:\n \"\"\"\n Get cache statistics.\n\n Returns:\n Dictionary with cache statistics\n \"\"\"\n return self.cache.get_cache_stats()", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 13418}, "tests/test_cli_parser.py::83": {"resolved_imports": ["src/vllm_cli/cli/parser.py"], "used_names": ["create_parser"], "enclosing_function": "test_info_command", "extracted_code": "# Source: src/vllm_cli/cli/parser.py\ndef create_parser() -> argparse.ArgumentParser:\n \"\"\"\n Create the main argument parser for vLLM CLI.\n\n Sets up the main parser with all subcommands and their arguments.\n\n Returns:\n Configured ArgumentParser instance\n \"\"\"\n parser = argparse.ArgumentParser(\n prog=\"vllm-cli\",\n description=\"vLLM CLI - Convenient LLM serving tool\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"Examples:\n vllm-cli # Interactive mode\n vllm-cli serve MODEL --profile standard # Serve with profile\n vllm-cli serve MODEL --quantization awq # Serve with AWQ quantization\n vllm-cli serve MODEL --extra-args \"--seed 42\" # With custom vLLM args\n vllm-cli info # System information\n vllm-cli models # List available models\n vllm-cli status # Show active servers\"\"\",\n )\n\n # Global options\n from .. import __version__\n\n parser.add_argument(\n \"--version\", action=\"version\", version=f\"vLLM CLI {__version__}\"\n )\n\n # Create subparsers for commands\n subparsers = parser.add_subparsers(\n dest=\"command\",\n help=\"Available commands\",\n metavar=\"{serve,proxy,info,models,shortcuts,status,stop,dirs}\",\n )\n\n # Add individual command parsers\n _add_serve_parser(subparsers)\n _add_proxy_parser(subparsers)\n _add_info_parser(subparsers)\n _add_models_parser(subparsers)\n _add_shortcuts_parser(subparsers)\n _add_status_parser(subparsers)\n _add_stop_parser(subparsers)\n _add_dirs_parser(subparsers)\n\n return parser", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1705}, "tests/proxy/test_integration.py::77": {"resolved_imports": ["src/vllm_cli/proxy/config.py", "src/vllm_cli/proxy/manager.py", "src/vllm_cli/proxy/models.py", "src/vllm_cli/proxy/server_process.py"], "used_names": ["ProxyConfigManager"], "enclosing_function": "test_load_proxy_config", "extracted_code": "# Source: src/vllm_cli/proxy/config.py\nclass ProxyConfigManager:\n \"\"\"\n Manages proxy server configuration including persistence and validation.\n \"\"\"\n\n def __init__(self):\n \"\"\"Initialize the proxy configuration manager.\"\"\"\n self.config_dir = Path.home() / \".config\" / \"vllm-cli\"\n # Default configuration file path - used as fallback when no path specified\n # Also maintains backward compatibility with existing configurations\n self.proxy_config_file = self.config_dir / \"proxy_config.yaml\"\n self.proxy_configs_dir = self.config_dir / \"proxy_configs\"\n self.config_dir.mkdir(parents=True, exist_ok=True)\n self.proxy_configs_dir.mkdir(parents=True, exist_ok=True)\n\n def load_config(self, config_path: Optional[Path] = None) -> ProxyConfig:\n \"\"\"\n Load proxy configuration from file.\n\n Args:\n config_path: Path to configuration file (uses default if not provided)\n\n Returns:\n ProxyConfig instance\n \"\"\"\n config_file = config_path or self.proxy_config_file\n\n if not config_file.exists():\n logger.info(f\"No config file found at {config_file}, using defaults\")\n return self.get_default_config()\n\n try:\n with open(config_file, \"r\") as f:\n if config_file.suffix in [\".yaml\", \".yml\"]:\n config_dict = yaml.safe_load(f)\n else:\n config_dict = json.load(f)\n\n return self._parse_config(config_dict)\n\n except Exception as e:\n logger.error(f\"Failed to load config from {config_file}: {e}\")\n return self.get_default_config()\n\n def save_config(self, config: ProxyConfig, config_path: Optional[Path] = None):\n \"\"\"\n Save proxy configuration to file.\n\n Args:\n config: ProxyConfig to save\n config_path: Path to save to (uses default if not provided)\n \"\"\"\n config_file = config_path or self.proxy_config_file\n\n try:\n config_dict = {\n \"proxy\": {\n \"host\": config.host,\n \"port\": config.port,\n \"enable_cors\": config.enable_cors,\n \"enable_metrics\": config.enable_metrics,\n \"log_requests\": config.log_requests,\n },\n \"models\": [\n {\n \"name\": model.name,\n \"model_path\": model.model_path,\n \"gpu_ids\": model.gpu_ids,\n \"port\": model.port,\n \"profile\": model.profile,\n \"config_overrides\": model.config_overrides,\n \"enabled\": model.enabled,\n \"loading_priority\": model.loading_priority,\n }\n for model in config.models\n ],\n }\n\n with open(config_file, \"w\") as f:\n if config_file.suffix in [\".yaml\", \".yml\"]:\n yaml.safe_dump(config_dict, f, default_flow_style=False)\n else:\n json.dump(config_dict, f, indent=2)\n\n logger.info(f\"Saved proxy configuration to {config_file}\")\n\n except Exception as e:\n logger.error(f\"Failed to save config to {config_file}: {e}\")\n\n def save_named_config(self, config: ProxyConfig, name: str):\n \"\"\"\n Save proxy configuration with a specific name.\n\n Args:\n config: ProxyConfig to save\n name: Name for the configuration\n \"\"\"\n # Sanitize name for filesystem\n safe_name = \"\".join(c if c.isalnum() or c in \"_-\" else \"_\" for c in name)\n config_file = self.proxy_configs_dir / f\"{safe_name}.yaml\"\n\n self.save_config(config, config_file)\n logger.info(f\"Saved proxy configuration as '{name}'\")\n\n def load_named_config(self, name: str) -> Optional[ProxyConfig]:\n \"\"\"\n Load a named proxy configuration.\n\n Args:\n name: Name of the configuration to load\n\n Returns:\n ProxyConfig if found, None otherwise\n \"\"\"\n safe_name = \"\".join(c if c.isalnum() or c in \"_-\" else \"_\" for c in name)\n config_file = self.proxy_configs_dir / f\"{safe_name}.yaml\"\n\n if not config_file.exists():\n logger.error(f\"Configuration '{name}' not found\")\n return None\n\n return self.load_config(config_file)\n\n def list_saved_configs(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"\n List all saved proxy configurations.\n\n Returns:\n Dictionary mapping config names to their summaries\n \"\"\"\n configs = {}\n\n # Check new named configs directory\n for config_file in self.proxy_configs_dir.glob(\"*.yaml\"):\n name = config_file.stem\n try:\n config = self.load_config(config_file)\n if config:\n configs[name] = {\n \"file\": str(config_file),\n \"models\": len(config.models),\n \"port\": config.port,\n \"model_names\": [m.name for m in config.models][\n :3\n ], # First 3 models\n }\n except Exception as e:\n logger.warning(f\"Failed to load config {name}: {e}\")\n\n # Also check legacy default location\n if self.proxy_config_file.exists():\n try:\n config = self.load_config(self.proxy_config_file)\n if config:\n configs[\"default\"] = {\n \"file\": str(self.proxy_config_file),\n \"models\": len(config.models),\n \"port\": config.port,\n \"model_names\": [m.name for m in config.models][:3],\n }\n except Exception:\n pass\n\n return configs\n\n def delete_named_config(self, name: str) -> bool:\n \"\"\"\n Delete a named proxy configuration.\n\n Args:\n name: Name of the configuration to delete\n\n Returns:\n True if deleted successfully\n \"\"\"\n safe_name = \"\".join(c if c.isalnum() or c in \"_-\" else \"_\" for c in name)\n config_file = self.proxy_configs_dir / f\"{safe_name}.yaml\"\n\n if config_file.exists():\n try:\n config_file.unlink()\n logger.info(f\"Deleted configuration '{name}'\")\n return True\n except Exception as e:\n logger.error(f\"Failed to delete configuration '{name}': {e}\")\n return False\n else:\n logger.warning(f\"Configuration '{name}' not found\")\n return False\n\n def get_default_config(self) -> ProxyConfig:\n \"\"\"\n Get default proxy configuration.\n\n Returns:\n Default ProxyConfig instance\n \"\"\"\n return ProxyConfig(\n host=\"0.0.0.0\", # nosec B104\n port=8000,\n models=[],\n enable_cors=True,\n enable_metrics=True,\n log_requests=False,\n )\n\n def _parse_config(self, config_dict: Dict[str, Any]) -> ProxyConfig:\n \"\"\"\n Parse configuration dictionary into ProxyConfig.\n\n Args:\n config_dict: Configuration dictionary\n\n Returns:\n ProxyConfig instance\n \"\"\"\n proxy_settings = config_dict.get(\"proxy\", {})\n models_list = config_dict.get(\"models\", [])\n\n models = []\n for model_dict in models_list:\n try:\n models.append(ModelConfig(**model_dict))\n except Exception as e:\n logger.warning(f\"Failed to parse model config: {e}\")\n\n return ProxyConfig(\n host=proxy_settings.get(\"host\", \"0.0.0.0\"), # nosec B104\n port=proxy_settings.get(\"port\", 8000),\n models=models,\n enable_cors=proxy_settings.get(\"enable_cors\", True),\n enable_metrics=proxy_settings.get(\"enable_metrics\", True),\n log_requests=proxy_settings.get(\"log_requests\", False),\n )\n\n def validate_config(self, config: ProxyConfig) -> List[str]:\n \"\"\"\n Validate proxy configuration.\n\n Args:\n config: ProxyConfig to validate\n\n Returns:\n List of validation errors (empty if valid)\n \"\"\"\n errors = []\n\n # Check proxy port\n if not 1 <= config.port <= 65535:\n errors.append(f\"Invalid proxy port: {config.port}\")\n\n # Check for port conflicts\n used_ports = {config.port}\n for model in config.models:\n if model.port in used_ports:\n errors.append(f\"Port {model.port} is used by multiple services\")\n used_ports.add(model.port)\n\n # Check model names are unique\n model_names = [m.name for m in config.models]\n if len(model_names) != len(set(model_names)):\n errors.append(\"Model names must be unique\")\n\n return errors\n\n def create_example_config(self) -> ProxyConfig:\n \"\"\"\n Create an example proxy configuration.\n\n Returns:\n Example ProxyConfig instance\n \"\"\"\n return ProxyConfig(\n host=\"0.0.0.0\", # nosec B104\n port=8000,\n models=[\n ModelConfig(\n name=\"llama-3-8b\",\n model_path=\"meta-llama/Meta-Llama-3-8B-Instruct\",\n gpu_ids=[0],\n port=8001,\n profile=\"standard\",\n enabled=True,\n ),\n ModelConfig(\n name=\"mistral-7b\",\n model_path=\"mistralai/Mistral-7B-Instruct-v0.2\",\n gpu_ids=[1],\n port=8002,\n profile=\"performance\",\n enabled=True,\n ),\n ModelConfig(\n name=\"gemma-2b\",\n model_path=\"google/gemma-2b\",\n gpu_ids=[2],\n port=8003,\n profile=\"memory-optimized\",\n enabled=False, # Disabled by default\n ),\n ],\n enable_cors=True,\n enable_metrics=True,\n log_requests=False,\n )\n\n def export_config(self, config: ProxyConfig, export_path: Path):\n \"\"\"\n Export configuration to a file.\n\n Args:\n config: ProxyConfig to export\n export_path: Path to export to\n \"\"\"\n self.save_config(config, export_path)\n logger.info(f\"Exported configuration to {export_path}\")\n\n def import_config(self, import_path: Path) -> ProxyConfig:\n \"\"\"\n Import configuration from a file.\n\n Args:\n import_path: Path to import from\n\n Returns:\n Imported ProxyConfig instance\n \"\"\"\n config = self.load_config(import_path)\n logger.info(f\"Imported configuration from {import_path}\")\n return config", "n_imports_parsed": 9, "n_files_resolved": 4, "n_chars_extracted": 11221}, "tests/test_server_manager.py::153": {"resolved_imports": ["src/vllm_cli/server/__init__.py", "src/vllm_cli/server/process.py", "src/vllm_cli/server/manager.py"], "used_names": ["VLLMServer"], "enclosing_function": "test_get_recent_logs", "extracted_code": "# Source: src/vllm_cli/server/manager.py\nclass VLLMServer:\n \"\"\"\n Manages a vLLM server instance with comprehensive lifecycle control.\n\n This class handles the complete lifecycle of a vLLM server including\n configuration, process management, logging, monitoring, and cleanup.\n It supports both programmatically started servers and external server\n detection and management.\n\n Attributes:\n config: Server configuration dictionary\n model: Model name being served\n port: Port number the server is listening on\n process: Subprocess or external process reference\n log_file: File handle for server logs\n log_queue: Thread-safe queue for log lines\n log_thread: Background thread for log monitoring\n start_time: Timestamp when server was started\n log_path: Path to the server's log file\n \"\"\"\n\n def __init__(self, config: Dict[str, Any]) -> None:\n \"\"\"\n Initialize a vLLM server instance.\n\n Sets up the server configuration, logging infrastructure, and\n prepares the instance for server lifecycle management.\n\n Args:\n config: Server configuration dictionary containing model name,\n port, and other vLLM-specific parameters\n \"\"\"\n self.config: Dict[str, Any] = config\n\n # Extract model name - handle both string and dict (LoRA config) formats\n model_config = config.get(\"model\", \"unknown\")\n if isinstance(model_config, dict):\n # LoRA configuration - extract base model name\n self.model: str = model_config.get(\"model\", \"unknown\")\n else:\n # Regular string model name\n self.model: str = model_config\n\n self.port: int = config.get(\"port\", 8000)\n self.process: Optional[Union[subprocess.Popen, Any]] = None\n self.log_file: Optional[TextIO] = None\n self.log_queue: Queue[str] = Queue()\n self.log_thread: Optional[Thread] = None\n self.start_time: Optional[datetime] = None\n self.log_path: Path\n self._recent_logs: List[str] = []\n\n # Setup logging\n log_dir = Path.home() / \".vllm-cli\" / \"logs\"\n log_dir.mkdir(parents=True, exist_ok=True)\n\n timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n self.log_path = log_dir / f\"vllm_{self.model.replace('/', '_')}_{timestamp}.log\"\n\n def start(self) -> bool:\n \"\"\"\n Start the vLLM server.\n\n Returns:\n True if server started successfully, False otherwise\n \"\"\"\n if self.is_running():\n logger.warning(f\"Server already running for {self.model}\")\n return False\n\n try:\n # Build command - run directly without conda wrapper\n full_cmd = self._build_command()\n\n logger.info(f\"Starting vLLM server with command: {' '.join(full_cmd)}\")\n\n # Open log file for writing\n self.log_file = open(self.log_path, \"w\", buffering=1)\n\n # Start with parent environment\n env = os.environ.copy()\n # Note: No longer forcing PYTHONUNBUFFERED=1, let user control it\n\n # Layer 1: Apply universal environment variables from settings\n config_manager = ConfigManager()\n universal_env = config_manager.config.get(\"universal_environment\", {})\n if universal_env:\n logger.info(\n f\"Applying {len(universal_env)} universal environment variable(s)\"\n )\n for key, value in universal_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting universal {key}={value}\")\n else:\n logger.debug(f\"Setting universal {key}=\")\n\n # Layer 2: Apply profile environment variables (override universal)\n profile_env = self.config.get(\"profile_environment\", {})\n if profile_env:\n logger.info(\n f\"Applying {len(profile_env)} profile environment variable(s)\"\n )\n for key, value in profile_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting profile {key}={value}\")\n else:\n logger.debug(f\"Setting profile {key}=\")\n\n # Handle GPU device selection via CUDA_VISIBLE_DEVICES\n # This overrides any CUDA_VISIBLE_DEVICES from the profile\n if self.config.get(\"device\"):\n device_str = str(self.config[\"device\"])\n env[\"CUDA_VISIBLE_DEVICES\"] = device_str\n logger.info(f\"Setting CUDA_VISIBLE_DEVICES={device_str}\")\n\n # If using specific GPUs, adjust tensor parallel size if needed\n device_list = [d.strip() for d in device_str.split(\",\")]\n num_devices = len(device_list)\n\n # Check if tensor_parallel_size is set and compatible\n if self.config.get(\"tensor_parallel_size\"):\n tp_size = self.config[\"tensor_parallel_size\"]\n if tp_size > num_devices:\n logger.warning(\n f\"tensor_parallel_size ({tp_size}) > number of selected devices ({num_devices}). \"\n f\"Adjusting tensor_parallel_size to {num_devices}\"\n )\n self.config[\"tensor_parallel_size\"] = num_devices\n elif num_devices % tp_size != 0:\n logger.warning(\n f\"Number of GPUs ({num_devices}) is not evenly divisible by \"\n f\"tensor_parallel_size ({tp_size}). This may lead to inefficient GPU utilization. \"\n f\"Consider using tensor_parallel_size of: \"\n f\"{', '.join(str(i) for i in range(1, num_devices + 1) if num_devices % i == 0)}\"\n )\n\n # Add HuggingFace token if configured\n config_manager = ConfigManager()\n hf_token = config_manager.config.get(\"hf_token\")\n if hf_token:\n env[\"HF_TOKEN\"] = hf_token\n env[\"HUGGING_FACE_HUB_TOKEN\"] = hf_token # Some tools use this variant\n logger.info(\"HuggingFace token configured for server\")\n\n # Enable development mode for sleep endpoints if sleep mode is enabled\n if self.config.get(\"enable_sleep_mode\"):\n env[\"VLLM_SERVER_DEV_MODE\"] = \"1\"\n logger.info(\"Sleep mode enabled with development endpoints\")\n\n # Start the process with proper pipe configuration\n # Use start_new_session=True to create a new process group\n # This prevents the child process from receiving Ctrl+C signals\n self.process = subprocess.Popen(\n full_cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n text=True,\n bufsize=0, # Unbuffered\n universal_newlines=True,\n env=env,\n start_new_session=True, # Create new process group to isolate from parent signals\n )\n\n # Start log monitoring thread\n self._start_log_monitor()\n\n # Set start time and add to registry\n self.start_time = datetime.now()\n from .process import add_server\n\n add_server(self)\n\n # Return immediately - let the UI monitor the startup\n logger.info(\n f\"vLLM server process launched for {self.model} on port {self.port}\"\n )\n return True\n\n except Exception as e:\n logger.error(f\"Error starting vLLM server: {e}\")\n return False\n\n def _build_command(self) -> List[str]:\n \"\"\"\n Build the vLLM command from configuration using the schema.\n\n Returns:\n List of command arguments\n \"\"\"\n # Use the new ConfigManager to build CLI args\n config_manager = ConfigManager()\n\n # Start with the vllm command\n cmd = [\"vllm\"]\n\n # Add the arguments built from schema\n cli_args = config_manager.build_cli_args(self.config)\n cmd.extend(cli_args)\n\n # Handle extra_args if present (backward compatibility)\n if self.config.get(\"extra_args\"):\n self._add_extra_args_to_command(cmd)\n\n logger.debug(f\"Built command: {' '.join(cmd)}\")\n return cmd\n\n def _add_extra_args_to_command(self, cmd: List[str]) -> None:\n \"\"\"\n Add extra arguments to the vLLM command.\n\n Args:\n cmd: Command list to extend with extra arguments\n \"\"\"\n try:\n extra_args = shlex.split(self.config[\"extra_args\"])\n if extra_args:\n logger.info(f\"Adding extra arguments: {extra_args}\")\n cmd.extend(extra_args)\n except ValueError as e:\n logger.warning(f\"Failed to parse extra_args: {e}\")\n\n def _start_log_monitor(self) -> None:\n \"\"\"\n Start a thread to monitor log output from the vLLM server process.\n\n Creates a daemon thread that continuously reads stdout/stderr from\n the server process, writes to log files, and queues log lines for\n real-time display in the UI.\n \"\"\"\n self.log_thread = Thread(target=self._log_monitor_worker, daemon=True)\n self.log_thread.start()\n\n def _log_monitor_worker(self) -> None:\n \"\"\"\n Worker function for log monitoring thread.\n\n Continuously reads log output from the server process and handles\n file writing and queue management for UI display.\n \"\"\"\n try:\n self.log_queue.put(\"Starting vLLM server process...\")\n\n while self._should_continue_monitoring():\n if self._process_log_line():\n continue\n else:\n # No line read, check if process still running\n if self.process and self.process.poll() is not None:\n break\n time.sleep(0.01) # Small sleep to prevent busy waiting\n\n except Exception as e:\n logger.error(f\"Error in log monitor: {e}\")\n self.log_queue.put(f\"Log monitoring error: {e}\")\n\n def _should_continue_monitoring(self) -> bool:\n \"\"\"\n Check if log monitoring should continue.\n\n Returns:\n True if monitoring should continue, False otherwise\n \"\"\"\n return (\n self.is_running()\n and self.process\n and hasattr(self.process, \"stdout\")\n and self.process.stdout\n )\n\n def _process_log_line(self) -> bool:\n \"\"\"\n Process a single log line from the server output.\n\n Reads one line from the process stdout, writes it to the log file,\n and adds it to the queue for UI display after filtering and formatting.\n\n Returns:\n True if a line was processed, False if no line was available\n \"\"\"\n if not (self.process and self.process.stdout):\n return False\n\n line = self.process.stdout.readline()\n if not line:\n return False\n\n # Write to log file\n self._write_to_log_file(line)\n\n # Process for UI display\n line_stripped = line.strip()\n if line_stripped and self._should_display_log_line(line_stripped):\n # Truncate overly long lines\n if len(line_stripped) > 200:\n line_stripped = line_stripped[:197] + \"...\"\n\n self.log_queue.put(line_stripped)\n logger.debug(f\"Log captured: {line_stripped[:50]}...\")\n\n return True\n\n def _write_to_log_file(self, line: str) -> None:\n \"\"\"\n Write a log line to the log file.\n\n Args:\n line: Log line to write\n \"\"\"\n if self.log_file and not self.log_file.closed:\n self.log_file.write(line)\n self.log_file.flush()\n\n def _should_display_log_line(self, line: str) -> bool:\n \"\"\"\n Determine if a log line should be displayed in the UI.\n\n Filters out certain system messages that are not useful for users.\n\n Args:\n line: Stripped log line to check\n\n Returns:\n True if the line should be displayed, False otherwise\n \"\"\"\n # Filter out conda activation and system messages\n filtered_messages = [\n \"Activated CUDA\",\n \"Using nvcc from:\",\n \"Cuda compilation tools\",\n ]\n return not any(skip in line for skip in filtered_messages)\n\n def stop(self) -> bool:\n \"\"\"\n Stop the vLLM server.\n\n Returns:\n True if server stopped successfully, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n try:\n # Check if this is an external server\n if hasattr(self.process, \"terminate\"):\n # Normal subprocess\n # Since we created a new session, we need to terminate the entire process group\n try:\n # Get the process group ID (pgid)\n # Since we used start_new_session=True, the pgid is the same as the pid\n pgid = self.process.pid\n\n # Send SIGTERM to the entire process group for graceful shutdown\n logger.info(f\"Sending SIGTERM to process group {pgid}\")\n os.killpg(pgid, signal.SIGTERM)\n\n # Wait for process to terminate\n try:\n self.process.wait(timeout=10)\n logger.info(f\"Process group {pgid} terminated gracefully\")\n except subprocess.TimeoutExpired:\n # Force kill if not terminated\n logger.warning(\n f\"Process group {pgid} did not terminate, sending SIGKILL\"\n )\n os.killpg(pgid, signal.SIGKILL)\n self.process.wait()\n logger.info(f\"Process group {pgid} force killed\")\n\n except ProcessLookupError:\n # Process already dead\n logger.info(\"Process already terminated\")\n except PermissionError as e:\n # Fall back to terminating just the process\n logger.warning(\n f\"Permission denied for process group kill: {e}, falling back to process termination\"\n )\n self.process.terminate()\n try:\n self.process.wait(timeout=10)\n except subprocess.TimeoutExpired:\n self.process.kill()\n self.process.wait()\n elif hasattr(self.process, \"pid\"):\n # External server - kill entire process group or individual process\n try:\n pgid = self.process.pid\n killed = False\n\n # First attempt: try to kill process group\n try:\n os.killpg(pgid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process group {pgid}\")\n killed = True\n except (OSError, ProcessLookupError) as e:\n # Process group kill failed, try individual process\n logger.debug(\n f\"Process group kill failed: {e}, trying individual process\"\n )\n try:\n # Ensure pid is an integer (handle Mock objects)\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process {self.process.pid}\")\n killed = True\n except ProcessLookupError:\n # Process already dead\n logger.info(\n f\"Process {self.process.pid} already terminated\"\n )\n except OSError as e:\n logger.warning(\n f\"Failed to send SIGTERM to {self.process.pid}: {e}\"\n )\n\n if killed:\n # Wait for graceful shutdown\n time.sleep(2)\n\n # Check if still running and force kill if needed\n if self.is_running():\n try:\n os.killpg(pgid, signal.SIGKILL)\n logger.info(f\"Force killed process group {pgid}\")\n except (OSError, ProcessLookupError):\n # Process group kill failed, try individual\n try:\n # Ensure pid is an integer (handle Mock objects in tests)\n if hasattr(self.process, \"pid\"):\n try:\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGKILL)\n logger.info(f\"Force killed process {pid}\")\n except (TypeError, ValueError):\n # PID is not a valid integer (might be Mock)\n pass\n except ProcessLookupError:\n pass # Already dead\n except OSError as e:\n logger.error(\n f\"Failed to force kill {self.process.pid}: {e}\"\n )\n\n except Exception as e:\n logger.error(f\"Unexpected error stopping external server: {e}\")\n\n # Close log file if we have one\n if hasattr(self, \"log_file\") and self.log_file:\n self.log_file.close()\n\n # Remove from registry\n from .process import remove_server\n\n remove_server(self)\n\n logger.info(f\"vLLM server stopped for {self.model}\")\n return True\n\n except Exception as e:\n logger.error(f\"Error stopping vLLM server: {e}\")\n return False\n\n def is_running(self) -> bool:\n \"\"\"\n Check if the server is running.\n\n Returns:\n True if server is running, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n # Check if this is an external server (detected, not started by us)\n if hasattr(self.process, \"poll\"):\n # Normal subprocess\n return self.process.poll() is None\n elif hasattr(self.process, \"pid\"):\n # External server - check if PID still exists\n try:\n import psutil\n\n return psutil.pid_exists(self.process.pid)\n except ImportError:\n # Fallback to os method\n try:\n os.kill(self.process.pid, 0)\n return True\n except (OSError, ProcessLookupError):\n return False\n\n return False\n\n def get_status(self) -> Dict[str, Any]:\n \"\"\"\n Get server status information.\n\n Returns:\n Dictionary with status information\n \"\"\"\n status = {\n \"model\": self.model,\n \"port\": self.port,\n \"running\": self.is_running(),\n \"pid\": self.process.pid if self.process else None,\n \"start_time\": self.start_time.isoformat() if self.start_time else None,\n \"log_path\": str(self.log_path) if self.log_path else None,\n }\n\n if self.is_running() and self.start_time:\n uptime = datetime.now() - self.start_time\n status[\"uptime_seconds\"] = uptime.total_seconds()\n status[\"uptime_str\"] = str(uptime).split(\".\")[0]\n\n return status\n\n def wait_for_startup(self) -> bool:\n \"\"\"\n Wait for the server to complete startup.\n\n Monitors the server logs for startup completion indicators and verifies\n via HTTP endpoint. Will wait indefinitely until either startup completes\n or the process terminates.\n\n Returns:\n True if server started successfully, False if process terminated\n \"\"\"\n import time\n\n logger.info(f\"Waiting for {self.model} server to complete startup...\")\n\n # Track if we've seen startup indicators in logs\n log_indicates_ready = False\n\n while True:\n # Check if server is still running\n if not self.is_running():\n logger.error(\n f\"Server process for {self.model} terminated during startup\"\n )\n return False\n\n # Get recent logs to check for startup completion\n recent_logs = self.get_recent_logs(50)\n\n if recent_logs and not log_indicates_ready:\n # Check for startup completion indicators\n for log in recent_logs:\n log_lower = log.lower()\n # Look for the explicit \"Application startup complete\" message\n if \"application startup complete\" in log_lower:\n logger.debug(f\"Server {self.model} startup detected in logs\")\n log_indicates_ready = True\n break\n\n # Also check for other ready indicators as fallback\n if any(\n indicator in log_lower\n for indicator in [\n \"uvicorn running on\",\n \"started server process\",\n \"server is ready\",\n \"api server started\",\n ]\n ):\n logger.debug(\n f\"Server {self.model} startup detected via ready indicator\"\n )\n log_indicates_ready = True\n break\n\n # If logs indicate ready, verify via HTTP\n if log_indicates_ready:\n # Try to verify server is actually ready via HTTP\n port = self.config.get(\"port\")\n if port:\n try:\n import httpx\n\n with httpx.Client() as client:\n # Try /v1/models endpoint first (most reliable)\n response = client.get(\n f\"http://localhost:{port}/v1/models\", timeout=5.0\n )\n if response.status_code == 200:\n logger.info(\n f\"Server {self.model} startup complete \"\n \"(verified via HTTP)\"\n )\n return True\n except httpx.ConnectError:\n # Server not ready yet, continue waiting\n logger.debug(\n f\"Server {self.model} not accepting connections yet\"\n )\n except Exception as e:\n # Log but continue, might be network issue\n logger.debug(f\"HTTP verification failed: {e}\")\n else:\n # No port configured, trust the logs\n logger.info(\n f\"Server {self.model} startup complete (no port for verification)\"\n )\n return True\n\n # Small sleep to avoid busy waiting\n time.sleep(0.5)\n\n def get_recent_logs(self, n: int = 20) -> List[str]:\n \"\"\"\n Get recent log lines from the server output.\n\n Retrieves the most recent log lines from either the in-memory queue\n or the log file on disk. This method ensures logs are available even\n after the monitoring thread has processed them.\n\n Args:\n n: Number of recent lines to return (default: 20)\n\n Returns:\n List of recent log lines, with the most recent last\n \"\"\"\n # Update recent logs from queue\n self._update_recent_logs_from_queue()\n\n # Return from memory if available\n if self._recent_logs:\n return self._recent_logs[-n:]\n\n # Fallback to reading from file\n return self._read_logs_from_file(n)\n\n def _update_recent_logs_from_queue(self) -> None:\n \"\"\"\n Update the recent logs cache from the log queue.\n\n Drains all available log lines from the queue and adds them\n to the recent logs cache, maintaining a maximum of 100 lines.\n \"\"\"\n temp_logs = []\n\n # Get all available logs from queue (don't block)\n while not self.log_queue.empty():\n try:\n log_line = self.log_queue.get_nowait()\n temp_logs.append(log_line)\n except Empty:\n break\n\n if temp_logs:\n self._recent_logs.extend(temp_logs)\n # Keep only the last 100 logs in memory to prevent unbounded growth\n self._recent_logs = self._recent_logs[-100:]\n\n def _read_logs_from_file(self, n: int) -> List[str]:\n \"\"\"\n Read recent log lines from the log file.\n\n Args:\n n: Number of lines to read\n\n Returns:\n List of log lines from file\n \"\"\"\n if not (self.log_path and self.log_path.exists()):\n return []\n\n try:\n with open(self.log_path, \"r\") as f:\n file_logs = f.readlines()\n if file_logs:\n # Get last n lines, strip them\n logs = [line.strip() for line in file_logs[-n:]]\n # Update recent logs cache\n self._recent_logs = logs[-100:]\n return logs\n except Exception as e:\n logger.debug(f\"Error reading log file: {e}\")\n\n return []\n\n def restart(self) -> bool:\n \"\"\"\n Restart the server with the same configuration.\n\n Returns:\n True if restart successful, False otherwise\n \"\"\"\n logger.info(f\"Restarting vLLM server for {self.model}\")\n\n # Stop if running\n if self.is_running():\n self.stop()\n time.sleep(2) # Wait a bit before restarting\n\n # Start again\n return self.start()\n\n def health_check(self) -> bool:\n \"\"\"\n Perform a health check on the server.\n\n Returns:\n True if server is healthy, False otherwise\n \"\"\"\n if not self.is_running():\n return False\n\n try:\n import requests\n\n # Try to connect to the server\n response = requests.get(f\"http://localhost:{self.port}/health\", timeout=5)\n\n return response.status_code == 200\n\n except Exception:\n # If requests fails, just check process\n return self.is_running()", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 27979}, "tests/test_server_manager.py::152": {"resolved_imports": ["src/vllm_cli/server/__init__.py", "src/vllm_cli/server/process.py", "src/vllm_cli/server/manager.py"], "used_names": ["VLLMServer"], "enclosing_function": "test_get_recent_logs", "extracted_code": "# Source: src/vllm_cli/server/manager.py\nclass VLLMServer:\n \"\"\"\n Manages a vLLM server instance with comprehensive lifecycle control.\n\n This class handles the complete lifecycle of a vLLM server including\n configuration, process management, logging, monitoring, and cleanup.\n It supports both programmatically started servers and external server\n detection and management.\n\n Attributes:\n config: Server configuration dictionary\n model: Model name being served\n port: Port number the server is listening on\n process: Subprocess or external process reference\n log_file: File handle for server logs\n log_queue: Thread-safe queue for log lines\n log_thread: Background thread for log monitoring\n start_time: Timestamp when server was started\n log_path: Path to the server's log file\n \"\"\"\n\n def __init__(self, config: Dict[str, Any]) -> None:\n \"\"\"\n Initialize a vLLM server instance.\n\n Sets up the server configuration, logging infrastructure, and\n prepares the instance for server lifecycle management.\n\n Args:\n config: Server configuration dictionary containing model name,\n port, and other vLLM-specific parameters\n \"\"\"\n self.config: Dict[str, Any] = config\n\n # Extract model name - handle both string and dict (LoRA config) formats\n model_config = config.get(\"model\", \"unknown\")\n if isinstance(model_config, dict):\n # LoRA configuration - extract base model name\n self.model: str = model_config.get(\"model\", \"unknown\")\n else:\n # Regular string model name\n self.model: str = model_config\n\n self.port: int = config.get(\"port\", 8000)\n self.process: Optional[Union[subprocess.Popen, Any]] = None\n self.log_file: Optional[TextIO] = None\n self.log_queue: Queue[str] = Queue()\n self.log_thread: Optional[Thread] = None\n self.start_time: Optional[datetime] = None\n self.log_path: Path\n self._recent_logs: List[str] = []\n\n # Setup logging\n log_dir = Path.home() / \".vllm-cli\" / \"logs\"\n log_dir.mkdir(parents=True, exist_ok=True)\n\n timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n self.log_path = log_dir / f\"vllm_{self.model.replace('/', '_')}_{timestamp}.log\"\n\n def start(self) -> bool:\n \"\"\"\n Start the vLLM server.\n\n Returns:\n True if server started successfully, False otherwise\n \"\"\"\n if self.is_running():\n logger.warning(f\"Server already running for {self.model}\")\n return False\n\n try:\n # Build command - run directly without conda wrapper\n full_cmd = self._build_command()\n\n logger.info(f\"Starting vLLM server with command: {' '.join(full_cmd)}\")\n\n # Open log file for writing\n self.log_file = open(self.log_path, \"w\", buffering=1)\n\n # Start with parent environment\n env = os.environ.copy()\n # Note: No longer forcing PYTHONUNBUFFERED=1, let user control it\n\n # Layer 1: Apply universal environment variables from settings\n config_manager = ConfigManager()\n universal_env = config_manager.config.get(\"universal_environment\", {})\n if universal_env:\n logger.info(\n f\"Applying {len(universal_env)} universal environment variable(s)\"\n )\n for key, value in universal_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting universal {key}={value}\")\n else:\n logger.debug(f\"Setting universal {key}=\")\n\n # Layer 2: Apply profile environment variables (override universal)\n profile_env = self.config.get(\"profile_environment\", {})\n if profile_env:\n logger.info(\n f\"Applying {len(profile_env)} profile environment variable(s)\"\n )\n for key, value in profile_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting profile {key}={value}\")\n else:\n logger.debug(f\"Setting profile {key}=\")\n\n # Handle GPU device selection via CUDA_VISIBLE_DEVICES\n # This overrides any CUDA_VISIBLE_DEVICES from the profile\n if self.config.get(\"device\"):\n device_str = str(self.config[\"device\"])\n env[\"CUDA_VISIBLE_DEVICES\"] = device_str\n logger.info(f\"Setting CUDA_VISIBLE_DEVICES={device_str}\")\n\n # If using specific GPUs, adjust tensor parallel size if needed\n device_list = [d.strip() for d in device_str.split(\",\")]\n num_devices = len(device_list)\n\n # Check if tensor_parallel_size is set and compatible\n if self.config.get(\"tensor_parallel_size\"):\n tp_size = self.config[\"tensor_parallel_size\"]\n if tp_size > num_devices:\n logger.warning(\n f\"tensor_parallel_size ({tp_size}) > number of selected devices ({num_devices}). \"\n f\"Adjusting tensor_parallel_size to {num_devices}\"\n )\n self.config[\"tensor_parallel_size\"] = num_devices\n elif num_devices % tp_size != 0:\n logger.warning(\n f\"Number of GPUs ({num_devices}) is not evenly divisible by \"\n f\"tensor_parallel_size ({tp_size}). This may lead to inefficient GPU utilization. \"\n f\"Consider using tensor_parallel_size of: \"\n f\"{', '.join(str(i) for i in range(1, num_devices + 1) if num_devices % i == 0)}\"\n )\n\n # Add HuggingFace token if configured\n config_manager = ConfigManager()\n hf_token = config_manager.config.get(\"hf_token\")\n if hf_token:\n env[\"HF_TOKEN\"] = hf_token\n env[\"HUGGING_FACE_HUB_TOKEN\"] = hf_token # Some tools use this variant\n logger.info(\"HuggingFace token configured for server\")\n\n # Enable development mode for sleep endpoints if sleep mode is enabled\n if self.config.get(\"enable_sleep_mode\"):\n env[\"VLLM_SERVER_DEV_MODE\"] = \"1\"\n logger.info(\"Sleep mode enabled with development endpoints\")\n\n # Start the process with proper pipe configuration\n # Use start_new_session=True to create a new process group\n # This prevents the child process from receiving Ctrl+C signals\n self.process = subprocess.Popen(\n full_cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n text=True,\n bufsize=0, # Unbuffered\n universal_newlines=True,\n env=env,\n start_new_session=True, # Create new process group to isolate from parent signals\n )\n\n # Start log monitoring thread\n self._start_log_monitor()\n\n # Set start time and add to registry\n self.start_time = datetime.now()\n from .process import add_server\n\n add_server(self)\n\n # Return immediately - let the UI monitor the startup\n logger.info(\n f\"vLLM server process launched for {self.model} on port {self.port}\"\n )\n return True\n\n except Exception as e:\n logger.error(f\"Error starting vLLM server: {e}\")\n return False\n\n def _build_command(self) -> List[str]:\n \"\"\"\n Build the vLLM command from configuration using the schema.\n\n Returns:\n List of command arguments\n \"\"\"\n # Use the new ConfigManager to build CLI args\n config_manager = ConfigManager()\n\n # Start with the vllm command\n cmd = [\"vllm\"]\n\n # Add the arguments built from schema\n cli_args = config_manager.build_cli_args(self.config)\n cmd.extend(cli_args)\n\n # Handle extra_args if present (backward compatibility)\n if self.config.get(\"extra_args\"):\n self._add_extra_args_to_command(cmd)\n\n logger.debug(f\"Built command: {' '.join(cmd)}\")\n return cmd\n\n def _add_extra_args_to_command(self, cmd: List[str]) -> None:\n \"\"\"\n Add extra arguments to the vLLM command.\n\n Args:\n cmd: Command list to extend with extra arguments\n \"\"\"\n try:\n extra_args = shlex.split(self.config[\"extra_args\"])\n if extra_args:\n logger.info(f\"Adding extra arguments: {extra_args}\")\n cmd.extend(extra_args)\n except ValueError as e:\n logger.warning(f\"Failed to parse extra_args: {e}\")\n\n def _start_log_monitor(self) -> None:\n \"\"\"\n Start a thread to monitor log output from the vLLM server process.\n\n Creates a daemon thread that continuously reads stdout/stderr from\n the server process, writes to log files, and queues log lines for\n real-time display in the UI.\n \"\"\"\n self.log_thread = Thread(target=self._log_monitor_worker, daemon=True)\n self.log_thread.start()\n\n def _log_monitor_worker(self) -> None:\n \"\"\"\n Worker function for log monitoring thread.\n\n Continuously reads log output from the server process and handles\n file writing and queue management for UI display.\n \"\"\"\n try:\n self.log_queue.put(\"Starting vLLM server process...\")\n\n while self._should_continue_monitoring():\n if self._process_log_line():\n continue\n else:\n # No line read, check if process still running\n if self.process and self.process.poll() is not None:\n break\n time.sleep(0.01) # Small sleep to prevent busy waiting\n\n except Exception as e:\n logger.error(f\"Error in log monitor: {e}\")\n self.log_queue.put(f\"Log monitoring error: {e}\")\n\n def _should_continue_monitoring(self) -> bool:\n \"\"\"\n Check if log monitoring should continue.\n\n Returns:\n True if monitoring should continue, False otherwise\n \"\"\"\n return (\n self.is_running()\n and self.process\n and hasattr(self.process, \"stdout\")\n and self.process.stdout\n )\n\n def _process_log_line(self) -> bool:\n \"\"\"\n Process a single log line from the server output.\n\n Reads one line from the process stdout, writes it to the log file,\n and adds it to the queue for UI display after filtering and formatting.\n\n Returns:\n True if a line was processed, False if no line was available\n \"\"\"\n if not (self.process and self.process.stdout):\n return False\n\n line = self.process.stdout.readline()\n if not line:\n return False\n\n # Write to log file\n self._write_to_log_file(line)\n\n # Process for UI display\n line_stripped = line.strip()\n if line_stripped and self._should_display_log_line(line_stripped):\n # Truncate overly long lines\n if len(line_stripped) > 200:\n line_stripped = line_stripped[:197] + \"...\"\n\n self.log_queue.put(line_stripped)\n logger.debug(f\"Log captured: {line_stripped[:50]}...\")\n\n return True\n\n def _write_to_log_file(self, line: str) -> None:\n \"\"\"\n Write a log line to the log file.\n\n Args:\n line: Log line to write\n \"\"\"\n if self.log_file and not self.log_file.closed:\n self.log_file.write(line)\n self.log_file.flush()\n\n def _should_display_log_line(self, line: str) -> bool:\n \"\"\"\n Determine if a log line should be displayed in the UI.\n\n Filters out certain system messages that are not useful for users.\n\n Args:\n line: Stripped log line to check\n\n Returns:\n True if the line should be displayed, False otherwise\n \"\"\"\n # Filter out conda activation and system messages\n filtered_messages = [\n \"Activated CUDA\",\n \"Using nvcc from:\",\n \"Cuda compilation tools\",\n ]\n return not any(skip in line for skip in filtered_messages)\n\n def stop(self) -> bool:\n \"\"\"\n Stop the vLLM server.\n\n Returns:\n True if server stopped successfully, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n try:\n # Check if this is an external server\n if hasattr(self.process, \"terminate\"):\n # Normal subprocess\n # Since we created a new session, we need to terminate the entire process group\n try:\n # Get the process group ID (pgid)\n # Since we used start_new_session=True, the pgid is the same as the pid\n pgid = self.process.pid\n\n # Send SIGTERM to the entire process group for graceful shutdown\n logger.info(f\"Sending SIGTERM to process group {pgid}\")\n os.killpg(pgid, signal.SIGTERM)\n\n # Wait for process to terminate\n try:\n self.process.wait(timeout=10)\n logger.info(f\"Process group {pgid} terminated gracefully\")\n except subprocess.TimeoutExpired:\n # Force kill if not terminated\n logger.warning(\n f\"Process group {pgid} did not terminate, sending SIGKILL\"\n )\n os.killpg(pgid, signal.SIGKILL)\n self.process.wait()\n logger.info(f\"Process group {pgid} force killed\")\n\n except ProcessLookupError:\n # Process already dead\n logger.info(\"Process already terminated\")\n except PermissionError as e:\n # Fall back to terminating just the process\n logger.warning(\n f\"Permission denied for process group kill: {e}, falling back to process termination\"\n )\n self.process.terminate()\n try:\n self.process.wait(timeout=10)\n except subprocess.TimeoutExpired:\n self.process.kill()\n self.process.wait()\n elif hasattr(self.process, \"pid\"):\n # External server - kill entire process group or individual process\n try:\n pgid = self.process.pid\n killed = False\n\n # First attempt: try to kill process group\n try:\n os.killpg(pgid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process group {pgid}\")\n killed = True\n except (OSError, ProcessLookupError) as e:\n # Process group kill failed, try individual process\n logger.debug(\n f\"Process group kill failed: {e}, trying individual process\"\n )\n try:\n # Ensure pid is an integer (handle Mock objects)\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process {self.process.pid}\")\n killed = True\n except ProcessLookupError:\n # Process already dead\n logger.info(\n f\"Process {self.process.pid} already terminated\"\n )\n except OSError as e:\n logger.warning(\n f\"Failed to send SIGTERM to {self.process.pid}: {e}\"\n )\n\n if killed:\n # Wait for graceful shutdown\n time.sleep(2)\n\n # Check if still running and force kill if needed\n if self.is_running():\n try:\n os.killpg(pgid, signal.SIGKILL)\n logger.info(f\"Force killed process group {pgid}\")\n except (OSError, ProcessLookupError):\n # Process group kill failed, try individual\n try:\n # Ensure pid is an integer (handle Mock objects in tests)\n if hasattr(self.process, \"pid\"):\n try:\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGKILL)\n logger.info(f\"Force killed process {pid}\")\n except (TypeError, ValueError):\n # PID is not a valid integer (might be Mock)\n pass\n except ProcessLookupError:\n pass # Already dead\n except OSError as e:\n logger.error(\n f\"Failed to force kill {self.process.pid}: {e}\"\n )\n\n except Exception as e:\n logger.error(f\"Unexpected error stopping external server: {e}\")\n\n # Close log file if we have one\n if hasattr(self, \"log_file\") and self.log_file:\n self.log_file.close()\n\n # Remove from registry\n from .process import remove_server\n\n remove_server(self)\n\n logger.info(f\"vLLM server stopped for {self.model}\")\n return True\n\n except Exception as e:\n logger.error(f\"Error stopping vLLM server: {e}\")\n return False\n\n def is_running(self) -> bool:\n \"\"\"\n Check if the server is running.\n\n Returns:\n True if server is running, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n # Check if this is an external server (detected, not started by us)\n if hasattr(self.process, \"poll\"):\n # Normal subprocess\n return self.process.poll() is None\n elif hasattr(self.process, \"pid\"):\n # External server - check if PID still exists\n try:\n import psutil\n\n return psutil.pid_exists(self.process.pid)\n except ImportError:\n # Fallback to os method\n try:\n os.kill(self.process.pid, 0)\n return True\n except (OSError, ProcessLookupError):\n return False\n\n return False\n\n def get_status(self) -> Dict[str, Any]:\n \"\"\"\n Get server status information.\n\n Returns:\n Dictionary with status information\n \"\"\"\n status = {\n \"model\": self.model,\n \"port\": self.port,\n \"running\": self.is_running(),\n \"pid\": self.process.pid if self.process else None,\n \"start_time\": self.start_time.isoformat() if self.start_time else None,\n \"log_path\": str(self.log_path) if self.log_path else None,\n }\n\n if self.is_running() and self.start_time:\n uptime = datetime.now() - self.start_time\n status[\"uptime_seconds\"] = uptime.total_seconds()\n status[\"uptime_str\"] = str(uptime).split(\".\")[0]\n\n return status\n\n def wait_for_startup(self) -> bool:\n \"\"\"\n Wait for the server to complete startup.\n\n Monitors the server logs for startup completion indicators and verifies\n via HTTP endpoint. Will wait indefinitely until either startup completes\n or the process terminates.\n\n Returns:\n True if server started successfully, False if process terminated\n \"\"\"\n import time\n\n logger.info(f\"Waiting for {self.model} server to complete startup...\")\n\n # Track if we've seen startup indicators in logs\n log_indicates_ready = False\n\n while True:\n # Check if server is still running\n if not self.is_running():\n logger.error(\n f\"Server process for {self.model} terminated during startup\"\n )\n return False\n\n # Get recent logs to check for startup completion\n recent_logs = self.get_recent_logs(50)\n\n if recent_logs and not log_indicates_ready:\n # Check for startup completion indicators\n for log in recent_logs:\n log_lower = log.lower()\n # Look for the explicit \"Application startup complete\" message\n if \"application startup complete\" in log_lower:\n logger.debug(f\"Server {self.model} startup detected in logs\")\n log_indicates_ready = True\n break\n\n # Also check for other ready indicators as fallback\n if any(\n indicator in log_lower\n for indicator in [\n \"uvicorn running on\",\n \"started server process\",\n \"server is ready\",\n \"api server started\",\n ]\n ):\n logger.debug(\n f\"Server {self.model} startup detected via ready indicator\"\n )\n log_indicates_ready = True\n break\n\n # If logs indicate ready, verify via HTTP\n if log_indicates_ready:\n # Try to verify server is actually ready via HTTP\n port = self.config.get(\"port\")\n if port:\n try:\n import httpx\n\n with httpx.Client() as client:\n # Try /v1/models endpoint first (most reliable)\n response = client.get(\n f\"http://localhost:{port}/v1/models\", timeout=5.0\n )\n if response.status_code == 200:\n logger.info(\n f\"Server {self.model} startup complete \"\n \"(verified via HTTP)\"\n )\n return True\n except httpx.ConnectError:\n # Server not ready yet, continue waiting\n logger.debug(\n f\"Server {self.model} not accepting connections yet\"\n )\n except Exception as e:\n # Log but continue, might be network issue\n logger.debug(f\"HTTP verification failed: {e}\")\n else:\n # No port configured, trust the logs\n logger.info(\n f\"Server {self.model} startup complete (no port for verification)\"\n )\n return True\n\n # Small sleep to avoid busy waiting\n time.sleep(0.5)\n\n def get_recent_logs(self, n: int = 20) -> List[str]:\n \"\"\"\n Get recent log lines from the server output.\n\n Retrieves the most recent log lines from either the in-memory queue\n or the log file on disk. This method ensures logs are available even\n after the monitoring thread has processed them.\n\n Args:\n n: Number of recent lines to return (default: 20)\n\n Returns:\n List of recent log lines, with the most recent last\n \"\"\"\n # Update recent logs from queue\n self._update_recent_logs_from_queue()\n\n # Return from memory if available\n if self._recent_logs:\n return self._recent_logs[-n:]\n\n # Fallback to reading from file\n return self._read_logs_from_file(n)\n\n def _update_recent_logs_from_queue(self) -> None:\n \"\"\"\n Update the recent logs cache from the log queue.\n\n Drains all available log lines from the queue and adds them\n to the recent logs cache, maintaining a maximum of 100 lines.\n \"\"\"\n temp_logs = []\n\n # Get all available logs from queue (don't block)\n while not self.log_queue.empty():\n try:\n log_line = self.log_queue.get_nowait()\n temp_logs.append(log_line)\n except Empty:\n break\n\n if temp_logs:\n self._recent_logs.extend(temp_logs)\n # Keep only the last 100 logs in memory to prevent unbounded growth\n self._recent_logs = self._recent_logs[-100:]\n\n def _read_logs_from_file(self, n: int) -> List[str]:\n \"\"\"\n Read recent log lines from the log file.\n\n Args:\n n: Number of lines to read\n\n Returns:\n List of log lines from file\n \"\"\"\n if not (self.log_path and self.log_path.exists()):\n return []\n\n try:\n with open(self.log_path, \"r\") as f:\n file_logs = f.readlines()\n if file_logs:\n # Get last n lines, strip them\n logs = [line.strip() for line in file_logs[-n:]]\n # Update recent logs cache\n self._recent_logs = logs[-100:]\n return logs\n except Exception as e:\n logger.debug(f\"Error reading log file: {e}\")\n\n return []\n\n def restart(self) -> bool:\n \"\"\"\n Restart the server with the same configuration.\n\n Returns:\n True if restart successful, False otherwise\n \"\"\"\n logger.info(f\"Restarting vLLM server for {self.model}\")\n\n # Stop if running\n if self.is_running():\n self.stop()\n time.sleep(2) # Wait a bit before restarting\n\n # Start again\n return self.start()\n\n def health_check(self) -> bool:\n \"\"\"\n Perform a health check on the server.\n\n Returns:\n True if server is healthy, False otherwise\n \"\"\"\n if not self.is_running():\n return False\n\n try:\n import requests\n\n # Try to connect to the server\n response = requests.get(f\"http://localhost:{self.port}/health\", timeout=5)\n\n return response.status_code == 200\n\n except Exception:\n # If requests fails, just check process\n return self.is_running()", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 27979}, "tests/test_server_manager.py::169": {"resolved_imports": ["src/vllm_cli/server/__init__.py", "src/vllm_cli/server/process.py", "src/vllm_cli/server/manager.py"], "used_names": ["Mock", "VLLMServer", "datetime", "process"], "enclosing_function": "test_get_status", "extracted_code": "# Source: src/vllm_cli/server/__init__.py\n\nThis package provides comprehensive vLLM server management including\nprocess lifecycle, monitoring, discovery, and utilities.\n\nMain Components:\n- VLLMServer: Core server management class\n- Process management: Server registry and lifecycle\n- Discovery: External server detection\n- Monitoring: Health checks and metrics\n- Utils: Port management and cleanup utilities\n\"\"\"\n\n\n\n# Process management functions\nfrom .process import (\n add_server,\n cleanup_servers_on_exit,\n find_server_by_model,\n find_server_by_port,\n get_active_servers,\n remove_server,\n stop_all_servers,\n)\n\n\n\n# Source: src/vllm_cli/server/manager.py\nclass VLLMServer:\n \"\"\"\n Manages a vLLM server instance with comprehensive lifecycle control.\n\n This class handles the complete lifecycle of a vLLM server including\n configuration, process management, logging, monitoring, and cleanup.\n It supports both programmatically started servers and external server\n detection and management.\n\n Attributes:\n config: Server configuration dictionary\n model: Model name being served\n port: Port number the server is listening on\n process: Subprocess or external process reference\n log_file: File handle for server logs\n log_queue: Thread-safe queue for log lines\n log_thread: Background thread for log monitoring\n start_time: Timestamp when server was started\n log_path: Path to the server's log file\n \"\"\"\n\n def __init__(self, config: Dict[str, Any]) -> None:\n \"\"\"\n Initialize a vLLM server instance.\n\n Sets up the server configuration, logging infrastructure, and\n prepares the instance for server lifecycle management.\n\n Args:\n config: Server configuration dictionary containing model name,\n port, and other vLLM-specific parameters\n \"\"\"\n self.config: Dict[str, Any] = config\n\n # Extract model name - handle both string and dict (LoRA config) formats\n model_config = config.get(\"model\", \"unknown\")\n if isinstance(model_config, dict):\n # LoRA configuration - extract base model name\n self.model: str = model_config.get(\"model\", \"unknown\")\n else:\n # Regular string model name\n self.model: str = model_config\n\n self.port: int = config.get(\"port\", 8000)\n self.process: Optional[Union[subprocess.Popen, Any]] = None\n self.log_file: Optional[TextIO] = None\n self.log_queue: Queue[str] = Queue()\n self.log_thread: Optional[Thread] = None\n self.start_time: Optional[datetime] = None\n self.log_path: Path\n self._recent_logs: List[str] = []\n\n # Setup logging\n log_dir = Path.home() / \".vllm-cli\" / \"logs\"\n log_dir.mkdir(parents=True, exist_ok=True)\n\n timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n self.log_path = log_dir / f\"vllm_{self.model.replace('/', '_')}_{timestamp}.log\"\n\n def start(self) -> bool:\n \"\"\"\n Start the vLLM server.\n\n Returns:\n True if server started successfully, False otherwise\n \"\"\"\n if self.is_running():\n logger.warning(f\"Server already running for {self.model}\")\n return False\n\n try:\n # Build command - run directly without conda wrapper\n full_cmd = self._build_command()\n\n logger.info(f\"Starting vLLM server with command: {' '.join(full_cmd)}\")\n\n # Open log file for writing\n self.log_file = open(self.log_path, \"w\", buffering=1)\n\n # Start with parent environment\n env = os.environ.copy()\n # Note: No longer forcing PYTHONUNBUFFERED=1, let user control it\n\n # Layer 1: Apply universal environment variables from settings\n config_manager = ConfigManager()\n universal_env = config_manager.config.get(\"universal_environment\", {})\n if universal_env:\n logger.info(\n f\"Applying {len(universal_env)} universal environment variable(s)\"\n )\n for key, value in universal_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting universal {key}={value}\")\n else:\n logger.debug(f\"Setting universal {key}=\")\n\n # Layer 2: Apply profile environment variables (override universal)\n profile_env = self.config.get(\"profile_environment\", {})\n if profile_env:\n logger.info(\n f\"Applying {len(profile_env)} profile environment variable(s)\"\n )\n for key, value in profile_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting profile {key}={value}\")\n else:\n logger.debug(f\"Setting profile {key}=\")\n\n # Handle GPU device selection via CUDA_VISIBLE_DEVICES\n # This overrides any CUDA_VISIBLE_DEVICES from the profile\n if self.config.get(\"device\"):\n device_str = str(self.config[\"device\"])\n env[\"CUDA_VISIBLE_DEVICES\"] = device_str\n logger.info(f\"Setting CUDA_VISIBLE_DEVICES={device_str}\")\n\n # If using specific GPUs, adjust tensor parallel size if needed\n device_list = [d.strip() for d in device_str.split(\",\")]\n num_devices = len(device_list)\n\n # Check if tensor_parallel_size is set and compatible\n if self.config.get(\"tensor_parallel_size\"):\n tp_size = self.config[\"tensor_parallel_size\"]\n if tp_size > num_devices:\n logger.warning(\n f\"tensor_parallel_size ({tp_size}) > number of selected devices ({num_devices}). \"\n f\"Adjusting tensor_parallel_size to {num_devices}\"\n )\n self.config[\"tensor_parallel_size\"] = num_devices\n elif num_devices % tp_size != 0:\n logger.warning(\n f\"Number of GPUs ({num_devices}) is not evenly divisible by \"\n f\"tensor_parallel_size ({tp_size}). This may lead to inefficient GPU utilization. \"\n f\"Consider using tensor_parallel_size of: \"\n f\"{', '.join(str(i) for i in range(1, num_devices + 1) if num_devices % i == 0)}\"\n )\n\n # Add HuggingFace token if configured\n config_manager = ConfigManager()\n hf_token = config_manager.config.get(\"hf_token\")\n if hf_token:\n env[\"HF_TOKEN\"] = hf_token\n env[\"HUGGING_FACE_HUB_TOKEN\"] = hf_token # Some tools use this variant\n logger.info(\"HuggingFace token configured for server\")\n\n # Enable development mode for sleep endpoints if sleep mode is enabled\n if self.config.get(\"enable_sleep_mode\"):\n env[\"VLLM_SERVER_DEV_MODE\"] = \"1\"\n logger.info(\"Sleep mode enabled with development endpoints\")\n\n # Start the process with proper pipe configuration\n # Use start_new_session=True to create a new process group\n # This prevents the child process from receiving Ctrl+C signals\n self.process = subprocess.Popen(\n full_cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n text=True,\n bufsize=0, # Unbuffered\n universal_newlines=True,\n env=env,\n start_new_session=True, # Create new process group to isolate from parent signals\n )\n\n # Start log monitoring thread\n self._start_log_monitor()\n\n # Set start time and add to registry\n self.start_time = datetime.now()\n from .process import add_server\n\n add_server(self)\n\n # Return immediately - let the UI monitor the startup\n logger.info(\n f\"vLLM server process launched for {self.model} on port {self.port}\"\n )\n return True\n\n except Exception as e:\n logger.error(f\"Error starting vLLM server: {e}\")\n return False\n\n def _build_command(self) -> List[str]:\n \"\"\"\n Build the vLLM command from configuration using the schema.\n\n Returns:\n List of command arguments\n \"\"\"\n # Use the new ConfigManager to build CLI args\n config_manager = ConfigManager()\n\n # Start with the vllm command\n cmd = [\"vllm\"]\n\n # Add the arguments built from schema\n cli_args = config_manager.build_cli_args(self.config)\n cmd.extend(cli_args)\n\n # Handle extra_args if present (backward compatibility)\n if self.config.get(\"extra_args\"):\n self._add_extra_args_to_command(cmd)\n\n logger.debug(f\"Built command: {' '.join(cmd)}\")\n return cmd\n\n def _add_extra_args_to_command(self, cmd: List[str]) -> None:\n \"\"\"\n Add extra arguments to the vLLM command.\n\n Args:\n cmd: Command list to extend with extra arguments\n \"\"\"\n try:\n extra_args = shlex.split(self.config[\"extra_args\"])\n if extra_args:\n logger.info(f\"Adding extra arguments: {extra_args}\")\n cmd.extend(extra_args)\n except ValueError as e:\n logger.warning(f\"Failed to parse extra_args: {e}\")\n\n def _start_log_monitor(self) -> None:\n \"\"\"\n Start a thread to monitor log output from the vLLM server process.\n\n Creates a daemon thread that continuously reads stdout/stderr from\n the server process, writes to log files, and queues log lines for\n real-time display in the UI.\n \"\"\"\n self.log_thread = Thread(target=self._log_monitor_worker, daemon=True)\n self.log_thread.start()\n\n def _log_monitor_worker(self) -> None:\n \"\"\"\n Worker function for log monitoring thread.\n\n Continuously reads log output from the server process and handles\n file writing and queue management for UI display.\n \"\"\"\n try:\n self.log_queue.put(\"Starting vLLM server process...\")\n\n while self._should_continue_monitoring():\n if self._process_log_line():\n continue\n else:\n # No line read, check if process still running\n if self.process and self.process.poll() is not None:\n break\n time.sleep(0.01) # Small sleep to prevent busy waiting\n\n except Exception as e:\n logger.error(f\"Error in log monitor: {e}\")\n self.log_queue.put(f\"Log monitoring error: {e}\")\n\n def _should_continue_monitoring(self) -> bool:\n \"\"\"\n Check if log monitoring should continue.\n\n Returns:\n True if monitoring should continue, False otherwise\n \"\"\"\n return (\n self.is_running()\n and self.process\n and hasattr(self.process, \"stdout\")\n and self.process.stdout\n )\n\n def _process_log_line(self) -> bool:\n \"\"\"\n Process a single log line from the server output.\n\n Reads one line from the process stdout, writes it to the log file,\n and adds it to the queue for UI display after filtering and formatting.\n\n Returns:\n True if a line was processed, False if no line was available\n \"\"\"\n if not (self.process and self.process.stdout):\n return False\n\n line = self.process.stdout.readline()\n if not line:\n return False\n\n # Write to log file\n self._write_to_log_file(line)\n\n # Process for UI display\n line_stripped = line.strip()\n if line_stripped and self._should_display_log_line(line_stripped):\n # Truncate overly long lines\n if len(line_stripped) > 200:\n line_stripped = line_stripped[:197] + \"...\"\n\n self.log_queue.put(line_stripped)\n logger.debug(f\"Log captured: {line_stripped[:50]}...\")\n\n return True\n\n def _write_to_log_file(self, line: str) -> None:\n \"\"\"\n Write a log line to the log file.\n\n Args:\n line: Log line to write\n \"\"\"\n if self.log_file and not self.log_file.closed:\n self.log_file.write(line)\n self.log_file.flush()\n\n def _should_display_log_line(self, line: str) -> bool:\n \"\"\"\n Determine if a log line should be displayed in the UI.\n\n Filters out certain system messages that are not useful for users.\n\n Args:\n line: Stripped log line to check\n\n Returns:\n True if the line should be displayed, False otherwise\n \"\"\"\n # Filter out conda activation and system messages\n filtered_messages = [\n \"Activated CUDA\",\n \"Using nvcc from:\",\n \"Cuda compilation tools\",\n ]\n return not any(skip in line for skip in filtered_messages)\n\n def stop(self) -> bool:\n \"\"\"\n Stop the vLLM server.\n\n Returns:\n True if server stopped successfully, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n try:\n # Check if this is an external server\n if hasattr(self.process, \"terminate\"):\n # Normal subprocess\n # Since we created a new session, we need to terminate the entire process group\n try:\n # Get the process group ID (pgid)\n # Since we used start_new_session=True, the pgid is the same as the pid\n pgid = self.process.pid\n\n # Send SIGTERM to the entire process group for graceful shutdown\n logger.info(f\"Sending SIGTERM to process group {pgid}\")\n os.killpg(pgid, signal.SIGTERM)\n\n # Wait for process to terminate\n try:\n self.process.wait(timeout=10)\n logger.info(f\"Process group {pgid} terminated gracefully\")\n except subprocess.TimeoutExpired:\n # Force kill if not terminated\n logger.warning(\n f\"Process group {pgid} did not terminate, sending SIGKILL\"\n )\n os.killpg(pgid, signal.SIGKILL)\n self.process.wait()\n logger.info(f\"Process group {pgid} force killed\")\n\n except ProcessLookupError:\n # Process already dead\n logger.info(\"Process already terminated\")\n except PermissionError as e:\n # Fall back to terminating just the process\n logger.warning(\n f\"Permission denied for process group kill: {e}, falling back to process termination\"\n )\n self.process.terminate()\n try:\n self.process.wait(timeout=10)\n except subprocess.TimeoutExpired:\n self.process.kill()\n self.process.wait()\n elif hasattr(self.process, \"pid\"):\n # External server - kill entire process group or individual process\n try:\n pgid = self.process.pid\n killed = False\n\n # First attempt: try to kill process group\n try:\n os.killpg(pgid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process group {pgid}\")\n killed = True\n except (OSError, ProcessLookupError) as e:\n # Process group kill failed, try individual process\n logger.debug(\n f\"Process group kill failed: {e}, trying individual process\"\n )\n try:\n # Ensure pid is an integer (handle Mock objects)\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process {self.process.pid}\")\n killed = True\n except ProcessLookupError:\n # Process already dead\n logger.info(\n f\"Process {self.process.pid} already terminated\"\n )\n except OSError as e:\n logger.warning(\n f\"Failed to send SIGTERM to {self.process.pid}: {e}\"\n )\n\n if killed:\n # Wait for graceful shutdown\n time.sleep(2)\n\n # Check if still running and force kill if needed\n if self.is_running():\n try:\n os.killpg(pgid, signal.SIGKILL)\n logger.info(f\"Force killed process group {pgid}\")\n except (OSError, ProcessLookupError):\n # Process group kill failed, try individual\n try:\n # Ensure pid is an integer (handle Mock objects in tests)\n if hasattr(self.process, \"pid\"):\n try:\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGKILL)\n logger.info(f\"Force killed process {pid}\")\n except (TypeError, ValueError):\n # PID is not a valid integer (might be Mock)\n pass\n except ProcessLookupError:\n pass # Already dead\n except OSError as e:\n logger.error(\n f\"Failed to force kill {self.process.pid}: {e}\"\n )\n\n except Exception as e:\n logger.error(f\"Unexpected error stopping external server: {e}\")\n\n # Close log file if we have one\n if hasattr(self, \"log_file\") and self.log_file:\n self.log_file.close()\n\n # Remove from registry\n from .process import remove_server\n\n remove_server(self)\n\n logger.info(f\"vLLM server stopped for {self.model}\")\n return True\n\n except Exception as e:\n logger.error(f\"Error stopping vLLM server: {e}\")\n return False\n\n def is_running(self) -> bool:\n \"\"\"\n Check if the server is running.\n\n Returns:\n True if server is running, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n # Check if this is an external server (detected, not started by us)\n if hasattr(self.process, \"poll\"):\n # Normal subprocess\n return self.process.poll() is None\n elif hasattr(self.process, \"pid\"):\n # External server - check if PID still exists\n try:\n import psutil\n\n return psutil.pid_exists(self.process.pid)\n except ImportError:\n # Fallback to os method\n try:\n os.kill(self.process.pid, 0)\n return True\n except (OSError, ProcessLookupError):\n return False\n\n return False\n\n def get_status(self) -> Dict[str, Any]:\n \"\"\"\n Get server status information.\n\n Returns:\n Dictionary with status information\n \"\"\"\n status = {\n \"model\": self.model,\n \"port\": self.port,\n \"running\": self.is_running(),\n \"pid\": self.process.pid if self.process else None,\n \"start_time\": self.start_time.isoformat() if self.start_time else None,\n \"log_path\": str(self.log_path) if self.log_path else None,\n }\n\n if self.is_running() and self.start_time:\n uptime = datetime.now() - self.start_time\n status[\"uptime_seconds\"] = uptime.total_seconds()\n status[\"uptime_str\"] = str(uptime).split(\".\")[0]\n\n return status\n\n def wait_for_startup(self) -> bool:\n \"\"\"\n Wait for the server to complete startup.\n\n Monitors the server logs for startup completion indicators and verifies\n via HTTP endpoint. Will wait indefinitely until either startup completes\n or the process terminates.\n\n Returns:\n True if server started successfully, False if process terminated\n \"\"\"\n import time\n\n logger.info(f\"Waiting for {self.model} server to complete startup...\")\n\n # Track if we've seen startup indicators in logs\n log_indicates_ready = False\n\n while True:\n # Check if server is still running\n if not self.is_running():\n logger.error(\n f\"Server process for {self.model} terminated during startup\"\n )\n return False\n\n # Get recent logs to check for startup completion\n recent_logs = self.get_recent_logs(50)\n\n if recent_logs and not log_indicates_ready:\n # Check for startup completion indicators\n for log in recent_logs:\n log_lower = log.lower()\n # Look for the explicit \"Application startup complete\" message\n if \"application startup complete\" in log_lower:\n logger.debug(f\"Server {self.model} startup detected in logs\")\n log_indicates_ready = True\n break\n\n # Also check for other ready indicators as fallback\n if any(\n indicator in log_lower\n for indicator in [\n \"uvicorn running on\",\n \"started server process\",\n \"server is ready\",\n \"api server started\",\n ]\n ):\n logger.debug(\n f\"Server {self.model} startup detected via ready indicator\"\n )\n log_indicates_ready = True\n break\n\n # If logs indicate ready, verify via HTTP\n if log_indicates_ready:\n # Try to verify server is actually ready via HTTP\n port = self.config.get(\"port\")\n if port:\n try:\n import httpx\n\n with httpx.Client() as client:\n # Try /v1/models endpoint first (most reliable)\n response = client.get(\n f\"http://localhost:{port}/v1/models\", timeout=5.0\n )\n if response.status_code == 200:\n logger.info(\n f\"Server {self.model} startup complete \"\n \"(verified via HTTP)\"\n )\n return True\n except httpx.ConnectError:\n # Server not ready yet, continue waiting\n logger.debug(\n f\"Server {self.model} not accepting connections yet\"\n )\n except Exception as e:\n # Log but continue, might be network issue\n logger.debug(f\"HTTP verification failed: {e}\")\n else:\n # No port configured, trust the logs\n logger.info(\n f\"Server {self.model} startup complete (no port for verification)\"\n )\n return True\n\n # Small sleep to avoid busy waiting\n time.sleep(0.5)\n\n def get_recent_logs(self, n: int = 20) -> List[str]:\n \"\"\"\n Get recent log lines from the server output.\n\n Retrieves the most recent log lines from either the in-memory queue\n or the log file on disk. This method ensures logs are available even\n after the monitoring thread has processed them.\n\n Args:\n n: Number of recent lines to return (default: 20)\n\n Returns:\n List of recent log lines, with the most recent last\n \"\"\"\n # Update recent logs from queue\n self._update_recent_logs_from_queue()\n\n # Return from memory if available\n if self._recent_logs:\n return self._recent_logs[-n:]\n\n # Fallback to reading from file\n return self._read_logs_from_file(n)\n\n def _update_recent_logs_from_queue(self) -> None:\n \"\"\"\n Update the recent logs cache from the log queue.\n\n Drains all available log lines from the queue and adds them\n to the recent logs cache, maintaining a maximum of 100 lines.\n \"\"\"\n temp_logs = []\n\n # Get all available logs from queue (don't block)\n while not self.log_queue.empty():\n try:\n log_line = self.log_queue.get_nowait()\n temp_logs.append(log_line)\n except Empty:\n break\n\n if temp_logs:\n self._recent_logs.extend(temp_logs)\n # Keep only the last 100 logs in memory to prevent unbounded growth\n self._recent_logs = self._recent_logs[-100:]\n\n def _read_logs_from_file(self, n: int) -> List[str]:\n \"\"\"\n Read recent log lines from the log file.\n\n Args:\n n: Number of lines to read\n\n Returns:\n List of log lines from file\n \"\"\"\n if not (self.log_path and self.log_path.exists()):\n return []\n\n try:\n with open(self.log_path, \"r\") as f:\n file_logs = f.readlines()\n if file_logs:\n # Get last n lines, strip them\n logs = [line.strip() for line in file_logs[-n:]]\n # Update recent logs cache\n self._recent_logs = logs[-100:]\n return logs\n except Exception as e:\n logger.debug(f\"Error reading log file: {e}\")\n\n return []\n\n def restart(self) -> bool:\n \"\"\"\n Restart the server with the same configuration.\n\n Returns:\n True if restart successful, False otherwise\n \"\"\"\n logger.info(f\"Restarting vLLM server for {self.model}\")\n\n # Stop if running\n if self.is_running():\n self.stop()\n time.sleep(2) # Wait a bit before restarting\n\n # Start again\n return self.start()\n\n def health_check(self) -> bool:\n \"\"\"\n Perform a health check on the server.\n\n Returns:\n True if server is healthy, False otherwise\n \"\"\"\n if not self.is_running():\n return False\n\n try:\n import requests\n\n # Try to connect to the server\n response = requests.get(f\"http://localhost:{self.port}/health\", timeout=5)\n\n return response.status_code == 200\n\n except Exception:\n # If requests fails, just check process\n return self.is_running()", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 28614}, "tests/proxy/test_router.py::27": {"resolved_imports": ["src/vllm_cli/proxy/router.py"], "used_names": [], "enclosing_function": "test_add_backend", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_config_manager.py::153": {"resolved_imports": ["src/vllm_cli/config/manager.py"], "used_names": ["ConfigManager", "Mock", "patch"], "enclosing_function": "test_validate_config_valid", "extracted_code": "# Source: src/vllm_cli/config/manager.py\nclass ConfigManager:\n \"\"\"\n Enhanced configuration manager with comprehensive validation support.\n\n This class manages configuration files, profiles, and validation using\n the new validation framework. It provides a clean API for configuration\n operations while ensuring data integrity through comprehensive validation.\n\n Attributes:\n config_dir: Directory for configuration files\n validation_registry: Registry of validation rules\n compatibility_validator: Validator for parameter combinations\n \"\"\"\n\n def __init__(self):\n # Paths for configuration files\n self.config_dir = Path.home() / \".config\" / \"vllm-cli\"\n self.config_file = self.config_dir / \"config.yaml\"\n\n # Ensure config directory exists\n self.config_dir.mkdir(parents=True, exist_ok=True)\n\n # Initialize sub-managers\n self.schema_manager = SchemaManager()\n self.profile_manager = ProfileManager(self.config_dir)\n self.persistence_manager = PersistenceManager()\n self.shortcut_manager = ShortcutManager(self.config_dir)\n\n # Initialize validation system\n self.validation_registry = create_vllm_validation_registry()\n self.compatibility_validator = create_compatibility_validator(\n self.validation_registry\n )\n\n # Load main configuration\n self.config = self._load_config()\n\n def _load_config(self) -> Dict[str, Any]:\n \"\"\"Load main configuration file (legacy YAML support).\"\"\"\n return self.persistence_manager.load_yaml_file(self.config_file)\n\n def _save_config(self) -> None:\n \"\"\"Save main configuration file.\"\"\"\n self.persistence_manager.save_yaml_file(self.config_file, self.config)\n\n def get_argument_info(self, arg_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get detailed information about a specific argument.\"\"\"\n return self.schema_manager.get_argument_info(arg_name)\n\n def get_arguments_by_category(self, category: str) -> List[Dict[str, Any]]:\n \"\"\"Get all arguments belonging to a specific category.\"\"\"\n return self.schema_manager.get_arguments_by_category(category)\n\n def get_category_info(self, category: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get information about a specific category.\"\"\"\n return self.schema_manager.get_category_info(category)\n\n def get_ordered_categories(self) -> List[Tuple[str, Dict[str, Any]]]:\n \"\"\"Get categories ordered by their display order.\"\"\"\n return self.schema_manager.get_ordered_categories()\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n return self.profile_manager.get_all_profiles()\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name with dynamic defaults applied.\"\"\"\n profile = self.profile_manager.get_profile(name)\n if profile and \"config\" in profile:\n # Apply dynamic defaults to the profile configuration\n profile[\"config\"] = self.profile_manager.apply_dynamic_defaults(\n profile[\"config\"]\n )\n return profile\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"Save or update a user profile with validation.\"\"\"\n # Validate profile configuration if present\n if \"config\" in profile:\n is_valid, errors = self.validate_config(profile[\"config\"])\n if not is_valid:\n from ..errors import ProfileError\n\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n return self.profile_manager.save_user_profile(name, profile)\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n return self.profile_manager.delete_user_profile(name)\n\n @property\n def default_profiles(self) -> Dict[str, Any]:\n \"\"\"Get default profiles.\"\"\"\n return self.profile_manager.default_profiles\n\n @property\n def user_profiles(self) -> Dict[str, Any]:\n \"\"\"Get user profiles.\"\"\"\n return self.profile_manager.user_profiles\n\n def validate_config(self, config: Dict[str, Any]) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate a configuration using the new validation framework.\n\n This method uses the comprehensive validation system to check\n configuration values, types, ranges, and dependencies.\n\n Args:\n config: Configuration dictionary to validate\n\n Returns:\n Tuple of (is_valid, list_of_error_messages)\n\n Raises:\n ConfigurationError: If validation system fails\n \"\"\"\n try:\n # Use new validation system\n result = self.validation_registry.validate_config(config)\n\n # Convert validation errors to string messages for backward compatibility\n error_messages = result.get_error_messages()\n\n # Add warnings if any\n if result.warnings:\n for warning in result.warnings:\n logger.warning(f\"Configuration warning: {warning}\")\n\n return result.is_valid(), error_messages\n\n except Exception as e:\n logger.error(f\"Error during configuration validation: {e}\")\n raise ConfigurationError(\n f\"Validation system error: {e}\", error_code=\"VALIDATION_SYSTEM_ERROR\"\n ) from e\n\n def validate_argument_combination(\n self, config: Dict[str, Any]\n ) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate that argument combinations are compatible using the new compatibility validator.\n\n Args:\n config: Configuration dictionary to check for compatibility\n\n Returns:\n Tuple of (is_valid, list_of_warnings_or_errors)\n \"\"\"\n try:\n issues = self.compatibility_validator.validate_compatibility(config)\n\n warnings = []\n errors = []\n\n for issue in issues:\n message = issue[\"message\"]\n if issue[\"severity\"] == \"error\":\n errors.append(message)\n else:\n warnings.append(message)\n\n # Log warnings\n for warning in warnings:\n logger.warning(f\"Configuration compatibility warning: {warning}\")\n\n # Return all issues as warnings for backward compatibility\n # (errors are treated as warnings in the legacy interface)\n all_issues = errors + warnings\n\n return len(errors) == 0, all_issues\n\n except Exception as e:\n logger.error(f\"Error during compatibility validation: {e}\")\n return False, [f\"Compatibility validation error: {e}\"]\n\n def build_cli_args(self, config: Dict[str, Any]) -> List[str]:\n \"\"\"\n Build command-line arguments from a configuration dictionary.\n\n Only includes arguments that are explicitly set in the config.\n Handles special cases like LoRA modules.\n \"\"\"\n args = []\n\n # Special handling for model (positional argument)\n # Check if this is a GGUF/Ollama configuration\n if (\n isinstance(config.get(\"model\"), dict)\n and \"quantization\" in config[\"model\"]\n and config[\"model\"][\"quantization\"] == \"gguf\"\n ):\n # Extract GGUF model config\n gguf_config = config[\"model\"]\n model_path = gguf_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", model_path])\n\n # Set quantization to gguf\n config[\"quantization\"] = \"gguf\"\n\n # Add served-model-name if provided (for Ollama models)\n if \"served_model_name\" in gguf_config:\n config[\"served_model_name\"] = gguf_config[\"served_model_name\"]\n logger.info(\n f\"Configuring GGUF model: {model_path} as {gguf_config['served_model_name']}\"\n )\n else:\n logger.info(f\"Configuring GGUF model: {model_path}\")\n\n # Check if this is a LoRA configuration\n elif (\n isinstance(config.get(\"model\"), dict) and \"lora_modules\" in config[\"model\"]\n ):\n # Extract base model and LoRA config\n lora_config = config[\"model\"]\n base_model = lora_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", base_model])\n\n # Enable LoRA support when modules are present\n args.append(\"--enable-lora\")\n\n # Track maximum rank for all LoRA modules\n max_rank = 16 # Default minimum\n\n # Add LoRA modules\n for lora in lora_config.get(\"lora_modules\", []):\n lora_path = lora.get(\"path\", \"\")\n if lora_path:\n # vLLM expects --lora-modules with name=path format\n lora_name = lora.get(\"name\", \"adapter\")\n args.extend([\"--lora-modules\", f\"{lora_name}={lora_path}\"])\n\n # Track maximum rank\n lora_rank = lora.get(\"rank\", 16)\n max_rank = max(max_rank, lora_rank)\n\n # Add max-lora-rank parameter\n args.extend([\"--max-lora-rank\", str(max_rank)])\n\n elif \"model\" in config:\n args.extend([\"serve\", config[\"model\"]])\n\n # Handle lora_modules if present as a string (from CLI)\n if \"lora_modules\" in config and config[\"lora_modules\"]:\n # Enable LoRA support\n if \"--enable-lora\" not in args:\n args.append(\"--enable-lora\")\n\n # Parse and add LoRA modules\n lora_modules_str = config[\"lora_modules\"]\n if isinstance(lora_modules_str, str):\n # Split by space and add each module\n for module in lora_modules_str.split():\n args.extend([\"--lora-modules\", module])\n\n # Add max-lora-rank if not already added\n # Use a safe default of 64 which should cover most LoRA adapters\n if \"--max-lora-rank\" not in args:\n # Check if max_lora_rank is explicitly set in config\n if \"max_lora_rank\" not in config:\n args.extend([\"--max-lora-rank\", \"64\"])\n\n for arg_name, value in config.items():\n # Skip special keys and None values\n if (\n arg_name in [\"model\", \"name\", \"description\", \"icon\", \"lora_modules\"]\n or value is None\n ):\n continue\n\n arg_info = self.schema_manager.get_argument_info(arg_name)\n if not arg_info:\n logger.warning(f\"Unknown argument in config: {arg_name}\")\n continue\n\n cli_flag = arg_info.get(\"cli_flag\")\n if not cli_flag:\n continue\n\n arg_type = arg_info.get(\"type\")\n\n if arg_type == \"boolean\":\n if value: # Only add flag if True\n args.append(cli_flag)\n elif arg_type in [\"integer\", \"float\", \"string\", \"choice\"]:\n args.extend([cli_flag, str(value)])\n else:\n logger.warning(f\"Unknown argument type for {arg_name}: {arg_type}\")\n\n return args\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n return self.profile_manager.export_profile(profile_name, filepath)\n\n def import_profile(self, filepath: Path, new_name: Optional[str] = None) -> bool:\n \"\"\"Import a profile from a JSON file with comprehensive validation.\"\"\"\n return self.profile_manager.import_profile(\n filepath, new_name, self.validate_config\n )\n\n def get_last_config(self) -> Optional[Dict[str, Any]]:\n \"\"\"Get the last used server configuration.\"\"\"\n return self.config.get(\"last_config\")\n\n def save_last_config(self, config: Dict[str, Any]) -> None:\n \"\"\"Save the last used server configuration.\"\"\"\n self.config[\"last_config\"] = config\n self._save_config()\n\n def get_recent_models(self, limit: int = 5) -> List[str]:\n \"\"\"Get recently used models.\"\"\"\n return self.config.get(\"recent_models\", [])[:limit]\n\n def add_recent_model(self, model: str) -> None:\n \"\"\"Add a model to recent models list.\"\"\"\n recent = self.config.get(\"recent_models\", [])\n if model in recent:\n recent.remove(model)\n recent.insert(0, model)\n self.config[\"recent_models\"] = recent[:10] # Keep only last 10\n self._save_config()\n\n def clear_cache(self) -> None:\n \"\"\"Clear cached data.\"\"\"\n cache_file = self.config_dir / \"cache.json\"\n if cache_file.exists():\n cache_file.unlink()\n self.config.pop(\"last_config\", None)\n self.config.pop(\"recent_models\", None)\n self._save_config()\n logger.info(\"Cache cleared\")\n\n def get_server_defaults(self) -> Dict[str, Any]:\n \"\"\"Get default server settings.\"\"\"\n return self.config.get(\n \"server_defaults\",\n {\n \"default_port\": 8000,\n \"auto_restart\": False,\n \"log_level\": \"info\",\n \"cleanup_on_exit\": True, # Default to cleaning up servers on exit\n },\n )\n\n def save_server_defaults(self, defaults: Dict[str, Any]) -> None:\n \"\"\"Save default server settings.\"\"\"\n self.config[\"server_defaults\"] = defaults\n self._save_config()\n\n def get_ui_preferences(self) -> Dict[str, Any]:\n \"\"\"Get UI preferences including progress bar style and log display settings.\"\"\"\n return self.config.get(\n \"ui_preferences\",\n {\n \"progress_bar_style\": \"blocks\", # Default style\n \"show_gpu_in_monitor\": True,\n \"log_lines_startup\": 50, # Number of log lines to show during startup\n \"log_lines_monitor\": 50, # Number of log lines to show in server monitor\n \"startup_refresh_rate\": 4.0, # Hz for startup log refresh\n \"monitor_refresh_rate\": 1.0, # Hz for monitor log refresh\n },\n )\n\n def save_ui_preferences(self, preferences: Dict[str, Any]) -> None:\n \"\"\"Save UI preferences.\"\"\"\n self.config[\"ui_preferences\"] = preferences\n self._save_config()\n\n # Shortcut management methods\n def get_all_shortcuts(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all shortcuts.\"\"\"\n return self.shortcut_manager.get_all_shortcuts()\n\n def get_shortcut(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific shortcut by name.\"\"\"\n return self.shortcut_manager.get_shortcut(name)\n\n def save_shortcut(self, name: str, shortcut_data: Dict[str, Any]) -> bool:\n \"\"\"Save or update a shortcut.\"\"\"\n return self.shortcut_manager.save_shortcut(name, shortcut_data)\n\n def delete_shortcut(self, name: str) -> bool:\n \"\"\"Delete a shortcut.\"\"\"\n return self.shortcut_manager.delete_shortcut(name)\n\n def list_shortcuts(self) -> List[Dict[str, Any]]:\n \"\"\"List all shortcuts with summary information.\"\"\"\n return self.shortcut_manager.list_shortcuts()\n\n def get_recent_shortcuts(self, limit: int = 5) -> List[Dict[str, Any]]:\n \"\"\"Get recently used shortcuts.\"\"\"\n return self.shortcut_manager.get_recent_shortcuts(limit)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 15704}, "tests/test_profiles.py::72": {"resolved_imports": ["src/vllm_cli/config/profiles.py"], "used_names": ["ProfileManager"], "enclosing_function": "test_save_user_profile", "extracted_code": "# Source: src/vllm_cli/config/profiles.py\nclass ProfileManager:\n \"\"\"\n Manages user profiles for vLLM configurations.\n\n Handles creation, retrieval, updating, and deletion of user profiles\n with validation and persistence.\n \"\"\"\n\n def __init__(self, config_dir: Path):\n self.config_dir = config_dir\n self.user_profiles_file = config_dir / \"user_profiles.json\"\n\n # Paths for schema files (packaged with application)\n schema_dir = Path(__file__).parent.parent / \"schemas\"\n self.default_profiles_file = schema_dir / \"default_profiles.json\"\n\n # Load profiles\n self.default_profiles = self._load_default_profiles()\n self.user_profiles = self._load_user_profiles()\n\n def _load_json_file(self, filepath: Path) -> Dict[str, Any]:\n \"\"\"Load a JSON file safely.\"\"\"\n if filepath.exists():\n try:\n with open(filepath, \"r\") as f:\n return json.load(f)\n except Exception as e:\n logger.error(f\"Error loading {filepath}: {e}\")\n return {}\n\n def _save_json_file(self, filepath: Path, data: Dict[str, Any]) -> bool:\n \"\"\"Save data to a JSON file.\"\"\"\n try:\n with open(filepath, \"w\") as f:\n json.dump(data, f, indent=2)\n return True\n except Exception as e:\n logger.error(f\"Error saving {filepath}: {e}\")\n return False\n\n def _load_default_profiles(self) -> Dict[str, Any]:\n \"\"\"Load default built-in profiles.\"\"\"\n profiles = self._load_json_file(self.default_profiles_file)\n return profiles.get(\"profiles\", {})\n\n def _load_user_profiles(self) -> Dict[str, Any]:\n \"\"\"Load user-created custom profiles.\"\"\"\n return self._load_json_file(self.user_profiles_file)\n\n def _save_user_profiles(self) -> bool:\n \"\"\"Save user profiles to file.\"\"\"\n return self._save_json_file(self.user_profiles_file, self.user_profiles)\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n all_profiles = deepcopy(self.default_profiles)\n all_profiles.update(self.user_profiles)\n return all_profiles\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name.\"\"\"\n # Check user profiles first, then default profiles\n if name in self.user_profiles:\n return deepcopy(self.user_profiles[name])\n elif name in self.default_profiles:\n return deepcopy(self.default_profiles[name])\n return None\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"\n Save or update a user profile with validation.\n\n Args:\n name: Profile name\n profile: Profile data to save\n\n Returns:\n True if saved successfully\n\n Raises:\n ProfileError: If profile validation fails or save fails\n \"\"\"\n try:\n # Validate profile structure\n if not isinstance(profile, dict):\n raise ProfileError(\n \"Profile must be a dictionary\",\n profile_name=name,\n error_code=\"INVALID_PROFILE_TYPE\",\n )\n\n # Process LoRA configuration if present\n if \"config\" in profile:\n config = profile[\"config\"]\n\n # Handle LoRA adapters in config\n if \"lora_adapters\" in config:\n # Validate LoRA adapter entries\n lora_adapters = config[\"lora_adapters\"]\n if isinstance(lora_adapters, list):\n # Ensure each adapter has required fields\n for adapter in lora_adapters:\n if not isinstance(adapter, dict):\n continue\n if \"path\" not in adapter and \"name\" in adapter:\n # Try to resolve adapter by name\n adapter[\"path\"] = self._resolve_lora_path(\n adapter[\"name\"]\n )\n\n # Convert to lora_modules format for vLLM\n if lora_adapters:\n config[\"enable_lora\"] = True\n lora_modules = []\n for adapter in lora_adapters:\n if isinstance(adapter, dict):\n name = adapter.get(\"name\", \"adapter\")\n path = adapter.get(\"path\", \"\")\n if path:\n lora_modules.append(f\"{name}={path}\")\n if lora_modules:\n config[\"lora_modules\"] = \" \".join(lora_modules)\n\n # Save the profile\n self.user_profiles[name] = deepcopy(profile)\n\n if not self._save_user_profiles():\n raise ProfileError(\n \"Failed to save profile to disk\",\n profile_name=name,\n error_code=\"PROFILE_SAVE_FAILED\",\n )\n\n logger.info(f\"Successfully saved user profile: {name}\")\n return True\n\n except ProfileError:\n raise\n except Exception as e:\n logger.error(f\"Unexpected error saving profile {name}: {e}\")\n raise ProfileError(\n f\"Unexpected error saving profile: {e}\",\n profile_name=name,\n error_code=\"PROFILE_SAVE_ERROR\",\n ) from e\n\n def _resolve_lora_path(self, adapter_name: str) -> str:\n \"\"\"\n Try to resolve a LoRA adapter path by name.\n\n Args:\n adapter_name: Name of the LoRA adapter\n\n Returns:\n Path to the adapter if found, empty string otherwise\n \"\"\"\n try:\n from ..models import scan_for_lora_adapters\n\n adapters = scan_for_lora_adapters()\n for adapter in adapters:\n if (\n adapter.get(\"name\") == adapter_name\n or adapter.get(\"display_name\") == adapter_name\n ):\n return adapter.get(\"path\", \"\")\n except Exception as e:\n logger.debug(f\"Could not resolve LoRA path for {adapter_name}: {e}\")\n return \"\"\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n if name in self.user_profiles:\n del self.user_profiles[name]\n return self._save_user_profiles()\n return False\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n profile = self.get_profile(profile_name)\n if not profile:\n logger.error(f\"Profile '{profile_name}' not found\")\n return False\n\n export_data = {\"version\": \"1.0\", \"profile\": profile}\n\n try:\n with open(filepath, \"w\") as f:\n json.dump(export_data, f, indent=2)\n logger.info(f\"Profile '{profile_name}' exported to {filepath}\")\n return True\n except Exception as e:\n logger.error(f\"Error exporting profile: {e}\")\n return False\n\n def import_profile(\n self,\n filepath: Path,\n new_name: Optional[str] = None,\n validate_config_func: Optional[Callable] = None,\n ) -> bool:\n \"\"\"\n Import a profile from a JSON file with comprehensive validation.\n\n Args:\n filepath: Path to the profile file\n new_name: Optional new name for the profile\n validate_config_func: Optional function to validate profile config\n\n Returns:\n True if imported successfully\n\n Raises:\n ProfileError: If import fails for any reason\n \"\"\"\n try:\n # Check file exists\n if not filepath.exists():\n raise ProfileError(\n f\"Profile file not found: {filepath}\",\n error_code=\"PROFILE_FILE_NOT_FOUND\",\n )\n\n # Load and parse file\n try:\n with open(filepath, \"r\") as f:\n data = json.load(f)\n except json.JSONDecodeError as e:\n raise ProfileError(\n f\"Invalid JSON in profile file: {e}\",\n error_code=\"PROFILE_INVALID_JSON\",\n ) from e\n\n # Validate file format\n if not isinstance(data, dict) or \"profile\" not in data:\n raise ProfileError(\n \"Invalid profile file format - missing 'profile' key\",\n error_code=\"PROFILE_INVALID_FORMAT\",\n )\n\n profile = data[\"profile\"]\n name = new_name or profile.get(\"name\", filepath.stem)\n\n # Validate profile configuration if function provided\n if validate_config_func and \"config\" in profile:\n is_valid, errors = validate_config_func(profile[\"config\"])\n if not is_valid:\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n # Save the profile\n return self.save_user_profile(name, profile)\n\n except ProfileError:\n raise\n except Exception as e:\n logger.error(f\"Unexpected error importing profile from {filepath}: {e}\")\n raise ProfileError(\n f\"Failed to import profile: {e}\", error_code=\"PROFILE_IMPORT_ERROR\"\n ) from e\n\n def list_profile_names(self) -> Dict[str, List[str]]:\n \"\"\"\n List all profile names categorized by type.\n\n Returns:\n Dictionary with 'default' and 'user' lists of profile names\n \"\"\"\n return {\n \"default\": list(self.default_profiles.keys()),\n \"user\": list(self.user_profiles.keys()),\n }\n\n def profile_exists(self, name: str) -> bool:\n \"\"\"Check if a profile exists (in either default or user profiles).\"\"\"\n return name in self.default_profiles or name in self.user_profiles\n\n def is_user_profile(self, name: str) -> bool:\n \"\"\"Check if a profile is a user-created profile.\"\"\"\n return name in self.user_profiles\n\n def has_user_override(self, name: str) -> bool:\n \"\"\"\n Check if a built-in profile has been overridden by a user profile.\n\n Args:\n name: Profile name to check\n\n Returns:\n True if this is a built-in profile that has a user override\n \"\"\"\n return name in self.default_profiles and name in self.user_profiles\n\n def get_original_default_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get the original default profile without any user overrides.\n\n Args:\n name: Profile name\n\n Returns:\n Original default profile if it exists, None otherwise\n \"\"\"\n if name in self.default_profiles:\n return deepcopy(self.default_profiles[name])\n return None\n\n def reset_to_default(self, name: str) -> bool:\n \"\"\"\n Reset a customized built-in profile to its default settings.\n\n This removes the user override for a built-in profile.\n\n Args:\n name: Profile name to reset\n\n Returns:\n True if reset successfully, False otherwise\n \"\"\"\n # Only reset if this is a built-in profile with a user override\n if self.has_user_override(name):\n return self.delete_user_profile(name)\n return False\n\n def get_profile_count(self) -> Dict[str, int]:\n \"\"\"Get count of profiles by type.\"\"\"\n return {\n \"default\": len(self.default_profiles),\n \"user\": len(self.user_profiles),\n \"total\": len(self.default_profiles) + len(self.user_profiles),\n }\n\n def apply_dynamic_defaults(self, profile_config: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Apply dynamic defaults to a profile configuration.\n\n This function intelligently sets tensor_parallel_size for multi-GPU systems.\n For single GPU systems, it allows vLLM to use its default behavior.\n\n Note: vLLM defaults to using only 1 GPU unless tensor_parallel_size is explicitly set.\n\n Args:\n profile_config: The profile configuration to enhance\n\n Returns:\n Enhanced profile configuration with dynamic defaults applied\n \"\"\"\n config = deepcopy(profile_config)\n\n # Apply dynamic tensor_parallel_size if not specified\n # Note: vLLM defaults to single GPU, so we only set this for multi-GPU systems\n # where tensor parallelism would be beneficial\n if \"tensor_parallel_size\" not in config:\n gpu_count = self._get_gpu_count()\n if gpu_count > 1:\n config[\"tensor_parallel_size\"] = gpu_count\n logger.debug(\n f\"Set tensor_parallel_size to {gpu_count} for multi-GPU system\"\n )\n # For single GPU, let vLLM use its default (no tensor_parallel_size needed)\n\n return config\n\n def _get_gpu_count(self) -> int:\n \"\"\"\n Get the number of available GPUs for tensor parallelism.\n\n Returns:\n Number of GPUs available, defaults to 1 if detection fails\n \"\"\"\n try:\n gpus = get_gpu_info()\n gpu_count = len(gpus) if gpus else 1\n logger.debug(f\"Detected {gpu_count} GPU(s)\")\n return gpu_count\n except Exception as e:\n logger.warning(f\"Failed to detect GPU count, defaulting to 1: {e}\")\n return 1", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 14008}, "tests/test_config_manager.py::131": {"resolved_imports": ["src/vllm_cli/config/manager.py"], "used_names": ["ConfigManager", "patch"], "enclosing_function": "test_save_last_config", "extracted_code": "# Source: src/vllm_cli/config/manager.py\nclass ConfigManager:\n \"\"\"\n Enhanced configuration manager with comprehensive validation support.\n\n This class manages configuration files, profiles, and validation using\n the new validation framework. It provides a clean API for configuration\n operations while ensuring data integrity through comprehensive validation.\n\n Attributes:\n config_dir: Directory for configuration files\n validation_registry: Registry of validation rules\n compatibility_validator: Validator for parameter combinations\n \"\"\"\n\n def __init__(self):\n # Paths for configuration files\n self.config_dir = Path.home() / \".config\" / \"vllm-cli\"\n self.config_file = self.config_dir / \"config.yaml\"\n\n # Ensure config directory exists\n self.config_dir.mkdir(parents=True, exist_ok=True)\n\n # Initialize sub-managers\n self.schema_manager = SchemaManager()\n self.profile_manager = ProfileManager(self.config_dir)\n self.persistence_manager = PersistenceManager()\n self.shortcut_manager = ShortcutManager(self.config_dir)\n\n # Initialize validation system\n self.validation_registry = create_vllm_validation_registry()\n self.compatibility_validator = create_compatibility_validator(\n self.validation_registry\n )\n\n # Load main configuration\n self.config = self._load_config()\n\n def _load_config(self) -> Dict[str, Any]:\n \"\"\"Load main configuration file (legacy YAML support).\"\"\"\n return self.persistence_manager.load_yaml_file(self.config_file)\n\n def _save_config(self) -> None:\n \"\"\"Save main configuration file.\"\"\"\n self.persistence_manager.save_yaml_file(self.config_file, self.config)\n\n def get_argument_info(self, arg_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get detailed information about a specific argument.\"\"\"\n return self.schema_manager.get_argument_info(arg_name)\n\n def get_arguments_by_category(self, category: str) -> List[Dict[str, Any]]:\n \"\"\"Get all arguments belonging to a specific category.\"\"\"\n return self.schema_manager.get_arguments_by_category(category)\n\n def get_category_info(self, category: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get information about a specific category.\"\"\"\n return self.schema_manager.get_category_info(category)\n\n def get_ordered_categories(self) -> List[Tuple[str, Dict[str, Any]]]:\n \"\"\"Get categories ordered by their display order.\"\"\"\n return self.schema_manager.get_ordered_categories()\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n return self.profile_manager.get_all_profiles()\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name with dynamic defaults applied.\"\"\"\n profile = self.profile_manager.get_profile(name)\n if profile and \"config\" in profile:\n # Apply dynamic defaults to the profile configuration\n profile[\"config\"] = self.profile_manager.apply_dynamic_defaults(\n profile[\"config\"]\n )\n return profile\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"Save or update a user profile with validation.\"\"\"\n # Validate profile configuration if present\n if \"config\" in profile:\n is_valid, errors = self.validate_config(profile[\"config\"])\n if not is_valid:\n from ..errors import ProfileError\n\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n return self.profile_manager.save_user_profile(name, profile)\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n return self.profile_manager.delete_user_profile(name)\n\n @property\n def default_profiles(self) -> Dict[str, Any]:\n \"\"\"Get default profiles.\"\"\"\n return self.profile_manager.default_profiles\n\n @property\n def user_profiles(self) -> Dict[str, Any]:\n \"\"\"Get user profiles.\"\"\"\n return self.profile_manager.user_profiles\n\n def validate_config(self, config: Dict[str, Any]) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate a configuration using the new validation framework.\n\n This method uses the comprehensive validation system to check\n configuration values, types, ranges, and dependencies.\n\n Args:\n config: Configuration dictionary to validate\n\n Returns:\n Tuple of (is_valid, list_of_error_messages)\n\n Raises:\n ConfigurationError: If validation system fails\n \"\"\"\n try:\n # Use new validation system\n result = self.validation_registry.validate_config(config)\n\n # Convert validation errors to string messages for backward compatibility\n error_messages = result.get_error_messages()\n\n # Add warnings if any\n if result.warnings:\n for warning in result.warnings:\n logger.warning(f\"Configuration warning: {warning}\")\n\n return result.is_valid(), error_messages\n\n except Exception as e:\n logger.error(f\"Error during configuration validation: {e}\")\n raise ConfigurationError(\n f\"Validation system error: {e}\", error_code=\"VALIDATION_SYSTEM_ERROR\"\n ) from e\n\n def validate_argument_combination(\n self, config: Dict[str, Any]\n ) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate that argument combinations are compatible using the new compatibility validator.\n\n Args:\n config: Configuration dictionary to check for compatibility\n\n Returns:\n Tuple of (is_valid, list_of_warnings_or_errors)\n \"\"\"\n try:\n issues = self.compatibility_validator.validate_compatibility(config)\n\n warnings = []\n errors = []\n\n for issue in issues:\n message = issue[\"message\"]\n if issue[\"severity\"] == \"error\":\n errors.append(message)\n else:\n warnings.append(message)\n\n # Log warnings\n for warning in warnings:\n logger.warning(f\"Configuration compatibility warning: {warning}\")\n\n # Return all issues as warnings for backward compatibility\n # (errors are treated as warnings in the legacy interface)\n all_issues = errors + warnings\n\n return len(errors) == 0, all_issues\n\n except Exception as e:\n logger.error(f\"Error during compatibility validation: {e}\")\n return False, [f\"Compatibility validation error: {e}\"]\n\n def build_cli_args(self, config: Dict[str, Any]) -> List[str]:\n \"\"\"\n Build command-line arguments from a configuration dictionary.\n\n Only includes arguments that are explicitly set in the config.\n Handles special cases like LoRA modules.\n \"\"\"\n args = []\n\n # Special handling for model (positional argument)\n # Check if this is a GGUF/Ollama configuration\n if (\n isinstance(config.get(\"model\"), dict)\n and \"quantization\" in config[\"model\"]\n and config[\"model\"][\"quantization\"] == \"gguf\"\n ):\n # Extract GGUF model config\n gguf_config = config[\"model\"]\n model_path = gguf_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", model_path])\n\n # Set quantization to gguf\n config[\"quantization\"] = \"gguf\"\n\n # Add served-model-name if provided (for Ollama models)\n if \"served_model_name\" in gguf_config:\n config[\"served_model_name\"] = gguf_config[\"served_model_name\"]\n logger.info(\n f\"Configuring GGUF model: {model_path} as {gguf_config['served_model_name']}\"\n )\n else:\n logger.info(f\"Configuring GGUF model: {model_path}\")\n\n # Check if this is a LoRA configuration\n elif (\n isinstance(config.get(\"model\"), dict) and \"lora_modules\" in config[\"model\"]\n ):\n # Extract base model and LoRA config\n lora_config = config[\"model\"]\n base_model = lora_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", base_model])\n\n # Enable LoRA support when modules are present\n args.append(\"--enable-lora\")\n\n # Track maximum rank for all LoRA modules\n max_rank = 16 # Default minimum\n\n # Add LoRA modules\n for lora in lora_config.get(\"lora_modules\", []):\n lora_path = lora.get(\"path\", \"\")\n if lora_path:\n # vLLM expects --lora-modules with name=path format\n lora_name = lora.get(\"name\", \"adapter\")\n args.extend([\"--lora-modules\", f\"{lora_name}={lora_path}\"])\n\n # Track maximum rank\n lora_rank = lora.get(\"rank\", 16)\n max_rank = max(max_rank, lora_rank)\n\n # Add max-lora-rank parameter\n args.extend([\"--max-lora-rank\", str(max_rank)])\n\n elif \"model\" in config:\n args.extend([\"serve\", config[\"model\"]])\n\n # Handle lora_modules if present as a string (from CLI)\n if \"lora_modules\" in config and config[\"lora_modules\"]:\n # Enable LoRA support\n if \"--enable-lora\" not in args:\n args.append(\"--enable-lora\")\n\n # Parse and add LoRA modules\n lora_modules_str = config[\"lora_modules\"]\n if isinstance(lora_modules_str, str):\n # Split by space and add each module\n for module in lora_modules_str.split():\n args.extend([\"--lora-modules\", module])\n\n # Add max-lora-rank if not already added\n # Use a safe default of 64 which should cover most LoRA adapters\n if \"--max-lora-rank\" not in args:\n # Check if max_lora_rank is explicitly set in config\n if \"max_lora_rank\" not in config:\n args.extend([\"--max-lora-rank\", \"64\"])\n\n for arg_name, value in config.items():\n # Skip special keys and None values\n if (\n arg_name in [\"model\", \"name\", \"description\", \"icon\", \"lora_modules\"]\n or value is None\n ):\n continue\n\n arg_info = self.schema_manager.get_argument_info(arg_name)\n if not arg_info:\n logger.warning(f\"Unknown argument in config: {arg_name}\")\n continue\n\n cli_flag = arg_info.get(\"cli_flag\")\n if not cli_flag:\n continue\n\n arg_type = arg_info.get(\"type\")\n\n if arg_type == \"boolean\":\n if value: # Only add flag if True\n args.append(cli_flag)\n elif arg_type in [\"integer\", \"float\", \"string\", \"choice\"]:\n args.extend([cli_flag, str(value)])\n else:\n logger.warning(f\"Unknown argument type for {arg_name}: {arg_type}\")\n\n return args\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n return self.profile_manager.export_profile(profile_name, filepath)\n\n def import_profile(self, filepath: Path, new_name: Optional[str] = None) -> bool:\n \"\"\"Import a profile from a JSON file with comprehensive validation.\"\"\"\n return self.profile_manager.import_profile(\n filepath, new_name, self.validate_config\n )\n\n def get_last_config(self) -> Optional[Dict[str, Any]]:\n \"\"\"Get the last used server configuration.\"\"\"\n return self.config.get(\"last_config\")\n\n def save_last_config(self, config: Dict[str, Any]) -> None:\n \"\"\"Save the last used server configuration.\"\"\"\n self.config[\"last_config\"] = config\n self._save_config()\n\n def get_recent_models(self, limit: int = 5) -> List[str]:\n \"\"\"Get recently used models.\"\"\"\n return self.config.get(\"recent_models\", [])[:limit]\n\n def add_recent_model(self, model: str) -> None:\n \"\"\"Add a model to recent models list.\"\"\"\n recent = self.config.get(\"recent_models\", [])\n if model in recent:\n recent.remove(model)\n recent.insert(0, model)\n self.config[\"recent_models\"] = recent[:10] # Keep only last 10\n self._save_config()\n\n def clear_cache(self) -> None:\n \"\"\"Clear cached data.\"\"\"\n cache_file = self.config_dir / \"cache.json\"\n if cache_file.exists():\n cache_file.unlink()\n self.config.pop(\"last_config\", None)\n self.config.pop(\"recent_models\", None)\n self._save_config()\n logger.info(\"Cache cleared\")\n\n def get_server_defaults(self) -> Dict[str, Any]:\n \"\"\"Get default server settings.\"\"\"\n return self.config.get(\n \"server_defaults\",\n {\n \"default_port\": 8000,\n \"auto_restart\": False,\n \"log_level\": \"info\",\n \"cleanup_on_exit\": True, # Default to cleaning up servers on exit\n },\n )\n\n def save_server_defaults(self, defaults: Dict[str, Any]) -> None:\n \"\"\"Save default server settings.\"\"\"\n self.config[\"server_defaults\"] = defaults\n self._save_config()\n\n def get_ui_preferences(self) -> Dict[str, Any]:\n \"\"\"Get UI preferences including progress bar style and log display settings.\"\"\"\n return self.config.get(\n \"ui_preferences\",\n {\n \"progress_bar_style\": \"blocks\", # Default style\n \"show_gpu_in_monitor\": True,\n \"log_lines_startup\": 50, # Number of log lines to show during startup\n \"log_lines_monitor\": 50, # Number of log lines to show in server monitor\n \"startup_refresh_rate\": 4.0, # Hz for startup log refresh\n \"monitor_refresh_rate\": 1.0, # Hz for monitor log refresh\n },\n )\n\n def save_ui_preferences(self, preferences: Dict[str, Any]) -> None:\n \"\"\"Save UI preferences.\"\"\"\n self.config[\"ui_preferences\"] = preferences\n self._save_config()\n\n # Shortcut management methods\n def get_all_shortcuts(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all shortcuts.\"\"\"\n return self.shortcut_manager.get_all_shortcuts()\n\n def get_shortcut(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific shortcut by name.\"\"\"\n return self.shortcut_manager.get_shortcut(name)\n\n def save_shortcut(self, name: str, shortcut_data: Dict[str, Any]) -> bool:\n \"\"\"Save or update a shortcut.\"\"\"\n return self.shortcut_manager.save_shortcut(name, shortcut_data)\n\n def delete_shortcut(self, name: str) -> bool:\n \"\"\"Delete a shortcut.\"\"\"\n return self.shortcut_manager.delete_shortcut(name)\n\n def list_shortcuts(self) -> List[Dict[str, Any]]:\n \"\"\"List all shortcuts with summary information.\"\"\"\n return self.shortcut_manager.list_shortcuts()\n\n def get_recent_shortcuts(self, limit: int = 5) -> List[Dict[str, Any]]:\n \"\"\"Get recently used shortcuts.\"\"\"\n return self.shortcut_manager.get_recent_shortcuts(limit)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 15704}, "tests/test_cli_parser.py::14": {"resolved_imports": ["src/vllm_cli/cli/parser.py"], "used_names": ["create_parser"], "enclosing_function": "test_create_parser", "extracted_code": "# Source: src/vllm_cli/cli/parser.py\ndef create_parser() -> argparse.ArgumentParser:\n \"\"\"\n Create the main argument parser for vLLM CLI.\n\n Sets up the main parser with all subcommands and their arguments.\n\n Returns:\n Configured ArgumentParser instance\n \"\"\"\n parser = argparse.ArgumentParser(\n prog=\"vllm-cli\",\n description=\"vLLM CLI - Convenient LLM serving tool\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"Examples:\n vllm-cli # Interactive mode\n vllm-cli serve MODEL --profile standard # Serve with profile\n vllm-cli serve MODEL --quantization awq # Serve with AWQ quantization\n vllm-cli serve MODEL --extra-args \"--seed 42\" # With custom vLLM args\n vllm-cli info # System information\n vllm-cli models # List available models\n vllm-cli status # Show active servers\"\"\",\n )\n\n # Global options\n from .. import __version__\n\n parser.add_argument(\n \"--version\", action=\"version\", version=f\"vLLM CLI {__version__}\"\n )\n\n # Create subparsers for commands\n subparsers = parser.add_subparsers(\n dest=\"command\",\n help=\"Available commands\",\n metavar=\"{serve,proxy,info,models,shortcuts,status,stop,dirs}\",\n )\n\n # Add individual command parsers\n _add_serve_parser(subparsers)\n _add_proxy_parser(subparsers)\n _add_info_parser(subparsers)\n _add_models_parser(subparsers)\n _add_shortcuts_parser(subparsers)\n _add_status_parser(subparsers)\n _add_stop_parser(subparsers)\n _add_dirs_parser(subparsers)\n\n return parser", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1705}, "tests/proxy/test_integration.py::82": {"resolved_imports": ["src/vllm_cli/proxy/config.py", "src/vllm_cli/proxy/manager.py", "src/vllm_cli/proxy/models.py", "src/vllm_cli/proxy/server_process.py"], "used_names": ["ProxyConfigManager"], "enclosing_function": "test_load_proxy_config", "extracted_code": "# Source: src/vllm_cli/proxy/config.py\nclass ProxyConfigManager:\n \"\"\"\n Manages proxy server configuration including persistence and validation.\n \"\"\"\n\n def __init__(self):\n \"\"\"Initialize the proxy configuration manager.\"\"\"\n self.config_dir = Path.home() / \".config\" / \"vllm-cli\"\n # Default configuration file path - used as fallback when no path specified\n # Also maintains backward compatibility with existing configurations\n self.proxy_config_file = self.config_dir / \"proxy_config.yaml\"\n self.proxy_configs_dir = self.config_dir / \"proxy_configs\"\n self.config_dir.mkdir(parents=True, exist_ok=True)\n self.proxy_configs_dir.mkdir(parents=True, exist_ok=True)\n\n def load_config(self, config_path: Optional[Path] = None) -> ProxyConfig:\n \"\"\"\n Load proxy configuration from file.\n\n Args:\n config_path: Path to configuration file (uses default if not provided)\n\n Returns:\n ProxyConfig instance\n \"\"\"\n config_file = config_path or self.proxy_config_file\n\n if not config_file.exists():\n logger.info(f\"No config file found at {config_file}, using defaults\")\n return self.get_default_config()\n\n try:\n with open(config_file, \"r\") as f:\n if config_file.suffix in [\".yaml\", \".yml\"]:\n config_dict = yaml.safe_load(f)\n else:\n config_dict = json.load(f)\n\n return self._parse_config(config_dict)\n\n except Exception as e:\n logger.error(f\"Failed to load config from {config_file}: {e}\")\n return self.get_default_config()\n\n def save_config(self, config: ProxyConfig, config_path: Optional[Path] = None):\n \"\"\"\n Save proxy configuration to file.\n\n Args:\n config: ProxyConfig to save\n config_path: Path to save to (uses default if not provided)\n \"\"\"\n config_file = config_path or self.proxy_config_file\n\n try:\n config_dict = {\n \"proxy\": {\n \"host\": config.host,\n \"port\": config.port,\n \"enable_cors\": config.enable_cors,\n \"enable_metrics\": config.enable_metrics,\n \"log_requests\": config.log_requests,\n },\n \"models\": [\n {\n \"name\": model.name,\n \"model_path\": model.model_path,\n \"gpu_ids\": model.gpu_ids,\n \"port\": model.port,\n \"profile\": model.profile,\n \"config_overrides\": model.config_overrides,\n \"enabled\": model.enabled,\n \"loading_priority\": model.loading_priority,\n }\n for model in config.models\n ],\n }\n\n with open(config_file, \"w\") as f:\n if config_file.suffix in [\".yaml\", \".yml\"]:\n yaml.safe_dump(config_dict, f, default_flow_style=False)\n else:\n json.dump(config_dict, f, indent=2)\n\n logger.info(f\"Saved proxy configuration to {config_file}\")\n\n except Exception as e:\n logger.error(f\"Failed to save config to {config_file}: {e}\")\n\n def save_named_config(self, config: ProxyConfig, name: str):\n \"\"\"\n Save proxy configuration with a specific name.\n\n Args:\n config: ProxyConfig to save\n name: Name for the configuration\n \"\"\"\n # Sanitize name for filesystem\n safe_name = \"\".join(c if c.isalnum() or c in \"_-\" else \"_\" for c in name)\n config_file = self.proxy_configs_dir / f\"{safe_name}.yaml\"\n\n self.save_config(config, config_file)\n logger.info(f\"Saved proxy configuration as '{name}'\")\n\n def load_named_config(self, name: str) -> Optional[ProxyConfig]:\n \"\"\"\n Load a named proxy configuration.\n\n Args:\n name: Name of the configuration to load\n\n Returns:\n ProxyConfig if found, None otherwise\n \"\"\"\n safe_name = \"\".join(c if c.isalnum() or c in \"_-\" else \"_\" for c in name)\n config_file = self.proxy_configs_dir / f\"{safe_name}.yaml\"\n\n if not config_file.exists():\n logger.error(f\"Configuration '{name}' not found\")\n return None\n\n return self.load_config(config_file)\n\n def list_saved_configs(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"\n List all saved proxy configurations.\n\n Returns:\n Dictionary mapping config names to their summaries\n \"\"\"\n configs = {}\n\n # Check new named configs directory\n for config_file in self.proxy_configs_dir.glob(\"*.yaml\"):\n name = config_file.stem\n try:\n config = self.load_config(config_file)\n if config:\n configs[name] = {\n \"file\": str(config_file),\n \"models\": len(config.models),\n \"port\": config.port,\n \"model_names\": [m.name for m in config.models][\n :3\n ], # First 3 models\n }\n except Exception as e:\n logger.warning(f\"Failed to load config {name}: {e}\")\n\n # Also check legacy default location\n if self.proxy_config_file.exists():\n try:\n config = self.load_config(self.proxy_config_file)\n if config:\n configs[\"default\"] = {\n \"file\": str(self.proxy_config_file),\n \"models\": len(config.models),\n \"port\": config.port,\n \"model_names\": [m.name for m in config.models][:3],\n }\n except Exception:\n pass\n\n return configs\n\n def delete_named_config(self, name: str) -> bool:\n \"\"\"\n Delete a named proxy configuration.\n\n Args:\n name: Name of the configuration to delete\n\n Returns:\n True if deleted successfully\n \"\"\"\n safe_name = \"\".join(c if c.isalnum() or c in \"_-\" else \"_\" for c in name)\n config_file = self.proxy_configs_dir / f\"{safe_name}.yaml\"\n\n if config_file.exists():\n try:\n config_file.unlink()\n logger.info(f\"Deleted configuration '{name}'\")\n return True\n except Exception as e:\n logger.error(f\"Failed to delete configuration '{name}': {e}\")\n return False\n else:\n logger.warning(f\"Configuration '{name}' not found\")\n return False\n\n def get_default_config(self) -> ProxyConfig:\n \"\"\"\n Get default proxy configuration.\n\n Returns:\n Default ProxyConfig instance\n \"\"\"\n return ProxyConfig(\n host=\"0.0.0.0\", # nosec B104\n port=8000,\n models=[],\n enable_cors=True,\n enable_metrics=True,\n log_requests=False,\n )\n\n def _parse_config(self, config_dict: Dict[str, Any]) -> ProxyConfig:\n \"\"\"\n Parse configuration dictionary into ProxyConfig.\n\n Args:\n config_dict: Configuration dictionary\n\n Returns:\n ProxyConfig instance\n \"\"\"\n proxy_settings = config_dict.get(\"proxy\", {})\n models_list = config_dict.get(\"models\", [])\n\n models = []\n for model_dict in models_list:\n try:\n models.append(ModelConfig(**model_dict))\n except Exception as e:\n logger.warning(f\"Failed to parse model config: {e}\")\n\n return ProxyConfig(\n host=proxy_settings.get(\"host\", \"0.0.0.0\"), # nosec B104\n port=proxy_settings.get(\"port\", 8000),\n models=models,\n enable_cors=proxy_settings.get(\"enable_cors\", True),\n enable_metrics=proxy_settings.get(\"enable_metrics\", True),\n log_requests=proxy_settings.get(\"log_requests\", False),\n )\n\n def validate_config(self, config: ProxyConfig) -> List[str]:\n \"\"\"\n Validate proxy configuration.\n\n Args:\n config: ProxyConfig to validate\n\n Returns:\n List of validation errors (empty if valid)\n \"\"\"\n errors = []\n\n # Check proxy port\n if not 1 <= config.port <= 65535:\n errors.append(f\"Invalid proxy port: {config.port}\")\n\n # Check for port conflicts\n used_ports = {config.port}\n for model in config.models:\n if model.port in used_ports:\n errors.append(f\"Port {model.port} is used by multiple services\")\n used_ports.add(model.port)\n\n # Check model names are unique\n model_names = [m.name for m in config.models]\n if len(model_names) != len(set(model_names)):\n errors.append(\"Model names must be unique\")\n\n return errors\n\n def create_example_config(self) -> ProxyConfig:\n \"\"\"\n Create an example proxy configuration.\n\n Returns:\n Example ProxyConfig instance\n \"\"\"\n return ProxyConfig(\n host=\"0.0.0.0\", # nosec B104\n port=8000,\n models=[\n ModelConfig(\n name=\"llama-3-8b\",\n model_path=\"meta-llama/Meta-Llama-3-8B-Instruct\",\n gpu_ids=[0],\n port=8001,\n profile=\"standard\",\n enabled=True,\n ),\n ModelConfig(\n name=\"mistral-7b\",\n model_path=\"mistralai/Mistral-7B-Instruct-v0.2\",\n gpu_ids=[1],\n port=8002,\n profile=\"performance\",\n enabled=True,\n ),\n ModelConfig(\n name=\"gemma-2b\",\n model_path=\"google/gemma-2b\",\n gpu_ids=[2],\n port=8003,\n profile=\"memory-optimized\",\n enabled=False, # Disabled by default\n ),\n ],\n enable_cors=True,\n enable_metrics=True,\n log_requests=False,\n )\n\n def export_config(self, config: ProxyConfig, export_path: Path):\n \"\"\"\n Export configuration to a file.\n\n Args:\n config: ProxyConfig to export\n export_path: Path to export to\n \"\"\"\n self.save_config(config, export_path)\n logger.info(f\"Exported configuration to {export_path}\")\n\n def import_config(self, import_path: Path) -> ProxyConfig:\n \"\"\"\n Import configuration from a file.\n\n Args:\n import_path: Path to import from\n\n Returns:\n Imported ProxyConfig instance\n \"\"\"\n config = self.load_config(import_path)\n logger.info(f\"Imported configuration from {import_path}\")\n return config", "n_imports_parsed": 9, "n_files_resolved": 4, "n_chars_extracted": 11221}, "tests/test_ollama_support.py::251": {"resolved_imports": ["src/vllm_cli/models/discovery.py", "src/vllm_cli/models/manager.py"], "used_names": [], "enclosing_function": "test_unsupported_architectures_documented", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/proxy/test_e2e.py::254": {"resolved_imports": ["src/vllm_cli/proxy/manager.py", "src/vllm_cli/proxy/models.py", "src/vllm_cli/proxy/server.py"], "used_names": ["asyncio", "httpx", "pytest"], "enclosing_function": "test_e2e_streaming_response", "extracted_code": "", "n_imports_parsed": 13, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_cli_parser.py::65": {"resolved_imports": ["src/vllm_cli/cli/parser.py"], "used_names": ["create_parser"], "enclosing_function": "test_serve_command_with_lora", "extracted_code": "# Source: src/vllm_cli/cli/parser.py\ndef create_parser() -> argparse.ArgumentParser:\n \"\"\"\n Create the main argument parser for vLLM CLI.\n\n Sets up the main parser with all subcommands and their arguments.\n\n Returns:\n Configured ArgumentParser instance\n \"\"\"\n parser = argparse.ArgumentParser(\n prog=\"vllm-cli\",\n description=\"vLLM CLI - Convenient LLM serving tool\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"Examples:\n vllm-cli # Interactive mode\n vllm-cli serve MODEL --profile standard # Serve with profile\n vllm-cli serve MODEL --quantization awq # Serve with AWQ quantization\n vllm-cli serve MODEL --extra-args \"--seed 42\" # With custom vLLM args\n vllm-cli info # System information\n vllm-cli models # List available models\n vllm-cli status # Show active servers\"\"\",\n )\n\n # Global options\n from .. import __version__\n\n parser.add_argument(\n \"--version\", action=\"version\", version=f\"vLLM CLI {__version__}\"\n )\n\n # Create subparsers for commands\n subparsers = parser.add_subparsers(\n dest=\"command\",\n help=\"Available commands\",\n metavar=\"{serve,proxy,info,models,shortcuts,status,stop,dirs}\",\n )\n\n # Add individual command parsers\n _add_serve_parser(subparsers)\n _add_proxy_parser(subparsers)\n _add_info_parser(subparsers)\n _add_models_parser(subparsers)\n _add_shortcuts_parser(subparsers)\n _add_status_parser(subparsers)\n _add_stop_parser(subparsers)\n _add_dirs_parser(subparsers)\n\n return parser", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1705}, "tests/proxy/test_router.py::29": {"resolved_imports": ["src/vllm_cli/proxy/router.py"], "used_names": [], "enclosing_function": "test_add_backend", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_profiles.py::111": {"resolved_imports": ["src/vllm_cli/config/profiles.py"], "used_names": ["ProfileManager"], "enclosing_function": "test_delete_nonexistent_profile", "extracted_code": "# Source: src/vllm_cli/config/profiles.py\nclass ProfileManager:\n \"\"\"\n Manages user profiles for vLLM configurations.\n\n Handles creation, retrieval, updating, and deletion of user profiles\n with validation and persistence.\n \"\"\"\n\n def __init__(self, config_dir: Path):\n self.config_dir = config_dir\n self.user_profiles_file = config_dir / \"user_profiles.json\"\n\n # Paths for schema files (packaged with application)\n schema_dir = Path(__file__).parent.parent / \"schemas\"\n self.default_profiles_file = schema_dir / \"default_profiles.json\"\n\n # Load profiles\n self.default_profiles = self._load_default_profiles()\n self.user_profiles = self._load_user_profiles()\n\n def _load_json_file(self, filepath: Path) -> Dict[str, Any]:\n \"\"\"Load a JSON file safely.\"\"\"\n if filepath.exists():\n try:\n with open(filepath, \"r\") as f:\n return json.load(f)\n except Exception as e:\n logger.error(f\"Error loading {filepath}: {e}\")\n return {}\n\n def _save_json_file(self, filepath: Path, data: Dict[str, Any]) -> bool:\n \"\"\"Save data to a JSON file.\"\"\"\n try:\n with open(filepath, \"w\") as f:\n json.dump(data, f, indent=2)\n return True\n except Exception as e:\n logger.error(f\"Error saving {filepath}: {e}\")\n return False\n\n def _load_default_profiles(self) -> Dict[str, Any]:\n \"\"\"Load default built-in profiles.\"\"\"\n profiles = self._load_json_file(self.default_profiles_file)\n return profiles.get(\"profiles\", {})\n\n def _load_user_profiles(self) -> Dict[str, Any]:\n \"\"\"Load user-created custom profiles.\"\"\"\n return self._load_json_file(self.user_profiles_file)\n\n def _save_user_profiles(self) -> bool:\n \"\"\"Save user profiles to file.\"\"\"\n return self._save_json_file(self.user_profiles_file, self.user_profiles)\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n all_profiles = deepcopy(self.default_profiles)\n all_profiles.update(self.user_profiles)\n return all_profiles\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name.\"\"\"\n # Check user profiles first, then default profiles\n if name in self.user_profiles:\n return deepcopy(self.user_profiles[name])\n elif name in self.default_profiles:\n return deepcopy(self.default_profiles[name])\n return None\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"\n Save or update a user profile with validation.\n\n Args:\n name: Profile name\n profile: Profile data to save\n\n Returns:\n True if saved successfully\n\n Raises:\n ProfileError: If profile validation fails or save fails\n \"\"\"\n try:\n # Validate profile structure\n if not isinstance(profile, dict):\n raise ProfileError(\n \"Profile must be a dictionary\",\n profile_name=name,\n error_code=\"INVALID_PROFILE_TYPE\",\n )\n\n # Process LoRA configuration if present\n if \"config\" in profile:\n config = profile[\"config\"]\n\n # Handle LoRA adapters in config\n if \"lora_adapters\" in config:\n # Validate LoRA adapter entries\n lora_adapters = config[\"lora_adapters\"]\n if isinstance(lora_adapters, list):\n # Ensure each adapter has required fields\n for adapter in lora_adapters:\n if not isinstance(adapter, dict):\n continue\n if \"path\" not in adapter and \"name\" in adapter:\n # Try to resolve adapter by name\n adapter[\"path\"] = self._resolve_lora_path(\n adapter[\"name\"]\n )\n\n # Convert to lora_modules format for vLLM\n if lora_adapters:\n config[\"enable_lora\"] = True\n lora_modules = []\n for adapter in lora_adapters:\n if isinstance(adapter, dict):\n name = adapter.get(\"name\", \"adapter\")\n path = adapter.get(\"path\", \"\")\n if path:\n lora_modules.append(f\"{name}={path}\")\n if lora_modules:\n config[\"lora_modules\"] = \" \".join(lora_modules)\n\n # Save the profile\n self.user_profiles[name] = deepcopy(profile)\n\n if not self._save_user_profiles():\n raise ProfileError(\n \"Failed to save profile to disk\",\n profile_name=name,\n error_code=\"PROFILE_SAVE_FAILED\",\n )\n\n logger.info(f\"Successfully saved user profile: {name}\")\n return True\n\n except ProfileError:\n raise\n except Exception as e:\n logger.error(f\"Unexpected error saving profile {name}: {e}\")\n raise ProfileError(\n f\"Unexpected error saving profile: {e}\",\n profile_name=name,\n error_code=\"PROFILE_SAVE_ERROR\",\n ) from e\n\n def _resolve_lora_path(self, adapter_name: str) -> str:\n \"\"\"\n Try to resolve a LoRA adapter path by name.\n\n Args:\n adapter_name: Name of the LoRA adapter\n\n Returns:\n Path to the adapter if found, empty string otherwise\n \"\"\"\n try:\n from ..models import scan_for_lora_adapters\n\n adapters = scan_for_lora_adapters()\n for adapter in adapters:\n if (\n adapter.get(\"name\") == adapter_name\n or adapter.get(\"display_name\") == adapter_name\n ):\n return adapter.get(\"path\", \"\")\n except Exception as e:\n logger.debug(f\"Could not resolve LoRA path for {adapter_name}: {e}\")\n return \"\"\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n if name in self.user_profiles:\n del self.user_profiles[name]\n return self._save_user_profiles()\n return False\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n profile = self.get_profile(profile_name)\n if not profile:\n logger.error(f\"Profile '{profile_name}' not found\")\n return False\n\n export_data = {\"version\": \"1.0\", \"profile\": profile}\n\n try:\n with open(filepath, \"w\") as f:\n json.dump(export_data, f, indent=2)\n logger.info(f\"Profile '{profile_name}' exported to {filepath}\")\n return True\n except Exception as e:\n logger.error(f\"Error exporting profile: {e}\")\n return False\n\n def import_profile(\n self,\n filepath: Path,\n new_name: Optional[str] = None,\n validate_config_func: Optional[Callable] = None,\n ) -> bool:\n \"\"\"\n Import a profile from a JSON file with comprehensive validation.\n\n Args:\n filepath: Path to the profile file\n new_name: Optional new name for the profile\n validate_config_func: Optional function to validate profile config\n\n Returns:\n True if imported successfully\n\n Raises:\n ProfileError: If import fails for any reason\n \"\"\"\n try:\n # Check file exists\n if not filepath.exists():\n raise ProfileError(\n f\"Profile file not found: {filepath}\",\n error_code=\"PROFILE_FILE_NOT_FOUND\",\n )\n\n # Load and parse file\n try:\n with open(filepath, \"r\") as f:\n data = json.load(f)\n except json.JSONDecodeError as e:\n raise ProfileError(\n f\"Invalid JSON in profile file: {e}\",\n error_code=\"PROFILE_INVALID_JSON\",\n ) from e\n\n # Validate file format\n if not isinstance(data, dict) or \"profile\" not in data:\n raise ProfileError(\n \"Invalid profile file format - missing 'profile' key\",\n error_code=\"PROFILE_INVALID_FORMAT\",\n )\n\n profile = data[\"profile\"]\n name = new_name or profile.get(\"name\", filepath.stem)\n\n # Validate profile configuration if function provided\n if validate_config_func and \"config\" in profile:\n is_valid, errors = validate_config_func(profile[\"config\"])\n if not is_valid:\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n # Save the profile\n return self.save_user_profile(name, profile)\n\n except ProfileError:\n raise\n except Exception as e:\n logger.error(f\"Unexpected error importing profile from {filepath}: {e}\")\n raise ProfileError(\n f\"Failed to import profile: {e}\", error_code=\"PROFILE_IMPORT_ERROR\"\n ) from e\n\n def list_profile_names(self) -> Dict[str, List[str]]:\n \"\"\"\n List all profile names categorized by type.\n\n Returns:\n Dictionary with 'default' and 'user' lists of profile names\n \"\"\"\n return {\n \"default\": list(self.default_profiles.keys()),\n \"user\": list(self.user_profiles.keys()),\n }\n\n def profile_exists(self, name: str) -> bool:\n \"\"\"Check if a profile exists (in either default or user profiles).\"\"\"\n return name in self.default_profiles or name in self.user_profiles\n\n def is_user_profile(self, name: str) -> bool:\n \"\"\"Check if a profile is a user-created profile.\"\"\"\n return name in self.user_profiles\n\n def has_user_override(self, name: str) -> bool:\n \"\"\"\n Check if a built-in profile has been overridden by a user profile.\n\n Args:\n name: Profile name to check\n\n Returns:\n True if this is a built-in profile that has a user override\n \"\"\"\n return name in self.default_profiles and name in self.user_profiles\n\n def get_original_default_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get the original default profile without any user overrides.\n\n Args:\n name: Profile name\n\n Returns:\n Original default profile if it exists, None otherwise\n \"\"\"\n if name in self.default_profiles:\n return deepcopy(self.default_profiles[name])\n return None\n\n def reset_to_default(self, name: str) -> bool:\n \"\"\"\n Reset a customized built-in profile to its default settings.\n\n This removes the user override for a built-in profile.\n\n Args:\n name: Profile name to reset\n\n Returns:\n True if reset successfully, False otherwise\n \"\"\"\n # Only reset if this is a built-in profile with a user override\n if self.has_user_override(name):\n return self.delete_user_profile(name)\n return False\n\n def get_profile_count(self) -> Dict[str, int]:\n \"\"\"Get count of profiles by type.\"\"\"\n return {\n \"default\": len(self.default_profiles),\n \"user\": len(self.user_profiles),\n \"total\": len(self.default_profiles) + len(self.user_profiles),\n }\n\n def apply_dynamic_defaults(self, profile_config: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Apply dynamic defaults to a profile configuration.\n\n This function intelligently sets tensor_parallel_size for multi-GPU systems.\n For single GPU systems, it allows vLLM to use its default behavior.\n\n Note: vLLM defaults to using only 1 GPU unless tensor_parallel_size is explicitly set.\n\n Args:\n profile_config: The profile configuration to enhance\n\n Returns:\n Enhanced profile configuration with dynamic defaults applied\n \"\"\"\n config = deepcopy(profile_config)\n\n # Apply dynamic tensor_parallel_size if not specified\n # Note: vLLM defaults to single GPU, so we only set this for multi-GPU systems\n # where tensor parallelism would be beneficial\n if \"tensor_parallel_size\" not in config:\n gpu_count = self._get_gpu_count()\n if gpu_count > 1:\n config[\"tensor_parallel_size\"] = gpu_count\n logger.debug(\n f\"Set tensor_parallel_size to {gpu_count} for multi-GPU system\"\n )\n # For single GPU, let vLLM use its default (no tensor_parallel_size needed)\n\n return config\n\n def _get_gpu_count(self) -> int:\n \"\"\"\n Get the number of available GPUs for tensor parallelism.\n\n Returns:\n Number of GPUs available, defaults to 1 if detection fails\n \"\"\"\n try:\n gpus = get_gpu_info()\n gpu_count = len(gpus) if gpus else 1\n logger.debug(f\"Detected {gpu_count} GPU(s)\")\n return gpu_count\n except Exception as e:\n logger.warning(f\"Failed to detect GPU count, defaulting to 1: {e}\")\n return 1", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 14008}, "tests/test_ollama_support.py::353": {"resolved_imports": ["src/vllm_cli/models/discovery.py", "src/vllm_cli/models/manager.py"], "used_names": ["patch"], "enclosing_function": "test_full_ollama_workflow", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_profiles.py::32": {"resolved_imports": ["src/vllm_cli/config/profiles.py"], "used_names": ["Path", "ProfileManager", "patch"], "enclosing_function": "test_load_default_profiles", "extracted_code": "# Source: src/vllm_cli/config/profiles.py\nclass ProfileManager:\n \"\"\"\n Manages user profiles for vLLM configurations.\n\n Handles creation, retrieval, updating, and deletion of user profiles\n with validation and persistence.\n \"\"\"\n\n def __init__(self, config_dir: Path):\n self.config_dir = config_dir\n self.user_profiles_file = config_dir / \"user_profiles.json\"\n\n # Paths for schema files (packaged with application)\n schema_dir = Path(__file__).parent.parent / \"schemas\"\n self.default_profiles_file = schema_dir / \"default_profiles.json\"\n\n # Load profiles\n self.default_profiles = self._load_default_profiles()\n self.user_profiles = self._load_user_profiles()\n\n def _load_json_file(self, filepath: Path) -> Dict[str, Any]:\n \"\"\"Load a JSON file safely.\"\"\"\n if filepath.exists():\n try:\n with open(filepath, \"r\") as f:\n return json.load(f)\n except Exception as e:\n logger.error(f\"Error loading {filepath}: {e}\")\n return {}\n\n def _save_json_file(self, filepath: Path, data: Dict[str, Any]) -> bool:\n \"\"\"Save data to a JSON file.\"\"\"\n try:\n with open(filepath, \"w\") as f:\n json.dump(data, f, indent=2)\n return True\n except Exception as e:\n logger.error(f\"Error saving {filepath}: {e}\")\n return False\n\n def _load_default_profiles(self) -> Dict[str, Any]:\n \"\"\"Load default built-in profiles.\"\"\"\n profiles = self._load_json_file(self.default_profiles_file)\n return profiles.get(\"profiles\", {})\n\n def _load_user_profiles(self) -> Dict[str, Any]:\n \"\"\"Load user-created custom profiles.\"\"\"\n return self._load_json_file(self.user_profiles_file)\n\n def _save_user_profiles(self) -> bool:\n \"\"\"Save user profiles to file.\"\"\"\n return self._save_json_file(self.user_profiles_file, self.user_profiles)\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n all_profiles = deepcopy(self.default_profiles)\n all_profiles.update(self.user_profiles)\n return all_profiles\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name.\"\"\"\n # Check user profiles first, then default profiles\n if name in self.user_profiles:\n return deepcopy(self.user_profiles[name])\n elif name in self.default_profiles:\n return deepcopy(self.default_profiles[name])\n return None\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"\n Save or update a user profile with validation.\n\n Args:\n name: Profile name\n profile: Profile data to save\n\n Returns:\n True if saved successfully\n\n Raises:\n ProfileError: If profile validation fails or save fails\n \"\"\"\n try:\n # Validate profile structure\n if not isinstance(profile, dict):\n raise ProfileError(\n \"Profile must be a dictionary\",\n profile_name=name,\n error_code=\"INVALID_PROFILE_TYPE\",\n )\n\n # Process LoRA configuration if present\n if \"config\" in profile:\n config = profile[\"config\"]\n\n # Handle LoRA adapters in config\n if \"lora_adapters\" in config:\n # Validate LoRA adapter entries\n lora_adapters = config[\"lora_adapters\"]\n if isinstance(lora_adapters, list):\n # Ensure each adapter has required fields\n for adapter in lora_adapters:\n if not isinstance(adapter, dict):\n continue\n if \"path\" not in adapter and \"name\" in adapter:\n # Try to resolve adapter by name\n adapter[\"path\"] = self._resolve_lora_path(\n adapter[\"name\"]\n )\n\n # Convert to lora_modules format for vLLM\n if lora_adapters:\n config[\"enable_lora\"] = True\n lora_modules = []\n for adapter in lora_adapters:\n if isinstance(adapter, dict):\n name = adapter.get(\"name\", \"adapter\")\n path = adapter.get(\"path\", \"\")\n if path:\n lora_modules.append(f\"{name}={path}\")\n if lora_modules:\n config[\"lora_modules\"] = \" \".join(lora_modules)\n\n # Save the profile\n self.user_profiles[name] = deepcopy(profile)\n\n if not self._save_user_profiles():\n raise ProfileError(\n \"Failed to save profile to disk\",\n profile_name=name,\n error_code=\"PROFILE_SAVE_FAILED\",\n )\n\n logger.info(f\"Successfully saved user profile: {name}\")\n return True\n\n except ProfileError:\n raise\n except Exception as e:\n logger.error(f\"Unexpected error saving profile {name}: {e}\")\n raise ProfileError(\n f\"Unexpected error saving profile: {e}\",\n profile_name=name,\n error_code=\"PROFILE_SAVE_ERROR\",\n ) from e\n\n def _resolve_lora_path(self, adapter_name: str) -> str:\n \"\"\"\n Try to resolve a LoRA adapter path by name.\n\n Args:\n adapter_name: Name of the LoRA adapter\n\n Returns:\n Path to the adapter if found, empty string otherwise\n \"\"\"\n try:\n from ..models import scan_for_lora_adapters\n\n adapters = scan_for_lora_adapters()\n for adapter in adapters:\n if (\n adapter.get(\"name\") == adapter_name\n or adapter.get(\"display_name\") == adapter_name\n ):\n return adapter.get(\"path\", \"\")\n except Exception as e:\n logger.debug(f\"Could not resolve LoRA path for {adapter_name}: {e}\")\n return \"\"\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n if name in self.user_profiles:\n del self.user_profiles[name]\n return self._save_user_profiles()\n return False\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n profile = self.get_profile(profile_name)\n if not profile:\n logger.error(f\"Profile '{profile_name}' not found\")\n return False\n\n export_data = {\"version\": \"1.0\", \"profile\": profile}\n\n try:\n with open(filepath, \"w\") as f:\n json.dump(export_data, f, indent=2)\n logger.info(f\"Profile '{profile_name}' exported to {filepath}\")\n return True\n except Exception as e:\n logger.error(f\"Error exporting profile: {e}\")\n return False\n\n def import_profile(\n self,\n filepath: Path,\n new_name: Optional[str] = None,\n validate_config_func: Optional[Callable] = None,\n ) -> bool:\n \"\"\"\n Import a profile from a JSON file with comprehensive validation.\n\n Args:\n filepath: Path to the profile file\n new_name: Optional new name for the profile\n validate_config_func: Optional function to validate profile config\n\n Returns:\n True if imported successfully\n\n Raises:\n ProfileError: If import fails for any reason\n \"\"\"\n try:\n # Check file exists\n if not filepath.exists():\n raise ProfileError(\n f\"Profile file not found: {filepath}\",\n error_code=\"PROFILE_FILE_NOT_FOUND\",\n )\n\n # Load and parse file\n try:\n with open(filepath, \"r\") as f:\n data = json.load(f)\n except json.JSONDecodeError as e:\n raise ProfileError(\n f\"Invalid JSON in profile file: {e}\",\n error_code=\"PROFILE_INVALID_JSON\",\n ) from e\n\n # Validate file format\n if not isinstance(data, dict) or \"profile\" not in data:\n raise ProfileError(\n \"Invalid profile file format - missing 'profile' key\",\n error_code=\"PROFILE_INVALID_FORMAT\",\n )\n\n profile = data[\"profile\"]\n name = new_name or profile.get(\"name\", filepath.stem)\n\n # Validate profile configuration if function provided\n if validate_config_func and \"config\" in profile:\n is_valid, errors = validate_config_func(profile[\"config\"])\n if not is_valid:\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n # Save the profile\n return self.save_user_profile(name, profile)\n\n except ProfileError:\n raise\n except Exception as e:\n logger.error(f\"Unexpected error importing profile from {filepath}: {e}\")\n raise ProfileError(\n f\"Failed to import profile: {e}\", error_code=\"PROFILE_IMPORT_ERROR\"\n ) from e\n\n def list_profile_names(self) -> Dict[str, List[str]]:\n \"\"\"\n List all profile names categorized by type.\n\n Returns:\n Dictionary with 'default' and 'user' lists of profile names\n \"\"\"\n return {\n \"default\": list(self.default_profiles.keys()),\n \"user\": list(self.user_profiles.keys()),\n }\n\n def profile_exists(self, name: str) -> bool:\n \"\"\"Check if a profile exists (in either default or user profiles).\"\"\"\n return name in self.default_profiles or name in self.user_profiles\n\n def is_user_profile(self, name: str) -> bool:\n \"\"\"Check if a profile is a user-created profile.\"\"\"\n return name in self.user_profiles\n\n def has_user_override(self, name: str) -> bool:\n \"\"\"\n Check if a built-in profile has been overridden by a user profile.\n\n Args:\n name: Profile name to check\n\n Returns:\n True if this is a built-in profile that has a user override\n \"\"\"\n return name in self.default_profiles and name in self.user_profiles\n\n def get_original_default_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get the original default profile without any user overrides.\n\n Args:\n name: Profile name\n\n Returns:\n Original default profile if it exists, None otherwise\n \"\"\"\n if name in self.default_profiles:\n return deepcopy(self.default_profiles[name])\n return None\n\n def reset_to_default(self, name: str) -> bool:\n \"\"\"\n Reset a customized built-in profile to its default settings.\n\n This removes the user override for a built-in profile.\n\n Args:\n name: Profile name to reset\n\n Returns:\n True if reset successfully, False otherwise\n \"\"\"\n # Only reset if this is a built-in profile with a user override\n if self.has_user_override(name):\n return self.delete_user_profile(name)\n return False\n\n def get_profile_count(self) -> Dict[str, int]:\n \"\"\"Get count of profiles by type.\"\"\"\n return {\n \"default\": len(self.default_profiles),\n \"user\": len(self.user_profiles),\n \"total\": len(self.default_profiles) + len(self.user_profiles),\n }\n\n def apply_dynamic_defaults(self, profile_config: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Apply dynamic defaults to a profile configuration.\n\n This function intelligently sets tensor_parallel_size for multi-GPU systems.\n For single GPU systems, it allows vLLM to use its default behavior.\n\n Note: vLLM defaults to using only 1 GPU unless tensor_parallel_size is explicitly set.\n\n Args:\n profile_config: The profile configuration to enhance\n\n Returns:\n Enhanced profile configuration with dynamic defaults applied\n \"\"\"\n config = deepcopy(profile_config)\n\n # Apply dynamic tensor_parallel_size if not specified\n # Note: vLLM defaults to single GPU, so we only set this for multi-GPU systems\n # where tensor parallelism would be beneficial\n if \"tensor_parallel_size\" not in config:\n gpu_count = self._get_gpu_count()\n if gpu_count > 1:\n config[\"tensor_parallel_size\"] = gpu_count\n logger.debug(\n f\"Set tensor_parallel_size to {gpu_count} for multi-GPU system\"\n )\n # For single GPU, let vLLM use its default (no tensor_parallel_size needed)\n\n return config\n\n def _get_gpu_count(self) -> int:\n \"\"\"\n Get the number of available GPUs for tensor parallelism.\n\n Returns:\n Number of GPUs available, defaults to 1 if detection fails\n \"\"\"\n try:\n gpus = get_gpu_info()\n gpu_count = len(gpus) if gpus else 1\n logger.debug(f\"Detected {gpu_count} GPU(s)\")\n return gpu_count\n except Exception as e:\n logger.warning(f\"Failed to detect GPU count, defaulting to 1: {e}\")\n return 1", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 14008}, "tests/proxy/test_manager.py::259": {"resolved_imports": ["src/vllm_cli/proxy/manager.py", "src/vllm_cli/proxy/models.py"], "used_names": ["MagicMock", "patch"], "enclosing_function": "test_start_all_models_no_wait", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/proxy/test_server.py::198": {"resolved_imports": ["src/vllm_cli/proxy/models.py", "src/vllm_cli/proxy/registry.py", "src/vllm_cli/proxy/server.py"], "used_names": [], "enclosing_function": "test_request_counting", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/proxy/test_router.py::28": {"resolved_imports": ["src/vllm_cli/proxy/router.py"], "used_names": [], "enclosing_function": "test_add_backend", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_config_manager.py::104": {"resolved_imports": ["src/vllm_cli/config/manager.py"], "used_names": ["ConfigManager", "patch", "yaml"], "enclosing_function": "test_get_last_config", "extracted_code": "# Source: src/vllm_cli/config/manager.py\nclass ConfigManager:\n \"\"\"\n Enhanced configuration manager with comprehensive validation support.\n\n This class manages configuration files, profiles, and validation using\n the new validation framework. It provides a clean API for configuration\n operations while ensuring data integrity through comprehensive validation.\n\n Attributes:\n config_dir: Directory for configuration files\n validation_registry: Registry of validation rules\n compatibility_validator: Validator for parameter combinations\n \"\"\"\n\n def __init__(self):\n # Paths for configuration files\n self.config_dir = Path.home() / \".config\" / \"vllm-cli\"\n self.config_file = self.config_dir / \"config.yaml\"\n\n # Ensure config directory exists\n self.config_dir.mkdir(parents=True, exist_ok=True)\n\n # Initialize sub-managers\n self.schema_manager = SchemaManager()\n self.profile_manager = ProfileManager(self.config_dir)\n self.persistence_manager = PersistenceManager()\n self.shortcut_manager = ShortcutManager(self.config_dir)\n\n # Initialize validation system\n self.validation_registry = create_vllm_validation_registry()\n self.compatibility_validator = create_compatibility_validator(\n self.validation_registry\n )\n\n # Load main configuration\n self.config = self._load_config()\n\n def _load_config(self) -> Dict[str, Any]:\n \"\"\"Load main configuration file (legacy YAML support).\"\"\"\n return self.persistence_manager.load_yaml_file(self.config_file)\n\n def _save_config(self) -> None:\n \"\"\"Save main configuration file.\"\"\"\n self.persistence_manager.save_yaml_file(self.config_file, self.config)\n\n def get_argument_info(self, arg_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get detailed information about a specific argument.\"\"\"\n return self.schema_manager.get_argument_info(arg_name)\n\n def get_arguments_by_category(self, category: str) -> List[Dict[str, Any]]:\n \"\"\"Get all arguments belonging to a specific category.\"\"\"\n return self.schema_manager.get_arguments_by_category(category)\n\n def get_category_info(self, category: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get information about a specific category.\"\"\"\n return self.schema_manager.get_category_info(category)\n\n def get_ordered_categories(self) -> List[Tuple[str, Dict[str, Any]]]:\n \"\"\"Get categories ordered by their display order.\"\"\"\n return self.schema_manager.get_ordered_categories()\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n return self.profile_manager.get_all_profiles()\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name with dynamic defaults applied.\"\"\"\n profile = self.profile_manager.get_profile(name)\n if profile and \"config\" in profile:\n # Apply dynamic defaults to the profile configuration\n profile[\"config\"] = self.profile_manager.apply_dynamic_defaults(\n profile[\"config\"]\n )\n return profile\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"Save or update a user profile with validation.\"\"\"\n # Validate profile configuration if present\n if \"config\" in profile:\n is_valid, errors = self.validate_config(profile[\"config\"])\n if not is_valid:\n from ..errors import ProfileError\n\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n return self.profile_manager.save_user_profile(name, profile)\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n return self.profile_manager.delete_user_profile(name)\n\n @property\n def default_profiles(self) -> Dict[str, Any]:\n \"\"\"Get default profiles.\"\"\"\n return self.profile_manager.default_profiles\n\n @property\n def user_profiles(self) -> Dict[str, Any]:\n \"\"\"Get user profiles.\"\"\"\n return self.profile_manager.user_profiles\n\n def validate_config(self, config: Dict[str, Any]) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate a configuration using the new validation framework.\n\n This method uses the comprehensive validation system to check\n configuration values, types, ranges, and dependencies.\n\n Args:\n config: Configuration dictionary to validate\n\n Returns:\n Tuple of (is_valid, list_of_error_messages)\n\n Raises:\n ConfigurationError: If validation system fails\n \"\"\"\n try:\n # Use new validation system\n result = self.validation_registry.validate_config(config)\n\n # Convert validation errors to string messages for backward compatibility\n error_messages = result.get_error_messages()\n\n # Add warnings if any\n if result.warnings:\n for warning in result.warnings:\n logger.warning(f\"Configuration warning: {warning}\")\n\n return result.is_valid(), error_messages\n\n except Exception as e:\n logger.error(f\"Error during configuration validation: {e}\")\n raise ConfigurationError(\n f\"Validation system error: {e}\", error_code=\"VALIDATION_SYSTEM_ERROR\"\n ) from e\n\n def validate_argument_combination(\n self, config: Dict[str, Any]\n ) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate that argument combinations are compatible using the new compatibility validator.\n\n Args:\n config: Configuration dictionary to check for compatibility\n\n Returns:\n Tuple of (is_valid, list_of_warnings_or_errors)\n \"\"\"\n try:\n issues = self.compatibility_validator.validate_compatibility(config)\n\n warnings = []\n errors = []\n\n for issue in issues:\n message = issue[\"message\"]\n if issue[\"severity\"] == \"error\":\n errors.append(message)\n else:\n warnings.append(message)\n\n # Log warnings\n for warning in warnings:\n logger.warning(f\"Configuration compatibility warning: {warning}\")\n\n # Return all issues as warnings for backward compatibility\n # (errors are treated as warnings in the legacy interface)\n all_issues = errors + warnings\n\n return len(errors) == 0, all_issues\n\n except Exception as e:\n logger.error(f\"Error during compatibility validation: {e}\")\n return False, [f\"Compatibility validation error: {e}\"]\n\n def build_cli_args(self, config: Dict[str, Any]) -> List[str]:\n \"\"\"\n Build command-line arguments from a configuration dictionary.\n\n Only includes arguments that are explicitly set in the config.\n Handles special cases like LoRA modules.\n \"\"\"\n args = []\n\n # Special handling for model (positional argument)\n # Check if this is a GGUF/Ollama configuration\n if (\n isinstance(config.get(\"model\"), dict)\n and \"quantization\" in config[\"model\"]\n and config[\"model\"][\"quantization\"] == \"gguf\"\n ):\n # Extract GGUF model config\n gguf_config = config[\"model\"]\n model_path = gguf_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", model_path])\n\n # Set quantization to gguf\n config[\"quantization\"] = \"gguf\"\n\n # Add served-model-name if provided (for Ollama models)\n if \"served_model_name\" in gguf_config:\n config[\"served_model_name\"] = gguf_config[\"served_model_name\"]\n logger.info(\n f\"Configuring GGUF model: {model_path} as {gguf_config['served_model_name']}\"\n )\n else:\n logger.info(f\"Configuring GGUF model: {model_path}\")\n\n # Check if this is a LoRA configuration\n elif (\n isinstance(config.get(\"model\"), dict) and \"lora_modules\" in config[\"model\"]\n ):\n # Extract base model and LoRA config\n lora_config = config[\"model\"]\n base_model = lora_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", base_model])\n\n # Enable LoRA support when modules are present\n args.append(\"--enable-lora\")\n\n # Track maximum rank for all LoRA modules\n max_rank = 16 # Default minimum\n\n # Add LoRA modules\n for lora in lora_config.get(\"lora_modules\", []):\n lora_path = lora.get(\"path\", \"\")\n if lora_path:\n # vLLM expects --lora-modules with name=path format\n lora_name = lora.get(\"name\", \"adapter\")\n args.extend([\"--lora-modules\", f\"{lora_name}={lora_path}\"])\n\n # Track maximum rank\n lora_rank = lora.get(\"rank\", 16)\n max_rank = max(max_rank, lora_rank)\n\n # Add max-lora-rank parameter\n args.extend([\"--max-lora-rank\", str(max_rank)])\n\n elif \"model\" in config:\n args.extend([\"serve\", config[\"model\"]])\n\n # Handle lora_modules if present as a string (from CLI)\n if \"lora_modules\" in config and config[\"lora_modules\"]:\n # Enable LoRA support\n if \"--enable-lora\" not in args:\n args.append(\"--enable-lora\")\n\n # Parse and add LoRA modules\n lora_modules_str = config[\"lora_modules\"]\n if isinstance(lora_modules_str, str):\n # Split by space and add each module\n for module in lora_modules_str.split():\n args.extend([\"--lora-modules\", module])\n\n # Add max-lora-rank if not already added\n # Use a safe default of 64 which should cover most LoRA adapters\n if \"--max-lora-rank\" not in args:\n # Check if max_lora_rank is explicitly set in config\n if \"max_lora_rank\" not in config:\n args.extend([\"--max-lora-rank\", \"64\"])\n\n for arg_name, value in config.items():\n # Skip special keys and None values\n if (\n arg_name in [\"model\", \"name\", \"description\", \"icon\", \"lora_modules\"]\n or value is None\n ):\n continue\n\n arg_info = self.schema_manager.get_argument_info(arg_name)\n if not arg_info:\n logger.warning(f\"Unknown argument in config: {arg_name}\")\n continue\n\n cli_flag = arg_info.get(\"cli_flag\")\n if not cli_flag:\n continue\n\n arg_type = arg_info.get(\"type\")\n\n if arg_type == \"boolean\":\n if value: # Only add flag if True\n args.append(cli_flag)\n elif arg_type in [\"integer\", \"float\", \"string\", \"choice\"]:\n args.extend([cli_flag, str(value)])\n else:\n logger.warning(f\"Unknown argument type for {arg_name}: {arg_type}\")\n\n return args\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n return self.profile_manager.export_profile(profile_name, filepath)\n\n def import_profile(self, filepath: Path, new_name: Optional[str] = None) -> bool:\n \"\"\"Import a profile from a JSON file with comprehensive validation.\"\"\"\n return self.profile_manager.import_profile(\n filepath, new_name, self.validate_config\n )\n\n def get_last_config(self) -> Optional[Dict[str, Any]]:\n \"\"\"Get the last used server configuration.\"\"\"\n return self.config.get(\"last_config\")\n\n def save_last_config(self, config: Dict[str, Any]) -> None:\n \"\"\"Save the last used server configuration.\"\"\"\n self.config[\"last_config\"] = config\n self._save_config()\n\n def get_recent_models(self, limit: int = 5) -> List[str]:\n \"\"\"Get recently used models.\"\"\"\n return self.config.get(\"recent_models\", [])[:limit]\n\n def add_recent_model(self, model: str) -> None:\n \"\"\"Add a model to recent models list.\"\"\"\n recent = self.config.get(\"recent_models\", [])\n if model in recent:\n recent.remove(model)\n recent.insert(0, model)\n self.config[\"recent_models\"] = recent[:10] # Keep only last 10\n self._save_config()\n\n def clear_cache(self) -> None:\n \"\"\"Clear cached data.\"\"\"\n cache_file = self.config_dir / \"cache.json\"\n if cache_file.exists():\n cache_file.unlink()\n self.config.pop(\"last_config\", None)\n self.config.pop(\"recent_models\", None)\n self._save_config()\n logger.info(\"Cache cleared\")\n\n def get_server_defaults(self) -> Dict[str, Any]:\n \"\"\"Get default server settings.\"\"\"\n return self.config.get(\n \"server_defaults\",\n {\n \"default_port\": 8000,\n \"auto_restart\": False,\n \"log_level\": \"info\",\n \"cleanup_on_exit\": True, # Default to cleaning up servers on exit\n },\n )\n\n def save_server_defaults(self, defaults: Dict[str, Any]) -> None:\n \"\"\"Save default server settings.\"\"\"\n self.config[\"server_defaults\"] = defaults\n self._save_config()\n\n def get_ui_preferences(self) -> Dict[str, Any]:\n \"\"\"Get UI preferences including progress bar style and log display settings.\"\"\"\n return self.config.get(\n \"ui_preferences\",\n {\n \"progress_bar_style\": \"blocks\", # Default style\n \"show_gpu_in_monitor\": True,\n \"log_lines_startup\": 50, # Number of log lines to show during startup\n \"log_lines_monitor\": 50, # Number of log lines to show in server monitor\n \"startup_refresh_rate\": 4.0, # Hz for startup log refresh\n \"monitor_refresh_rate\": 1.0, # Hz for monitor log refresh\n },\n )\n\n def save_ui_preferences(self, preferences: Dict[str, Any]) -> None:\n \"\"\"Save UI preferences.\"\"\"\n self.config[\"ui_preferences\"] = preferences\n self._save_config()\n\n # Shortcut management methods\n def get_all_shortcuts(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all shortcuts.\"\"\"\n return self.shortcut_manager.get_all_shortcuts()\n\n def get_shortcut(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific shortcut by name.\"\"\"\n return self.shortcut_manager.get_shortcut(name)\n\n def save_shortcut(self, name: str, shortcut_data: Dict[str, Any]) -> bool:\n \"\"\"Save or update a shortcut.\"\"\"\n return self.shortcut_manager.save_shortcut(name, shortcut_data)\n\n def delete_shortcut(self, name: str) -> bool:\n \"\"\"Delete a shortcut.\"\"\"\n return self.shortcut_manager.delete_shortcut(name)\n\n def list_shortcuts(self) -> List[Dict[str, Any]]:\n \"\"\"List all shortcuts with summary information.\"\"\"\n return self.shortcut_manager.list_shortcuts()\n\n def get_recent_shortcuts(self, limit: int = 5) -> List[Dict[str, Any]]:\n \"\"\"Get recently used shortcuts.\"\"\"\n return self.shortcut_manager.get_recent_shortcuts(limit)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 15704}, "tests/test_ollama_integration_fixed.py::93": {"resolved_imports": ["src/vllm_cli/models/cache.py", "src/vllm_cli/models/manager.py"], "used_names": ["ModelCache"], "enclosing_function": "test_cache_ttl_bypass_on_refresh", "extracted_code": "# Source: src/vllm_cli/models/cache.py\nclass ModelCache:\n \"\"\"\n Cache for model discovery results.\n\n Provides time-based caching of model listings to avoid expensive\n directory scanning operations when model data is accessed frequently.\n \"\"\"\n\n def __init__(self, ttl_seconds: float = 30.0):\n \"\"\"\n Initialize model cache.\n\n Args:\n ttl_seconds: Time-to-live for cached data in seconds\n \"\"\"\n self.ttl_seconds = ttl_seconds\n self._cache: Optional[Tuple[float, List[Dict[str, Any]]]] = None\n self._stats = {\"hits\": 0, \"misses\": 0, \"updates\": 0}\n\n def get_cached_models(self) -> Optional[List[Dict[str, Any]]]:\n \"\"\"\n Get cached model list if still valid.\n\n Returns:\n List of cached models if cache is valid, None if expired or empty\n \"\"\"\n if self._cache is None:\n self._stats[\"misses\"] += 1\n return None\n\n cache_time, cached_data = self._cache\n\n # Check if cache is still valid\n if time.time() - cache_time < self.ttl_seconds:\n self._stats[\"hits\"] += 1\n logger.debug(f\"Cache hit: returning {len(cached_data)} cached models\")\n return cached_data.copy() # Return copy to prevent modification\n else:\n # Cache expired\n self._stats[\"misses\"] += 1\n logger.debug(\"Cache expired\")\n self._cache = None\n return None\n\n def cache_models(self, models: List[Dict[str, Any]]) -> None:\n \"\"\"\n Cache a list of models.\n\n Args:\n models: List of model dictionaries to cache\n \"\"\"\n self._cache = (time.time(), models.copy())\n self._stats[\"updates\"] += 1\n logger.debug(f\"Cached {len(models)} models\")\n\n def clear_cache(self) -> None:\n \"\"\"Clear the model cache.\"\"\"\n self._cache = None\n # Increment misses to reflect that the next access will be a miss\n self._stats[\"misses\"] += 1\n logger.debug(\"Model cache cleared\")\n\n def is_cached(self) -> bool:\n \"\"\"\n Check if there is valid cached data.\n\n Returns:\n True if cache contains valid data, False otherwise\n \"\"\"\n if self._cache is None:\n return False\n\n cache_time, _ = self._cache\n return time.time() - cache_time < self.ttl_seconds\n\n def get_cache_age(self) -> Optional[float]:\n \"\"\"\n Get the age of cached data in seconds.\n\n Returns:\n Age in seconds if cache exists, None if no cache\n \"\"\"\n if self._cache is None:\n return None\n\n cache_time, _ = self._cache\n return time.time() - cache_time\n\n def get_cache_stats(self) -> Dict[str, Any]:\n \"\"\"\n Get cache statistics.\n\n Returns:\n Dictionary with cache performance statistics\n \"\"\"\n total_requests = self._stats[\"hits\"] + self._stats[\"misses\"]\n hit_rate = (\n (self._stats[\"hits\"] / total_requests * 100) if total_requests > 0 else 0\n )\n\n stats = {\n \"hits\": self._stats[\"hits\"],\n \"misses\": self._stats[\"misses\"],\n \"updates\": self._stats[\"updates\"],\n \"total_requests\": total_requests,\n \"hit_rate_percent\": round(hit_rate, 2),\n \"is_cached\": self.is_cached(),\n \"cache_age_seconds\": self.get_cache_age(),\n \"ttl_seconds\": self.ttl_seconds,\n }\n\n if self._cache:\n _, cached_data = self._cache\n stats[\"cached_models_count\"] = len(cached_data)\n else:\n stats[\"cached_models_count\"] = 0\n\n return stats\n\n def get_stats(self) -> Dict[str, Any]:\n \"\"\"\n Alias for get_cache_stats() for backward compatibility.\n\n Returns:\n Dictionary with cache performance statistics\n \"\"\"\n return self.get_cache_stats()\n\n def reset_stats(self) -> None:\n \"\"\"Reset cache statistics.\"\"\"\n self._stats = {\"hits\": 0, \"misses\": 0, \"updates\": 0}\n logger.debug(\"Cache statistics reset\")\n\n def set_ttl(self, ttl_seconds: float) -> None:\n \"\"\"\n Set new TTL for cache.\n\n Args:\n ttl_seconds: New time-to-live in seconds\n \"\"\"\n old_ttl = self.ttl_seconds\n self.ttl_seconds = ttl_seconds\n logger.debug(f\"Cache TTL changed from {old_ttl}s to {ttl_seconds}s\")\n\n def get_cached_model_count(self) -> int:\n \"\"\"\n Get the number of models currently cached.\n\n Returns:\n Number of cached models, 0 if no cache\n \"\"\"\n if self._cache is None:\n return 0\n\n _, cached_data = self._cache\n return len(cached_data)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 4761}, "tests/test_environment_variables.py::213": {"resolved_imports": ["src/vllm_cli/config/manager.py", "src/vllm_cli/server/manager.py"], "used_names": ["Mock", "VLLMServer", "patch"], "enclosing_function": "test_universal_env_applied", "extracted_code": "# Source: src/vllm_cli/server/manager.py\nclass VLLMServer:\n \"\"\"\n Manages a vLLM server instance with comprehensive lifecycle control.\n\n This class handles the complete lifecycle of a vLLM server including\n configuration, process management, logging, monitoring, and cleanup.\n It supports both programmatically started servers and external server\n detection and management.\n\n Attributes:\n config: Server configuration dictionary\n model: Model name being served\n port: Port number the server is listening on\n process: Subprocess or external process reference\n log_file: File handle for server logs\n log_queue: Thread-safe queue for log lines\n log_thread: Background thread for log monitoring\n start_time: Timestamp when server was started\n log_path: Path to the server's log file\n \"\"\"\n\n def __init__(self, config: Dict[str, Any]) -> None:\n \"\"\"\n Initialize a vLLM server instance.\n\n Sets up the server configuration, logging infrastructure, and\n prepares the instance for server lifecycle management.\n\n Args:\n config: Server configuration dictionary containing model name,\n port, and other vLLM-specific parameters\n \"\"\"\n self.config: Dict[str, Any] = config\n\n # Extract model name - handle both string and dict (LoRA config) formats\n model_config = config.get(\"model\", \"unknown\")\n if isinstance(model_config, dict):\n # LoRA configuration - extract base model name\n self.model: str = model_config.get(\"model\", \"unknown\")\n else:\n # Regular string model name\n self.model: str = model_config\n\n self.port: int = config.get(\"port\", 8000)\n self.process: Optional[Union[subprocess.Popen, Any]] = None\n self.log_file: Optional[TextIO] = None\n self.log_queue: Queue[str] = Queue()\n self.log_thread: Optional[Thread] = None\n self.start_time: Optional[datetime] = None\n self.log_path: Path\n self._recent_logs: List[str] = []\n\n # Setup logging\n log_dir = Path.home() / \".vllm-cli\" / \"logs\"\n log_dir.mkdir(parents=True, exist_ok=True)\n\n timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n self.log_path = log_dir / f\"vllm_{self.model.replace('/', '_')}_{timestamp}.log\"\n\n def start(self) -> bool:\n \"\"\"\n Start the vLLM server.\n\n Returns:\n True if server started successfully, False otherwise\n \"\"\"\n if self.is_running():\n logger.warning(f\"Server already running for {self.model}\")\n return False\n\n try:\n # Build command - run directly without conda wrapper\n full_cmd = self._build_command()\n\n logger.info(f\"Starting vLLM server with command: {' '.join(full_cmd)}\")\n\n # Open log file for writing\n self.log_file = open(self.log_path, \"w\", buffering=1)\n\n # Start with parent environment\n env = os.environ.copy()\n # Note: No longer forcing PYTHONUNBUFFERED=1, let user control it\n\n # Layer 1: Apply universal environment variables from settings\n config_manager = ConfigManager()\n universal_env = config_manager.config.get(\"universal_environment\", {})\n if universal_env:\n logger.info(\n f\"Applying {len(universal_env)} universal environment variable(s)\"\n )\n for key, value in universal_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting universal {key}={value}\")\n else:\n logger.debug(f\"Setting universal {key}=\")\n\n # Layer 2: Apply profile environment variables (override universal)\n profile_env = self.config.get(\"profile_environment\", {})\n if profile_env:\n logger.info(\n f\"Applying {len(profile_env)} profile environment variable(s)\"\n )\n for key, value in profile_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting profile {key}={value}\")\n else:\n logger.debug(f\"Setting profile {key}=\")\n\n # Handle GPU device selection via CUDA_VISIBLE_DEVICES\n # This overrides any CUDA_VISIBLE_DEVICES from the profile\n if self.config.get(\"device\"):\n device_str = str(self.config[\"device\"])\n env[\"CUDA_VISIBLE_DEVICES\"] = device_str\n logger.info(f\"Setting CUDA_VISIBLE_DEVICES={device_str}\")\n\n # If using specific GPUs, adjust tensor parallel size if needed\n device_list = [d.strip() for d in device_str.split(\",\")]\n num_devices = len(device_list)\n\n # Check if tensor_parallel_size is set and compatible\n if self.config.get(\"tensor_parallel_size\"):\n tp_size = self.config[\"tensor_parallel_size\"]\n if tp_size > num_devices:\n logger.warning(\n f\"tensor_parallel_size ({tp_size}) > number of selected devices ({num_devices}). \"\n f\"Adjusting tensor_parallel_size to {num_devices}\"\n )\n self.config[\"tensor_parallel_size\"] = num_devices\n elif num_devices % tp_size != 0:\n logger.warning(\n f\"Number of GPUs ({num_devices}) is not evenly divisible by \"\n f\"tensor_parallel_size ({tp_size}). This may lead to inefficient GPU utilization. \"\n f\"Consider using tensor_parallel_size of: \"\n f\"{', '.join(str(i) for i in range(1, num_devices + 1) if num_devices % i == 0)}\"\n )\n\n # Add HuggingFace token if configured\n config_manager = ConfigManager()\n hf_token = config_manager.config.get(\"hf_token\")\n if hf_token:\n env[\"HF_TOKEN\"] = hf_token\n env[\"HUGGING_FACE_HUB_TOKEN\"] = hf_token # Some tools use this variant\n logger.info(\"HuggingFace token configured for server\")\n\n # Enable development mode for sleep endpoints if sleep mode is enabled\n if self.config.get(\"enable_sleep_mode\"):\n env[\"VLLM_SERVER_DEV_MODE\"] = \"1\"\n logger.info(\"Sleep mode enabled with development endpoints\")\n\n # Start the process with proper pipe configuration\n # Use start_new_session=True to create a new process group\n # This prevents the child process from receiving Ctrl+C signals\n self.process = subprocess.Popen(\n full_cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n text=True,\n bufsize=0, # Unbuffered\n universal_newlines=True,\n env=env,\n start_new_session=True, # Create new process group to isolate from parent signals\n )\n\n # Start log monitoring thread\n self._start_log_monitor()\n\n # Set start time and add to registry\n self.start_time = datetime.now()\n from .process import add_server\n\n add_server(self)\n\n # Return immediately - let the UI monitor the startup\n logger.info(\n f\"vLLM server process launched for {self.model} on port {self.port}\"\n )\n return True\n\n except Exception as e:\n logger.error(f\"Error starting vLLM server: {e}\")\n return False\n\n def _build_command(self) -> List[str]:\n \"\"\"\n Build the vLLM command from configuration using the schema.\n\n Returns:\n List of command arguments\n \"\"\"\n # Use the new ConfigManager to build CLI args\n config_manager = ConfigManager()\n\n # Start with the vllm command\n cmd = [\"vllm\"]\n\n # Add the arguments built from schema\n cli_args = config_manager.build_cli_args(self.config)\n cmd.extend(cli_args)\n\n # Handle extra_args if present (backward compatibility)\n if self.config.get(\"extra_args\"):\n self._add_extra_args_to_command(cmd)\n\n logger.debug(f\"Built command: {' '.join(cmd)}\")\n return cmd\n\n def _add_extra_args_to_command(self, cmd: List[str]) -> None:\n \"\"\"\n Add extra arguments to the vLLM command.\n\n Args:\n cmd: Command list to extend with extra arguments\n \"\"\"\n try:\n extra_args = shlex.split(self.config[\"extra_args\"])\n if extra_args:\n logger.info(f\"Adding extra arguments: {extra_args}\")\n cmd.extend(extra_args)\n except ValueError as e:\n logger.warning(f\"Failed to parse extra_args: {e}\")\n\n def _start_log_monitor(self) -> None:\n \"\"\"\n Start a thread to monitor log output from the vLLM server process.\n\n Creates a daemon thread that continuously reads stdout/stderr from\n the server process, writes to log files, and queues log lines for\n real-time display in the UI.\n \"\"\"\n self.log_thread = Thread(target=self._log_monitor_worker, daemon=True)\n self.log_thread.start()\n\n def _log_monitor_worker(self) -> None:\n \"\"\"\n Worker function for log monitoring thread.\n\n Continuously reads log output from the server process and handles\n file writing and queue management for UI display.\n \"\"\"\n try:\n self.log_queue.put(\"Starting vLLM server process...\")\n\n while self._should_continue_monitoring():\n if self._process_log_line():\n continue\n else:\n # No line read, check if process still running\n if self.process and self.process.poll() is not None:\n break\n time.sleep(0.01) # Small sleep to prevent busy waiting\n\n except Exception as e:\n logger.error(f\"Error in log monitor: {e}\")\n self.log_queue.put(f\"Log monitoring error: {e}\")\n\n def _should_continue_monitoring(self) -> bool:\n \"\"\"\n Check if log monitoring should continue.\n\n Returns:\n True if monitoring should continue, False otherwise\n \"\"\"\n return (\n self.is_running()\n and self.process\n and hasattr(self.process, \"stdout\")\n and self.process.stdout\n )\n\n def _process_log_line(self) -> bool:\n \"\"\"\n Process a single log line from the server output.\n\n Reads one line from the process stdout, writes it to the log file,\n and adds it to the queue for UI display after filtering and formatting.\n\n Returns:\n True if a line was processed, False if no line was available\n \"\"\"\n if not (self.process and self.process.stdout):\n return False\n\n line = self.process.stdout.readline()\n if not line:\n return False\n\n # Write to log file\n self._write_to_log_file(line)\n\n # Process for UI display\n line_stripped = line.strip()\n if line_stripped and self._should_display_log_line(line_stripped):\n # Truncate overly long lines\n if len(line_stripped) > 200:\n line_stripped = line_stripped[:197] + \"...\"\n\n self.log_queue.put(line_stripped)\n logger.debug(f\"Log captured: {line_stripped[:50]}...\")\n\n return True\n\n def _write_to_log_file(self, line: str) -> None:\n \"\"\"\n Write a log line to the log file.\n\n Args:\n line: Log line to write\n \"\"\"\n if self.log_file and not self.log_file.closed:\n self.log_file.write(line)\n self.log_file.flush()\n\n def _should_display_log_line(self, line: str) -> bool:\n \"\"\"\n Determine if a log line should be displayed in the UI.\n\n Filters out certain system messages that are not useful for users.\n\n Args:\n line: Stripped log line to check\n\n Returns:\n True if the line should be displayed, False otherwise\n \"\"\"\n # Filter out conda activation and system messages\n filtered_messages = [\n \"Activated CUDA\",\n \"Using nvcc from:\",\n \"Cuda compilation tools\",\n ]\n return not any(skip in line for skip in filtered_messages)\n\n def stop(self) -> bool:\n \"\"\"\n Stop the vLLM server.\n\n Returns:\n True if server stopped successfully, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n try:\n # Check if this is an external server\n if hasattr(self.process, \"terminate\"):\n # Normal subprocess\n # Since we created a new session, we need to terminate the entire process group\n try:\n # Get the process group ID (pgid)\n # Since we used start_new_session=True, the pgid is the same as the pid\n pgid = self.process.pid\n\n # Send SIGTERM to the entire process group for graceful shutdown\n logger.info(f\"Sending SIGTERM to process group {pgid}\")\n os.killpg(pgid, signal.SIGTERM)\n\n # Wait for process to terminate\n try:\n self.process.wait(timeout=10)\n logger.info(f\"Process group {pgid} terminated gracefully\")\n except subprocess.TimeoutExpired:\n # Force kill if not terminated\n logger.warning(\n f\"Process group {pgid} did not terminate, sending SIGKILL\"\n )\n os.killpg(pgid, signal.SIGKILL)\n self.process.wait()\n logger.info(f\"Process group {pgid} force killed\")\n\n except ProcessLookupError:\n # Process already dead\n logger.info(\"Process already terminated\")\n except PermissionError as e:\n # Fall back to terminating just the process\n logger.warning(\n f\"Permission denied for process group kill: {e}, falling back to process termination\"\n )\n self.process.terminate()\n try:\n self.process.wait(timeout=10)\n except subprocess.TimeoutExpired:\n self.process.kill()\n self.process.wait()\n elif hasattr(self.process, \"pid\"):\n # External server - kill entire process group or individual process\n try:\n pgid = self.process.pid\n killed = False\n\n # First attempt: try to kill process group\n try:\n os.killpg(pgid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process group {pgid}\")\n killed = True\n except (OSError, ProcessLookupError) as e:\n # Process group kill failed, try individual process\n logger.debug(\n f\"Process group kill failed: {e}, trying individual process\"\n )\n try:\n # Ensure pid is an integer (handle Mock objects)\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process {self.process.pid}\")\n killed = True\n except ProcessLookupError:\n # Process already dead\n logger.info(\n f\"Process {self.process.pid} already terminated\"\n )\n except OSError as e:\n logger.warning(\n f\"Failed to send SIGTERM to {self.process.pid}: {e}\"\n )\n\n if killed:\n # Wait for graceful shutdown\n time.sleep(2)\n\n # Check if still running and force kill if needed\n if self.is_running():\n try:\n os.killpg(pgid, signal.SIGKILL)\n logger.info(f\"Force killed process group {pgid}\")\n except (OSError, ProcessLookupError):\n # Process group kill failed, try individual\n try:\n # Ensure pid is an integer (handle Mock objects in tests)\n if hasattr(self.process, \"pid\"):\n try:\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGKILL)\n logger.info(f\"Force killed process {pid}\")\n except (TypeError, ValueError):\n # PID is not a valid integer (might be Mock)\n pass\n except ProcessLookupError:\n pass # Already dead\n except OSError as e:\n logger.error(\n f\"Failed to force kill {self.process.pid}: {e}\"\n )\n\n except Exception as e:\n logger.error(f\"Unexpected error stopping external server: {e}\")\n\n # Close log file if we have one\n if hasattr(self, \"log_file\") and self.log_file:\n self.log_file.close()\n\n # Remove from registry\n from .process import remove_server\n\n remove_server(self)\n\n logger.info(f\"vLLM server stopped for {self.model}\")\n return True\n\n except Exception as e:\n logger.error(f\"Error stopping vLLM server: {e}\")\n return False\n\n def is_running(self) -> bool:\n \"\"\"\n Check if the server is running.\n\n Returns:\n True if server is running, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n # Check if this is an external server (detected, not started by us)\n if hasattr(self.process, \"poll\"):\n # Normal subprocess\n return self.process.poll() is None\n elif hasattr(self.process, \"pid\"):\n # External server - check if PID still exists\n try:\n import psutil\n\n return psutil.pid_exists(self.process.pid)\n except ImportError:\n # Fallback to os method\n try:\n os.kill(self.process.pid, 0)\n return True\n except (OSError, ProcessLookupError):\n return False\n\n return False\n\n def get_status(self) -> Dict[str, Any]:\n \"\"\"\n Get server status information.\n\n Returns:\n Dictionary with status information\n \"\"\"\n status = {\n \"model\": self.model,\n \"port\": self.port,\n \"running\": self.is_running(),\n \"pid\": self.process.pid if self.process else None,\n \"start_time\": self.start_time.isoformat() if self.start_time else None,\n \"log_path\": str(self.log_path) if self.log_path else None,\n }\n\n if self.is_running() and self.start_time:\n uptime = datetime.now() - self.start_time\n status[\"uptime_seconds\"] = uptime.total_seconds()\n status[\"uptime_str\"] = str(uptime).split(\".\")[0]\n\n return status\n\n def wait_for_startup(self) -> bool:\n \"\"\"\n Wait for the server to complete startup.\n\n Monitors the server logs for startup completion indicators and verifies\n via HTTP endpoint. Will wait indefinitely until either startup completes\n or the process terminates.\n\n Returns:\n True if server started successfully, False if process terminated\n \"\"\"\n import time\n\n logger.info(f\"Waiting for {self.model} server to complete startup...\")\n\n # Track if we've seen startup indicators in logs\n log_indicates_ready = False\n\n while True:\n # Check if server is still running\n if not self.is_running():\n logger.error(\n f\"Server process for {self.model} terminated during startup\"\n )\n return False\n\n # Get recent logs to check for startup completion\n recent_logs = self.get_recent_logs(50)\n\n if recent_logs and not log_indicates_ready:\n # Check for startup completion indicators\n for log in recent_logs:\n log_lower = log.lower()\n # Look for the explicit \"Application startup complete\" message\n if \"application startup complete\" in log_lower:\n logger.debug(f\"Server {self.model} startup detected in logs\")\n log_indicates_ready = True\n break\n\n # Also check for other ready indicators as fallback\n if any(\n indicator in log_lower\n for indicator in [\n \"uvicorn running on\",\n \"started server process\",\n \"server is ready\",\n \"api server started\",\n ]\n ):\n logger.debug(\n f\"Server {self.model} startup detected via ready indicator\"\n )\n log_indicates_ready = True\n break\n\n # If logs indicate ready, verify via HTTP\n if log_indicates_ready:\n # Try to verify server is actually ready via HTTP\n port = self.config.get(\"port\")\n if port:\n try:\n import httpx\n\n with httpx.Client() as client:\n # Try /v1/models endpoint first (most reliable)\n response = client.get(\n f\"http://localhost:{port}/v1/models\", timeout=5.0\n )\n if response.status_code == 200:\n logger.info(\n f\"Server {self.model} startup complete \"\n \"(verified via HTTP)\"\n )\n return True\n except httpx.ConnectError:\n # Server not ready yet, continue waiting\n logger.debug(\n f\"Server {self.model} not accepting connections yet\"\n )\n except Exception as e:\n # Log but continue, might be network issue\n logger.debug(f\"HTTP verification failed: {e}\")\n else:\n # No port configured, trust the logs\n logger.info(\n f\"Server {self.model} startup complete (no port for verification)\"\n )\n return True\n\n # Small sleep to avoid busy waiting\n time.sleep(0.5)\n\n def get_recent_logs(self, n: int = 20) -> List[str]:\n \"\"\"\n Get recent log lines from the server output.\n\n Retrieves the most recent log lines from either the in-memory queue\n or the log file on disk. This method ensures logs are available even\n after the monitoring thread has processed them.\n\n Args:\n n: Number of recent lines to return (default: 20)\n\n Returns:\n List of recent log lines, with the most recent last\n \"\"\"\n # Update recent logs from queue\n self._update_recent_logs_from_queue()\n\n # Return from memory if available\n if self._recent_logs:\n return self._recent_logs[-n:]\n\n # Fallback to reading from file\n return self._read_logs_from_file(n)\n\n def _update_recent_logs_from_queue(self) -> None:\n \"\"\"\n Update the recent logs cache from the log queue.\n\n Drains all available log lines from the queue and adds them\n to the recent logs cache, maintaining a maximum of 100 lines.\n \"\"\"\n temp_logs = []\n\n # Get all available logs from queue (don't block)\n while not self.log_queue.empty():\n try:\n log_line = self.log_queue.get_nowait()\n temp_logs.append(log_line)\n except Empty:\n break\n\n if temp_logs:\n self._recent_logs.extend(temp_logs)\n # Keep only the last 100 logs in memory to prevent unbounded growth\n self._recent_logs = self._recent_logs[-100:]\n\n def _read_logs_from_file(self, n: int) -> List[str]:\n \"\"\"\n Read recent log lines from the log file.\n\n Args:\n n: Number of lines to read\n\n Returns:\n List of log lines from file\n \"\"\"\n if not (self.log_path and self.log_path.exists()):\n return []\n\n try:\n with open(self.log_path, \"r\") as f:\n file_logs = f.readlines()\n if file_logs:\n # Get last n lines, strip them\n logs = [line.strip() for line in file_logs[-n:]]\n # Update recent logs cache\n self._recent_logs = logs[-100:]\n return logs\n except Exception as e:\n logger.debug(f\"Error reading log file: {e}\")\n\n return []\n\n def restart(self) -> bool:\n \"\"\"\n Restart the server with the same configuration.\n\n Returns:\n True if restart successful, False otherwise\n \"\"\"\n logger.info(f\"Restarting vLLM server for {self.model}\")\n\n # Stop if running\n if self.is_running():\n self.stop()\n time.sleep(2) # Wait a bit before restarting\n\n # Start again\n return self.start()\n\n def health_check(self) -> bool:\n \"\"\"\n Perform a health check on the server.\n\n Returns:\n True if server is healthy, False otherwise\n \"\"\"\n if not self.is_running():\n return False\n\n try:\n import requests\n\n # Try to connect to the server\n response = requests.get(f\"http://localhost:{self.port}/health\", timeout=5)\n\n return response.status_code == 200\n\n except Exception:\n # If requests fails, just check process\n return self.is_running()", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 27979}, "tests/proxy/test_router.py::37": {"resolved_imports": ["src/vllm_cli/proxy/router.py"], "used_names": [], "enclosing_function": "test_add_multiple_backends", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_ollama_support.py::60": {"resolved_imports": ["src/vllm_cli/models/discovery.py", "src/vllm_cli/models/manager.py"], "used_names": ["patch"], "enclosing_function": "test_scan_includes_ollama_models", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_cli_parser.py::131": {"resolved_imports": ["src/vllm_cli/cli/parser.py"], "used_names": ["create_parser", "pytest"], "enclosing_function": "test_version_flag", "extracted_code": "# Source: src/vllm_cli/cli/parser.py\ndef create_parser() -> argparse.ArgumentParser:\n \"\"\"\n Create the main argument parser for vLLM CLI.\n\n Sets up the main parser with all subcommands and their arguments.\n\n Returns:\n Configured ArgumentParser instance\n \"\"\"\n parser = argparse.ArgumentParser(\n prog=\"vllm-cli\",\n description=\"vLLM CLI - Convenient LLM serving tool\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"Examples:\n vllm-cli # Interactive mode\n vllm-cli serve MODEL --profile standard # Serve with profile\n vllm-cli serve MODEL --quantization awq # Serve with AWQ quantization\n vllm-cli serve MODEL --extra-args \"--seed 42\" # With custom vLLM args\n vllm-cli info # System information\n vllm-cli models # List available models\n vllm-cli status # Show active servers\"\"\",\n )\n\n # Global options\n from .. import __version__\n\n parser.add_argument(\n \"--version\", action=\"version\", version=f\"vLLM CLI {__version__}\"\n )\n\n # Create subparsers for commands\n subparsers = parser.add_subparsers(\n dest=\"command\",\n help=\"Available commands\",\n metavar=\"{serve,proxy,info,models,shortcuts,status,stop,dirs}\",\n )\n\n # Add individual command parsers\n _add_serve_parser(subparsers)\n _add_proxy_parser(subparsers)\n _add_info_parser(subparsers)\n _add_models_parser(subparsers)\n _add_shortcuts_parser(subparsers)\n _add_status_parser(subparsers)\n _add_stop_parser(subparsers)\n _add_dirs_parser(subparsers)\n\n return parser", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1705}, "tests/test_ollama_support.py::27": {"resolved_imports": ["src/vllm_cli/models/discovery.py", "src/vllm_cli/models/manager.py"], "used_names": ["build_model_dict"], "enclosing_function": "test_build_model_dict_with_ollama", "extracted_code": "# Source: src/vllm_cli/models/discovery.py\ndef build_model_dict(item: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Build a standardized model dictionary from model data.\n\n Takes raw model information from various sources and normalizes\n it into a consistent format.\n\n Args:\n item: Model item data\n\n Returns:\n Standardized model dictionary\n \"\"\"\n publisher = item.get(\"publisher\", \"unknown\")\n display_name = item.get(\"display_name\", item.get(\"name\", \"unknown\"))\n\n # Create proper model name\n if publisher and publisher != \"unknown\":\n model_name = f\"{publisher}/{display_name}\"\n else:\n model_name = display_name\n\n return {\n \"name\": model_name,\n \"size\": item.get(\"size\", 0),\n \"path\": item.get(\"path\", \"\"),\n \"type\": item.get(\"type\", \"model\"),\n \"publisher\": publisher,\n \"display_name\": display_name,\n \"metadata\": item.get(\"metadata\", {}),\n }", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 950}, "tests/proxy/test_e2e.py::457": {"resolved_imports": ["src/vllm_cli/proxy/manager.py", "src/vllm_cli/proxy/models.py", "src/vllm_cli/proxy/server.py", "src/vllm_cli/proxy/registry.py"], "used_names": ["ModelConfig", "ModelState", "ProxyConfig", "ProxyServer", "asyncio", "pytest"], "enclosing_function": "test_e2e_full_model_lifecycle_with_registry", "extracted_code": "# Source: src/vllm_cli/proxy/models.py\nclass ModelConfig(BaseModel):\n \"\"\"Configuration for a single model in the proxy.\"\"\"\n\n name: str = Field(..., description=\"Model identifier for API requests\")\n model_path: str = Field(..., description=\"Path or HuggingFace model ID\")\n gpu_ids: List[int] = Field(default_factory=list, description=\"GPU IDs to use\")\n port: int = Field(..., description=\"Port for the vLLM server\")\n profile: Optional[str] = Field(None, description=\"vLLM CLI profile to use\")\n config_overrides: Dict[str, Any] = Field(\n default_factory=dict, description=\"Additional vLLM configuration\"\n )\n enabled: bool = Field(True, description=\"Whether model is enabled\")\n loading_priority: Optional[int] = Field(\n None,\n description=\"Loading priority (lower numbers load first). \"\n \"Models with same priority load in parallel. \"\n \"Models with None priority load after all prioritized models.\",\n )\n\nclass ProxyConfig(BaseModel):\n \"\"\"Configuration for the proxy server.\"\"\"\n\n host: str = Field(\"0.0.0.0\", description=\"Proxy server host\") # nosec B104\n port: int = Field(8000, description=\"Proxy server port\")\n models: List[ModelConfig] = Field(\n default_factory=list, description=\"List of models to serve\"\n )\n enable_cors: bool = Field(True, description=\"Enable CORS headers\")\n enable_metrics: bool = Field(True, description=\"Enable metrics endpoint\")\n log_requests: bool = Field(False, description=\"Log all requests\")\n\n\n# Source: src/vllm_cli/proxy/server.py\nclass ProxyServer:\n \"\"\"\n FastAPI proxy server that routes OpenAI API requests to appropriate vLLM instances.\n \"\"\"\n\n def __init__(self, config: ProxyConfig):\n \"\"\"Initialize the proxy server with configuration.\"\"\"\n self.config = config\n self.app = FastAPI(title=\"vLLM Multi-Model Proxy\", version=\"0.1.0\")\n self.router = RequestRouter()\n self.registry = ModelRegistry() # Dynamic runtime registry\n self.start_time = datetime.now()\n self.total_requests = 0\n self.model_requests: Dict[str, int] = {}\n\n # HTTP client for forwarding requests\n self.client = httpx.AsyncClient(timeout=httpx.Timeout(timeout=300.0))\n\n # Setup middleware and routes\n self._setup_middleware()\n self._setup_routes()\n\n def _setup_middleware(self):\n \"\"\"Configure middleware for the FastAPI app.\"\"\"\n if self.config.enable_cors:\n self.app.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n )\n\n # Request logging middleware\n if self.config.log_requests:\n\n @self.app.middleware(\"http\")\n async def log_requests(request: Request, call_next):\n start_time = time.time()\n response = await call_next(request)\n duration = time.time() - start_time\n logger.info(\n f\"{request.method} {request.url.path} - \"\n f\"{response.status_code} - {duration:.3f}s\"\n )\n return response\n\n def _setup_routes(self):\n \"\"\"Setup API routes for the proxy server.\"\"\"\n\n @self.app.get(\"/\")\n async def root():\n \"\"\"Root endpoint.\"\"\"\n return {\n \"message\": \"vLLM Multi-Model Proxy Server\",\n \"version\": \"0.1.0\",\n \"models_count\": len(self.router.get_active_models()),\n }\n\n @self.app.get(\"/health\")\n async def health():\n \"\"\"Health check endpoint.\"\"\"\n return {\"status\": \"healthy\", \"timestamp\": datetime.now().isoformat()}\n\n @self.app.get(\"/v1/models\")\n async def list_models():\n \"\"\"List available models (OpenAI API compatible).\"\"\"\n models = self.router.get_active_models()\n return {\n \"object\": \"list\",\n \"data\": [\n {\n \"id\": model_name,\n \"object\": \"model\",\n \"created\": int(time.time()),\n \"owned_by\": \"vllm-cli-proxy\",\n }\n for model_name in models\n ],\n }\n\n @self.app.post(\"/v1/chat/completions\")\n async def chat_completions(request: Request):\n \"\"\"Handle chat completions requests.\"\"\"\n return await self._forward_request(request, \"/v1/chat/completions\")\n\n @self.app.post(\"/v1/completions\")\n async def completions(request: Request):\n \"\"\"Handle completions requests.\"\"\"\n return await self._forward_request(request, \"/v1/completions\")\n\n @self.app.post(\"/v1/embeddings\")\n async def embeddings(request: Request):\n \"\"\"Handle embeddings requests.\"\"\"\n return await self._forward_request(request, \"/v1/embeddings\")\n\n @self.app.post(\"/v1/responses\")\n async def responses(request: Request):\n \"\"\"Handle responses requests (OpenAI Responses API).\"\"\"\n return await self._forward_request(request, \"/v1/responses\")\n\n @self.app.get(\"/proxy/status\")\n async def proxy_status():\n \"\"\"Get proxy server status.\"\"\"\n models_status = []\n\n # Get models from registry\n for port, model_entry in self.registry.get_all_models().items():\n models_status.append(\n ModelStatus(\n name=model_entry.display_name,\n model_path=\"\", # Not tracked in registry\n port=port,\n gpu_ids=model_entry.gpu_ids,\n status=(\n \"running\"\n if model_entry.state.value == \"running\"\n else \"stopped\"\n ),\n registration_status=model_entry.status.value,\n request_count=0, # Not tracked in simplified registry\n )\n )\n\n return ProxyStatus(\n proxy_running=True,\n proxy_port=self.config.port,\n proxy_host=self.config.host,\n models=models_status,\n total_requests=self.total_requests,\n start_time=self.start_time.isoformat(),\n )\n\n @self.app.post(\"/proxy/pre_register\")\n async def pre_register(request: Dict[str, Any]):\n \"\"\"Pre-register a model with pending status.\"\"\"\n try:\n port = request[\"port\"]\n gpu_ids = request.get(\"gpu_ids\", [])\n config_name = request.get(\"config_name\")\n request.get(\"estimated_util\")\n\n logger.info(\n f\"Pre-registering model '{config_name}' on port {port} \"\n f\"with GPUs {gpu_ids}\"\n )\n\n # Pre-register in the runtime registry\n success = self.registry.pre_register(port, gpu_ids, config_name)\n\n if success:\n logger.info(f\"Pre-registered model on port {port}\")\n return {\n \"status\": \"success\",\n \"message\": f\"Pre-registered model on port {port}\",\n }\n else:\n message = f\"Failed to pre-register model on port {port}\"\n logger.error(message)\n raise HTTPException(status_code=400, detail=message)\n\n except Exception as e:\n logger.error(f\"Pre-registration error: {e}\")\n raise HTTPException(status_code=400, detail=str(e))\n\n @self.app.post(\"/proxy/register\")\n async def register_model(request: Dict[str, Any]):\n \"\"\"Register a new model in the runtime registry (backward compatibility).\"\"\"\n try:\n port = request[\"port\"]\n gpu_ids = request.get(\"gpu_ids\", [])\n actual_name = request.get(\"actual_name\", f\"model_{port}\")\n\n # Register in the runtime registry\n success = self.registry.verify_and_activate(port, actual_name)\n\n if success:\n # Add to router for request routing\n backend_url = f\"http://localhost:{port}\"\n self.router.add_backend(\n actual_name, backend_url, {\"port\": port, \"gpu_ids\": gpu_ids}\n )\n\n return {\n \"status\": \"success\",\n \"message\": f\"Registered model '{actual_name}' on port {port}\",\n \"actual_name\": actual_name,\n }\n else:\n message = f\"Failed to register model on port {port}\"\n raise HTTPException(status_code=400, detail=message)\n\n except Exception as e:\n raise HTTPException(status_code=400, detail=str(e))\n\n @self.app.delete(\"/proxy/models/{port}\")\n async def unregister_model(port: int):\n \"\"\"Unregister a model from the runtime registry.\"\"\"\n try:\n # Get model info before unregistering\n model_entry = self.registry.get_model(port)\n if not model_entry:\n raise HTTPException(\n status_code=404, detail=f\"Model on port {port} not found\"\n )\n\n # Unregister from registry\n success = self.registry.remove_model(port)\n message = (\n f\"Model on port {port} unregistered\"\n if success\n else f\"Model on port {port} not found\"\n )\n\n if success:\n # Remove from router\n if model_entry.actual_name:\n try:\n self.router.remove_backend(model_entry.actual_name)\n except Exception:\n pass # Router entry might not exist\n\n return {\"status\": \"success\", \"message\": message}\n else:\n raise HTTPException(status_code=400, detail=message)\n\n except HTTPException:\n raise\n except Exception as e:\n raise HTTPException(status_code=400, detail=str(e))\n\n @self.app.post(\"/proxy/state\")\n async def update_model_state(request: Dict[str, Any]):\n \"\"\"Update the state of a model (running/sleeping/stopped).\"\"\"\n try:\n port = request[\"port\"]\n state = request[\"state\"]\n sleep_level = request.get(\"sleep_level\", 0)\n\n # Update model state\n model_entry = self.registry.get_model(port)\n if model_entry:\n from .registry import ModelState\n\n if state == \"sleeping\":\n model_entry.state = ModelState.SLEEPING\n model_entry.sleep_level = sleep_level\n elif state == \"running\":\n model_entry.state = ModelState.RUNNING\n model_entry.sleep_level = 0\n elif state == \"stopped\":\n model_entry.state = ModelState.STOPPED\n message = f\"Updated state to {state}\"\n return {\"status\": \"success\", \"message\": message}\n else:\n raise HTTPException(\n status_code=404, detail=f\"Model on port {port} not found\"\n )\n\n except Exception as e:\n raise HTTPException(status_code=400, detail=str(e))\n\n @self.app.get(\"/proxy/registry\")\n async def get_registry():\n \"\"\"Get the complete registry status including GPU allocation.\"\"\"\n return self.registry.get_status_summary()\n\n @self.app.post(\"/proxy/refresh_models\")\n async def refresh_models():\n \"\"\"\n Refresh model registry - verify ALL models and update their status.\n \"\"\"\n import httpx\n\n from .registry import ModelState, RegistrationStatus\n\n # Cleanup any stale entries\n removed_count = self.registry.cleanup_stale_entries()\n if removed_count > 0:\n logger.info(f\"Removed {removed_count} stale entries\")\n\n # Get all models and check their status\n all_models = self.registry.get_all_models()\n newly_registered = []\n already_available = []\n newly_failed = []\n pending_count = 0\n\n for port, model_entry in all_models.items():\n # Check ALL models\n try:\n # Call the model's /v1/models endpoint\n async with httpx.AsyncClient() as client:\n response = await client.get(\n f\"http://localhost:{port}/v1/models\", timeout=5.0\n )\n\n if response.status_code == 200:\n # Model is responding\n # Always check if model is sleeping\n # (not just when marked as sleeping)\n is_sleeping = False\n try:\n sleep_response = await client.get(\n f\"http://localhost:{port}/is_sleeping\", timeout=2.0\n )\n if sleep_response.status_code == 200:\n sleep_data = sleep_response.json()\n is_sleeping = sleep_data.get(\"is_sleeping\", False)\n\n # Update model state based on actual sleep status\n if (\n is_sleeping\n and model_entry.state != ModelState.SLEEPING\n ):\n model_entry.state = ModelState.SLEEPING\n logger.info(f\"Model on port {port} is sleeping\")\n elif (\n not is_sleeping\n and model_entry.state == ModelState.SLEEPING\n ):\n model_entry.state = ModelState.RUNNING\n logger.info(\n f\"Model on port {port} has been woken up\"\n )\n elif not is_sleeping:\n model_entry.state = ModelState.RUNNING\n except Exception:\n # If /is_sleeping endpoint doesn't exist or fails,\n # check current state. If it was sleeping, keep it as\n # sleeping; otherwise assume running\n if model_entry.state != ModelState.SLEEPING:\n model_entry.state = ModelState.RUNNING\n\n # Extract actual model name from response\n models_data = response.json()\n actual_name = None\n if models_data.get(\"data\"):\n actual_name = models_data[\"data\"][0].get(\"id\")\n\n # Check previous status\n was_pending = (\n model_entry.status == RegistrationStatus.PENDING\n )\n was_error = model_entry.status == RegistrationStatus.ERROR\n\n # Verify and activate the model\n if self.registry.verify_and_activate(port, actual_name):\n if was_pending or was_error:\n newly_registered.append(\n actual_name or f\"port_{port}\"\n )\n else:\n already_available.append(\n actual_name or f\"port_{port}\"\n )\n\n # Ensure it's in the router\n if (\n actual_name\n and actual_name not in self.router.backends\n ):\n backend_url = f\"http://localhost:{port}\"\n self.router.add_backend(\n actual_name,\n backend_url,\n {\n \"port\": port,\n \"gpu_ids\": model_entry.gpu_ids,\n },\n )\n logger.debug(\n f\"Model on port {port} verified as available\"\n )\n else:\n # Model not responding properly\n if model_entry.status == RegistrationStatus.AVAILABLE:\n # Was available, now failing\n model_entry.mark_error(f\"HTTP {response.status_code}\")\n newly_failed.append(model_entry.display_name)\n # Remove from router if present\n if model_entry.actual_name in self.router.backends:\n self.router.remove_backend(model_entry.actual_name)\n else:\n pending_count += 1\n\n except Exception as e:\n # Model not accessible\n if model_entry.status == RegistrationStatus.AVAILABLE:\n # Was available, now failing\n model_entry.mark_error(\n str(e)[:100]\n ) # Limit error message length\n newly_failed.append(model_entry.display_name)\n # Remove from router if present\n if (\n model_entry.actual_name\n and model_entry.actual_name in self.router.backends\n ):\n self.router.remove_backend(model_entry.actual_name)\n logger.warning(\n f\"Model on port {port} no longer accessible: {e}\"\n )\n elif model_entry.status == RegistrationStatus.PENDING:\n pending_count += 1\n logger.debug(f\"Model on port {port} still not ready: {e}\")\n\n summary = {\n \"registered\": len(newly_registered),\n \"already_available\": len(already_available),\n \"failed\": len(newly_failed),\n \"pending\": pending_count,\n \"removed\": removed_count,\n \"total\": len(all_models),\n }\n\n return {\n \"status\": \"success\",\n \"summary\": summary,\n \"details\": {\n \"newly_registered\": newly_registered,\n \"already_available\": already_available,\n \"newly_failed\": newly_failed,\n },\n }\n\n if self.config.enable_metrics:\n\n @self.app.get(\"/metrics\")\n async def metrics():\n \"\"\"Prometheus-compatible metrics endpoint.\"\"\"\n metrics_text = []\n metrics_text.append(\n \"# HELP proxy_requests_total Total requests to proxy\"\n )\n metrics_text.append(\"# TYPE proxy_requests_total counter\")\n metrics_text.append(f\"proxy_requests_total {self.total_requests}\")\n\n metrics_text.append(\"# HELP model_requests_total Requests per model\")\n metrics_text.append(\"# TYPE model_requests_total counter\")\n for model, count in self.model_requests.items():\n metrics_text.append(\n f'model_requests_total{{model=\"{model}\"}} {count}'\n )\n\n uptime = (datetime.now() - self.start_time).total_seconds()\n metrics_text.append(\n \"# HELP proxy_uptime_seconds Proxy uptime in seconds\"\n )\n metrics_text.append(\"# TYPE proxy_uptime_seconds gauge\")\n metrics_text.append(f\"proxy_uptime_seconds {uptime}\")\n\n return \"\\n\".join(metrics_text)\n\n async def _forward_request(self, request: Request, endpoint: str):\n \"\"\"\n Forward a request to the appropriate vLLM backend.\n\n Args:\n request: Incoming FastAPI request\n endpoint: Target endpoint path\n\n Returns:\n Response from the backend server\n \"\"\"\n try:\n # Parse request body\n body = await request.body()\n json_body = json.loads(body) if body else {}\n\n # Extract model from request\n model_name = json_body.get(\"model\")\n if not model_name:\n raise HTTPException(\n status_code=400, detail=\"Missing 'model' field in request\"\n )\n\n # Get backend URL for this model\n backend_url = self.router.route_request(model_name)\n if not backend_url:\n raise HTTPException(\n status_code=404, detail=f\"Model '{model_name}' not found\"\n )\n\n # Update request counters\n self.total_requests += 1\n self.model_requests[model_name] = self.model_requests.get(model_name, 0) + 1\n\n # Check if streaming is requested\n stream = json_body.get(\"stream\", False)\n\n # Forward the request\n target_url = f\"{backend_url}{endpoint}\"\n headers = dict(request.headers)\n headers.pop(\"host\", None) # Remove host header\n\n if stream:\n # Handle streaming response\n return StreamingResponse(\n self._stream_response(target_url, headers, body),\n media_type=\"text/event-stream\",\n )\n else:\n # Handle regular response\n response = await self.client.post(\n target_url, headers=headers, content=body\n )\n\n if response.status_code != 200:\n raise HTTPException(\n status_code=response.status_code, detail=response.text\n )\n\n return JSONResponse(\n content=response.json(), status_code=response.status_code\n )\n\n except HTTPException:\n raise\n except Exception as e:\n logger.error(f\"Error forwarding request: {e}\")\n raise HTTPException(status_code=500, detail=str(e))\n\n async def _stream_response(\n self, url: str, headers: Dict, body: bytes\n ) -> AsyncGenerator[bytes, None]:\n \"\"\"\n Stream response from backend server.\n\n Args:\n url: Target URL\n headers: Request headers\n body: Request body\n\n Yields:\n Chunks of response data\n \"\"\"\n try:\n async with self.client.stream(\n \"POST\", url, headers=headers, content=body\n ) as response:\n async for chunk in response.aiter_bytes():\n yield chunk\n except Exception as e:\n logger.error(f\"Error streaming response: {e}\")\n yield f'data: {{\"error\": \"{str(e)}\"}}\\n\\n'.encode()\n\n async def _check_backend_health(self, port: int) -> str:\n \"\"\"\n Check health of a backend server.\n\n Args:\n port: Backend server port\n\n Returns:\n Status string: \"running\", \"error\", or \"unknown\"\n \"\"\"\n try:\n response = await self.client.get(\n f\"http://localhost:{port}/health\", timeout=5.0\n )\n return \"running\" if response.status_code == 200 else \"error\"\n except Exception:\n return \"unknown\"\n\n def run(self):\n \"\"\"Run the proxy server.\"\"\"\n import uvicorn\n\n logger.info(f\"Starting proxy server on {self.config.host}:{self.config.port}\")\n\n uvicorn.run(\n self.app, host=self.config.host, port=self.config.port, log_level=\"info\"\n )\n\n async def shutdown(self):\n \"\"\"Cleanup resources on shutdown.\"\"\"\n await self.client.aclose()\n\n\n# Source: src/vllm_cli/proxy/registry.py\nclass ModelState(Enum):\n \"\"\"Model state enumeration.\"\"\"\n\n RUNNING = \"running\"\n SLEEPING = \"sleeping\"\n STOPPED = \"stopped\"\n STARTING = \"starting\"", "n_imports_parsed": 14, "n_files_resolved": 4, "n_chars_extracted": 25670}, "tests/test_server_manager.py::109": {"resolved_imports": ["src/vllm_cli/server/__init__.py", "src/vllm_cli/server/process.py", "src/vllm_cli/server/manager.py"], "used_names": ["Mock", "VLLMServer", "patch", "process"], "enclosing_function": "test_stop_server", "extracted_code": "# Source: src/vllm_cli/server/__init__.py\n\nThis package provides comprehensive vLLM server management including\nprocess lifecycle, monitoring, discovery, and utilities.\n\nMain Components:\n- VLLMServer: Core server management class\n- Process management: Server registry and lifecycle\n- Discovery: External server detection\n- Monitoring: Health checks and metrics\n- Utils: Port management and cleanup utilities\n\"\"\"\n\n\n\n# Process management functions\nfrom .process import (\n add_server,\n cleanup_servers_on_exit,\n find_server_by_model,\n find_server_by_port,\n get_active_servers,\n remove_server,\n stop_all_servers,\n)\n\n\n\n# Source: src/vllm_cli/server/manager.py\nclass VLLMServer:\n \"\"\"\n Manages a vLLM server instance with comprehensive lifecycle control.\n\n This class handles the complete lifecycle of a vLLM server including\n configuration, process management, logging, monitoring, and cleanup.\n It supports both programmatically started servers and external server\n detection and management.\n\n Attributes:\n config: Server configuration dictionary\n model: Model name being served\n port: Port number the server is listening on\n process: Subprocess or external process reference\n log_file: File handle for server logs\n log_queue: Thread-safe queue for log lines\n log_thread: Background thread for log monitoring\n start_time: Timestamp when server was started\n log_path: Path to the server's log file\n \"\"\"\n\n def __init__(self, config: Dict[str, Any]) -> None:\n \"\"\"\n Initialize a vLLM server instance.\n\n Sets up the server configuration, logging infrastructure, and\n prepares the instance for server lifecycle management.\n\n Args:\n config: Server configuration dictionary containing model name,\n port, and other vLLM-specific parameters\n \"\"\"\n self.config: Dict[str, Any] = config\n\n # Extract model name - handle both string and dict (LoRA config) formats\n model_config = config.get(\"model\", \"unknown\")\n if isinstance(model_config, dict):\n # LoRA configuration - extract base model name\n self.model: str = model_config.get(\"model\", \"unknown\")\n else:\n # Regular string model name\n self.model: str = model_config\n\n self.port: int = config.get(\"port\", 8000)\n self.process: Optional[Union[subprocess.Popen, Any]] = None\n self.log_file: Optional[TextIO] = None\n self.log_queue: Queue[str] = Queue()\n self.log_thread: Optional[Thread] = None\n self.start_time: Optional[datetime] = None\n self.log_path: Path\n self._recent_logs: List[str] = []\n\n # Setup logging\n log_dir = Path.home() / \".vllm-cli\" / \"logs\"\n log_dir.mkdir(parents=True, exist_ok=True)\n\n timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n self.log_path = log_dir / f\"vllm_{self.model.replace('/', '_')}_{timestamp}.log\"\n\n def start(self) -> bool:\n \"\"\"\n Start the vLLM server.\n\n Returns:\n True if server started successfully, False otherwise\n \"\"\"\n if self.is_running():\n logger.warning(f\"Server already running for {self.model}\")\n return False\n\n try:\n # Build command - run directly without conda wrapper\n full_cmd = self._build_command()\n\n logger.info(f\"Starting vLLM server with command: {' '.join(full_cmd)}\")\n\n # Open log file for writing\n self.log_file = open(self.log_path, \"w\", buffering=1)\n\n # Start with parent environment\n env = os.environ.copy()\n # Note: No longer forcing PYTHONUNBUFFERED=1, let user control it\n\n # Layer 1: Apply universal environment variables from settings\n config_manager = ConfigManager()\n universal_env = config_manager.config.get(\"universal_environment\", {})\n if universal_env:\n logger.info(\n f\"Applying {len(universal_env)} universal environment variable(s)\"\n )\n for key, value in universal_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting universal {key}={value}\")\n else:\n logger.debug(f\"Setting universal {key}=\")\n\n # Layer 2: Apply profile environment variables (override universal)\n profile_env = self.config.get(\"profile_environment\", {})\n if profile_env:\n logger.info(\n f\"Applying {len(profile_env)} profile environment variable(s)\"\n )\n for key, value in profile_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting profile {key}={value}\")\n else:\n logger.debug(f\"Setting profile {key}=\")\n\n # Handle GPU device selection via CUDA_VISIBLE_DEVICES\n # This overrides any CUDA_VISIBLE_DEVICES from the profile\n if self.config.get(\"device\"):\n device_str = str(self.config[\"device\"])\n env[\"CUDA_VISIBLE_DEVICES\"] = device_str\n logger.info(f\"Setting CUDA_VISIBLE_DEVICES={device_str}\")\n\n # If using specific GPUs, adjust tensor parallel size if needed\n device_list = [d.strip() for d in device_str.split(\",\")]\n num_devices = len(device_list)\n\n # Check if tensor_parallel_size is set and compatible\n if self.config.get(\"tensor_parallel_size\"):\n tp_size = self.config[\"tensor_parallel_size\"]\n if tp_size > num_devices:\n logger.warning(\n f\"tensor_parallel_size ({tp_size}) > number of selected devices ({num_devices}). \"\n f\"Adjusting tensor_parallel_size to {num_devices}\"\n )\n self.config[\"tensor_parallel_size\"] = num_devices\n elif num_devices % tp_size != 0:\n logger.warning(\n f\"Number of GPUs ({num_devices}) is not evenly divisible by \"\n f\"tensor_parallel_size ({tp_size}). This may lead to inefficient GPU utilization. \"\n f\"Consider using tensor_parallel_size of: \"\n f\"{', '.join(str(i) for i in range(1, num_devices + 1) if num_devices % i == 0)}\"\n )\n\n # Add HuggingFace token if configured\n config_manager = ConfigManager()\n hf_token = config_manager.config.get(\"hf_token\")\n if hf_token:\n env[\"HF_TOKEN\"] = hf_token\n env[\"HUGGING_FACE_HUB_TOKEN\"] = hf_token # Some tools use this variant\n logger.info(\"HuggingFace token configured for server\")\n\n # Enable development mode for sleep endpoints if sleep mode is enabled\n if self.config.get(\"enable_sleep_mode\"):\n env[\"VLLM_SERVER_DEV_MODE\"] = \"1\"\n logger.info(\"Sleep mode enabled with development endpoints\")\n\n # Start the process with proper pipe configuration\n # Use start_new_session=True to create a new process group\n # This prevents the child process from receiving Ctrl+C signals\n self.process = subprocess.Popen(\n full_cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n text=True,\n bufsize=0, # Unbuffered\n universal_newlines=True,\n env=env,\n start_new_session=True, # Create new process group to isolate from parent signals\n )\n\n # Start log monitoring thread\n self._start_log_monitor()\n\n # Set start time and add to registry\n self.start_time = datetime.now()\n from .process import add_server\n\n add_server(self)\n\n # Return immediately - let the UI monitor the startup\n logger.info(\n f\"vLLM server process launched for {self.model} on port {self.port}\"\n )\n return True\n\n except Exception as e:\n logger.error(f\"Error starting vLLM server: {e}\")\n return False\n\n def _build_command(self) -> List[str]:\n \"\"\"\n Build the vLLM command from configuration using the schema.\n\n Returns:\n List of command arguments\n \"\"\"\n # Use the new ConfigManager to build CLI args\n config_manager = ConfigManager()\n\n # Start with the vllm command\n cmd = [\"vllm\"]\n\n # Add the arguments built from schema\n cli_args = config_manager.build_cli_args(self.config)\n cmd.extend(cli_args)\n\n # Handle extra_args if present (backward compatibility)\n if self.config.get(\"extra_args\"):\n self._add_extra_args_to_command(cmd)\n\n logger.debug(f\"Built command: {' '.join(cmd)}\")\n return cmd\n\n def _add_extra_args_to_command(self, cmd: List[str]) -> None:\n \"\"\"\n Add extra arguments to the vLLM command.\n\n Args:\n cmd: Command list to extend with extra arguments\n \"\"\"\n try:\n extra_args = shlex.split(self.config[\"extra_args\"])\n if extra_args:\n logger.info(f\"Adding extra arguments: {extra_args}\")\n cmd.extend(extra_args)\n except ValueError as e:\n logger.warning(f\"Failed to parse extra_args: {e}\")\n\n def _start_log_monitor(self) -> None:\n \"\"\"\n Start a thread to monitor log output from the vLLM server process.\n\n Creates a daemon thread that continuously reads stdout/stderr from\n the server process, writes to log files, and queues log lines for\n real-time display in the UI.\n \"\"\"\n self.log_thread = Thread(target=self._log_monitor_worker, daemon=True)\n self.log_thread.start()\n\n def _log_monitor_worker(self) -> None:\n \"\"\"\n Worker function for log monitoring thread.\n\n Continuously reads log output from the server process and handles\n file writing and queue management for UI display.\n \"\"\"\n try:\n self.log_queue.put(\"Starting vLLM server process...\")\n\n while self._should_continue_monitoring():\n if self._process_log_line():\n continue\n else:\n # No line read, check if process still running\n if self.process and self.process.poll() is not None:\n break\n time.sleep(0.01) # Small sleep to prevent busy waiting\n\n except Exception as e:\n logger.error(f\"Error in log monitor: {e}\")\n self.log_queue.put(f\"Log monitoring error: {e}\")\n\n def _should_continue_monitoring(self) -> bool:\n \"\"\"\n Check if log monitoring should continue.\n\n Returns:\n True if monitoring should continue, False otherwise\n \"\"\"\n return (\n self.is_running()\n and self.process\n and hasattr(self.process, \"stdout\")\n and self.process.stdout\n )\n\n def _process_log_line(self) -> bool:\n \"\"\"\n Process a single log line from the server output.\n\n Reads one line from the process stdout, writes it to the log file,\n and adds it to the queue for UI display after filtering and formatting.\n\n Returns:\n True if a line was processed, False if no line was available\n \"\"\"\n if not (self.process and self.process.stdout):\n return False\n\n line = self.process.stdout.readline()\n if not line:\n return False\n\n # Write to log file\n self._write_to_log_file(line)\n\n # Process for UI display\n line_stripped = line.strip()\n if line_stripped and self._should_display_log_line(line_stripped):\n # Truncate overly long lines\n if len(line_stripped) > 200:\n line_stripped = line_stripped[:197] + \"...\"\n\n self.log_queue.put(line_stripped)\n logger.debug(f\"Log captured: {line_stripped[:50]}...\")\n\n return True\n\n def _write_to_log_file(self, line: str) -> None:\n \"\"\"\n Write a log line to the log file.\n\n Args:\n line: Log line to write\n \"\"\"\n if self.log_file and not self.log_file.closed:\n self.log_file.write(line)\n self.log_file.flush()\n\n def _should_display_log_line(self, line: str) -> bool:\n \"\"\"\n Determine if a log line should be displayed in the UI.\n\n Filters out certain system messages that are not useful for users.\n\n Args:\n line: Stripped log line to check\n\n Returns:\n True if the line should be displayed, False otherwise\n \"\"\"\n # Filter out conda activation and system messages\n filtered_messages = [\n \"Activated CUDA\",\n \"Using nvcc from:\",\n \"Cuda compilation tools\",\n ]\n return not any(skip in line for skip in filtered_messages)\n\n def stop(self) -> bool:\n \"\"\"\n Stop the vLLM server.\n\n Returns:\n True if server stopped successfully, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n try:\n # Check if this is an external server\n if hasattr(self.process, \"terminate\"):\n # Normal subprocess\n # Since we created a new session, we need to terminate the entire process group\n try:\n # Get the process group ID (pgid)\n # Since we used start_new_session=True, the pgid is the same as the pid\n pgid = self.process.pid\n\n # Send SIGTERM to the entire process group for graceful shutdown\n logger.info(f\"Sending SIGTERM to process group {pgid}\")\n os.killpg(pgid, signal.SIGTERM)\n\n # Wait for process to terminate\n try:\n self.process.wait(timeout=10)\n logger.info(f\"Process group {pgid} terminated gracefully\")\n except subprocess.TimeoutExpired:\n # Force kill if not terminated\n logger.warning(\n f\"Process group {pgid} did not terminate, sending SIGKILL\"\n )\n os.killpg(pgid, signal.SIGKILL)\n self.process.wait()\n logger.info(f\"Process group {pgid} force killed\")\n\n except ProcessLookupError:\n # Process already dead\n logger.info(\"Process already terminated\")\n except PermissionError as e:\n # Fall back to terminating just the process\n logger.warning(\n f\"Permission denied for process group kill: {e}, falling back to process termination\"\n )\n self.process.terminate()\n try:\n self.process.wait(timeout=10)\n except subprocess.TimeoutExpired:\n self.process.kill()\n self.process.wait()\n elif hasattr(self.process, \"pid\"):\n # External server - kill entire process group or individual process\n try:\n pgid = self.process.pid\n killed = False\n\n # First attempt: try to kill process group\n try:\n os.killpg(pgid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process group {pgid}\")\n killed = True\n except (OSError, ProcessLookupError) as e:\n # Process group kill failed, try individual process\n logger.debug(\n f\"Process group kill failed: {e}, trying individual process\"\n )\n try:\n # Ensure pid is an integer (handle Mock objects)\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process {self.process.pid}\")\n killed = True\n except ProcessLookupError:\n # Process already dead\n logger.info(\n f\"Process {self.process.pid} already terminated\"\n )\n except OSError as e:\n logger.warning(\n f\"Failed to send SIGTERM to {self.process.pid}: {e}\"\n )\n\n if killed:\n # Wait for graceful shutdown\n time.sleep(2)\n\n # Check if still running and force kill if needed\n if self.is_running():\n try:\n os.killpg(pgid, signal.SIGKILL)\n logger.info(f\"Force killed process group {pgid}\")\n except (OSError, ProcessLookupError):\n # Process group kill failed, try individual\n try:\n # Ensure pid is an integer (handle Mock objects in tests)\n if hasattr(self.process, \"pid\"):\n try:\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGKILL)\n logger.info(f\"Force killed process {pid}\")\n except (TypeError, ValueError):\n # PID is not a valid integer (might be Mock)\n pass\n except ProcessLookupError:\n pass # Already dead\n except OSError as e:\n logger.error(\n f\"Failed to force kill {self.process.pid}: {e}\"\n )\n\n except Exception as e:\n logger.error(f\"Unexpected error stopping external server: {e}\")\n\n # Close log file if we have one\n if hasattr(self, \"log_file\") and self.log_file:\n self.log_file.close()\n\n # Remove from registry\n from .process import remove_server\n\n remove_server(self)\n\n logger.info(f\"vLLM server stopped for {self.model}\")\n return True\n\n except Exception as e:\n logger.error(f\"Error stopping vLLM server: {e}\")\n return False\n\n def is_running(self) -> bool:\n \"\"\"\n Check if the server is running.\n\n Returns:\n True if server is running, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n # Check if this is an external server (detected, not started by us)\n if hasattr(self.process, \"poll\"):\n # Normal subprocess\n return self.process.poll() is None\n elif hasattr(self.process, \"pid\"):\n # External server - check if PID still exists\n try:\n import psutil\n\n return psutil.pid_exists(self.process.pid)\n except ImportError:\n # Fallback to os method\n try:\n os.kill(self.process.pid, 0)\n return True\n except (OSError, ProcessLookupError):\n return False\n\n return False\n\n def get_status(self) -> Dict[str, Any]:\n \"\"\"\n Get server status information.\n\n Returns:\n Dictionary with status information\n \"\"\"\n status = {\n \"model\": self.model,\n \"port\": self.port,\n \"running\": self.is_running(),\n \"pid\": self.process.pid if self.process else None,\n \"start_time\": self.start_time.isoformat() if self.start_time else None,\n \"log_path\": str(self.log_path) if self.log_path else None,\n }\n\n if self.is_running() and self.start_time:\n uptime = datetime.now() - self.start_time\n status[\"uptime_seconds\"] = uptime.total_seconds()\n status[\"uptime_str\"] = str(uptime).split(\".\")[0]\n\n return status\n\n def wait_for_startup(self) -> bool:\n \"\"\"\n Wait for the server to complete startup.\n\n Monitors the server logs for startup completion indicators and verifies\n via HTTP endpoint. Will wait indefinitely until either startup completes\n or the process terminates.\n\n Returns:\n True if server started successfully, False if process terminated\n \"\"\"\n import time\n\n logger.info(f\"Waiting for {self.model} server to complete startup...\")\n\n # Track if we've seen startup indicators in logs\n log_indicates_ready = False\n\n while True:\n # Check if server is still running\n if not self.is_running():\n logger.error(\n f\"Server process for {self.model} terminated during startup\"\n )\n return False\n\n # Get recent logs to check for startup completion\n recent_logs = self.get_recent_logs(50)\n\n if recent_logs and not log_indicates_ready:\n # Check for startup completion indicators\n for log in recent_logs:\n log_lower = log.lower()\n # Look for the explicit \"Application startup complete\" message\n if \"application startup complete\" in log_lower:\n logger.debug(f\"Server {self.model} startup detected in logs\")\n log_indicates_ready = True\n break\n\n # Also check for other ready indicators as fallback\n if any(\n indicator in log_lower\n for indicator in [\n \"uvicorn running on\",\n \"started server process\",\n \"server is ready\",\n \"api server started\",\n ]\n ):\n logger.debug(\n f\"Server {self.model} startup detected via ready indicator\"\n )\n log_indicates_ready = True\n break\n\n # If logs indicate ready, verify via HTTP\n if log_indicates_ready:\n # Try to verify server is actually ready via HTTP\n port = self.config.get(\"port\")\n if port:\n try:\n import httpx\n\n with httpx.Client() as client:\n # Try /v1/models endpoint first (most reliable)\n response = client.get(\n f\"http://localhost:{port}/v1/models\", timeout=5.0\n )\n if response.status_code == 200:\n logger.info(\n f\"Server {self.model} startup complete \"\n \"(verified via HTTP)\"\n )\n return True\n except httpx.ConnectError:\n # Server not ready yet, continue waiting\n logger.debug(\n f\"Server {self.model} not accepting connections yet\"\n )\n except Exception as e:\n # Log but continue, might be network issue\n logger.debug(f\"HTTP verification failed: {e}\")\n else:\n # No port configured, trust the logs\n logger.info(\n f\"Server {self.model} startup complete (no port for verification)\"\n )\n return True\n\n # Small sleep to avoid busy waiting\n time.sleep(0.5)\n\n def get_recent_logs(self, n: int = 20) -> List[str]:\n \"\"\"\n Get recent log lines from the server output.\n\n Retrieves the most recent log lines from either the in-memory queue\n or the log file on disk. This method ensures logs are available even\n after the monitoring thread has processed them.\n\n Args:\n n: Number of recent lines to return (default: 20)\n\n Returns:\n List of recent log lines, with the most recent last\n \"\"\"\n # Update recent logs from queue\n self._update_recent_logs_from_queue()\n\n # Return from memory if available\n if self._recent_logs:\n return self._recent_logs[-n:]\n\n # Fallback to reading from file\n return self._read_logs_from_file(n)\n\n def _update_recent_logs_from_queue(self) -> None:\n \"\"\"\n Update the recent logs cache from the log queue.\n\n Drains all available log lines from the queue and adds them\n to the recent logs cache, maintaining a maximum of 100 lines.\n \"\"\"\n temp_logs = []\n\n # Get all available logs from queue (don't block)\n while not self.log_queue.empty():\n try:\n log_line = self.log_queue.get_nowait()\n temp_logs.append(log_line)\n except Empty:\n break\n\n if temp_logs:\n self._recent_logs.extend(temp_logs)\n # Keep only the last 100 logs in memory to prevent unbounded growth\n self._recent_logs = self._recent_logs[-100:]\n\n def _read_logs_from_file(self, n: int) -> List[str]:\n \"\"\"\n Read recent log lines from the log file.\n\n Args:\n n: Number of lines to read\n\n Returns:\n List of log lines from file\n \"\"\"\n if not (self.log_path and self.log_path.exists()):\n return []\n\n try:\n with open(self.log_path, \"r\") as f:\n file_logs = f.readlines()\n if file_logs:\n # Get last n lines, strip them\n logs = [line.strip() for line in file_logs[-n:]]\n # Update recent logs cache\n self._recent_logs = logs[-100:]\n return logs\n except Exception as e:\n logger.debug(f\"Error reading log file: {e}\")\n\n return []\n\n def restart(self) -> bool:\n \"\"\"\n Restart the server with the same configuration.\n\n Returns:\n True if restart successful, False otherwise\n \"\"\"\n logger.info(f\"Restarting vLLM server for {self.model}\")\n\n # Stop if running\n if self.is_running():\n self.stop()\n time.sleep(2) # Wait a bit before restarting\n\n # Start again\n return self.start()\n\n def health_check(self) -> bool:\n \"\"\"\n Perform a health check on the server.\n\n Returns:\n True if server is healthy, False otherwise\n \"\"\"\n if not self.is_running():\n return False\n\n try:\n import requests\n\n # Try to connect to the server\n response = requests.get(f\"http://localhost:{self.port}/health\", timeout=5)\n\n return response.status_code == 200\n\n except Exception:\n # If requests fails, just check process\n return self.is_running()", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 28614}, "tests/proxy/test_manager.py::311": {"resolved_imports": ["src/vllm_cli/proxy/manager.py", "src/vllm_cli/proxy/models.py"], "used_names": ["ModelConfig"], "enclosing_function": "test_build_vllm_config_multi_gpu", "extracted_code": "# Source: src/vllm_cli/proxy/models.py\nclass ModelConfig(BaseModel):\n \"\"\"Configuration for a single model in the proxy.\"\"\"\n\n name: str = Field(..., description=\"Model identifier for API requests\")\n model_path: str = Field(..., description=\"Path or HuggingFace model ID\")\n gpu_ids: List[int] = Field(default_factory=list, description=\"GPU IDs to use\")\n port: int = Field(..., description=\"Port for the vLLM server\")\n profile: Optional[str] = Field(None, description=\"vLLM CLI profile to use\")\n config_overrides: Dict[str, Any] = Field(\n default_factory=dict, description=\"Additional vLLM configuration\"\n )\n enabled: bool = Field(True, description=\"Whether model is enabled\")\n loading_priority: Optional[int] = Field(\n None,\n description=\"Loading priority (lower numbers load first). \"\n \"Models with same priority load in parallel. \"\n \"Models with None priority load after all prioritized models.\",\n )", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 967}, "tests/test_profiles.py::138": {"resolved_imports": ["src/vllm_cli/config/profiles.py"], "used_names": ["ProfileManager", "patch"], "enclosing_function": "test_get_profile_nonexistent", "extracted_code": "# Source: src/vllm_cli/config/profiles.py\nclass ProfileManager:\n \"\"\"\n Manages user profiles for vLLM configurations.\n\n Handles creation, retrieval, updating, and deletion of user profiles\n with validation and persistence.\n \"\"\"\n\n def __init__(self, config_dir: Path):\n self.config_dir = config_dir\n self.user_profiles_file = config_dir / \"user_profiles.json\"\n\n # Paths for schema files (packaged with application)\n schema_dir = Path(__file__).parent.parent / \"schemas\"\n self.default_profiles_file = schema_dir / \"default_profiles.json\"\n\n # Load profiles\n self.default_profiles = self._load_default_profiles()\n self.user_profiles = self._load_user_profiles()\n\n def _load_json_file(self, filepath: Path) -> Dict[str, Any]:\n \"\"\"Load a JSON file safely.\"\"\"\n if filepath.exists():\n try:\n with open(filepath, \"r\") as f:\n return json.load(f)\n except Exception as e:\n logger.error(f\"Error loading {filepath}: {e}\")\n return {}\n\n def _save_json_file(self, filepath: Path, data: Dict[str, Any]) -> bool:\n \"\"\"Save data to a JSON file.\"\"\"\n try:\n with open(filepath, \"w\") as f:\n json.dump(data, f, indent=2)\n return True\n except Exception as e:\n logger.error(f\"Error saving {filepath}: {e}\")\n return False\n\n def _load_default_profiles(self) -> Dict[str, Any]:\n \"\"\"Load default built-in profiles.\"\"\"\n profiles = self._load_json_file(self.default_profiles_file)\n return profiles.get(\"profiles\", {})\n\n def _load_user_profiles(self) -> Dict[str, Any]:\n \"\"\"Load user-created custom profiles.\"\"\"\n return self._load_json_file(self.user_profiles_file)\n\n def _save_user_profiles(self) -> bool:\n \"\"\"Save user profiles to file.\"\"\"\n return self._save_json_file(self.user_profiles_file, self.user_profiles)\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n all_profiles = deepcopy(self.default_profiles)\n all_profiles.update(self.user_profiles)\n return all_profiles\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name.\"\"\"\n # Check user profiles first, then default profiles\n if name in self.user_profiles:\n return deepcopy(self.user_profiles[name])\n elif name in self.default_profiles:\n return deepcopy(self.default_profiles[name])\n return None\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"\n Save or update a user profile with validation.\n\n Args:\n name: Profile name\n profile: Profile data to save\n\n Returns:\n True if saved successfully\n\n Raises:\n ProfileError: If profile validation fails or save fails\n \"\"\"\n try:\n # Validate profile structure\n if not isinstance(profile, dict):\n raise ProfileError(\n \"Profile must be a dictionary\",\n profile_name=name,\n error_code=\"INVALID_PROFILE_TYPE\",\n )\n\n # Process LoRA configuration if present\n if \"config\" in profile:\n config = profile[\"config\"]\n\n # Handle LoRA adapters in config\n if \"lora_adapters\" in config:\n # Validate LoRA adapter entries\n lora_adapters = config[\"lora_adapters\"]\n if isinstance(lora_adapters, list):\n # Ensure each adapter has required fields\n for adapter in lora_adapters:\n if not isinstance(adapter, dict):\n continue\n if \"path\" not in adapter and \"name\" in adapter:\n # Try to resolve adapter by name\n adapter[\"path\"] = self._resolve_lora_path(\n adapter[\"name\"]\n )\n\n # Convert to lora_modules format for vLLM\n if lora_adapters:\n config[\"enable_lora\"] = True\n lora_modules = []\n for adapter in lora_adapters:\n if isinstance(adapter, dict):\n name = adapter.get(\"name\", \"adapter\")\n path = adapter.get(\"path\", \"\")\n if path:\n lora_modules.append(f\"{name}={path}\")\n if lora_modules:\n config[\"lora_modules\"] = \" \".join(lora_modules)\n\n # Save the profile\n self.user_profiles[name] = deepcopy(profile)\n\n if not self._save_user_profiles():\n raise ProfileError(\n \"Failed to save profile to disk\",\n profile_name=name,\n error_code=\"PROFILE_SAVE_FAILED\",\n )\n\n logger.info(f\"Successfully saved user profile: {name}\")\n return True\n\n except ProfileError:\n raise\n except Exception as e:\n logger.error(f\"Unexpected error saving profile {name}: {e}\")\n raise ProfileError(\n f\"Unexpected error saving profile: {e}\",\n profile_name=name,\n error_code=\"PROFILE_SAVE_ERROR\",\n ) from e\n\n def _resolve_lora_path(self, adapter_name: str) -> str:\n \"\"\"\n Try to resolve a LoRA adapter path by name.\n\n Args:\n adapter_name: Name of the LoRA adapter\n\n Returns:\n Path to the adapter if found, empty string otherwise\n \"\"\"\n try:\n from ..models import scan_for_lora_adapters\n\n adapters = scan_for_lora_adapters()\n for adapter in adapters:\n if (\n adapter.get(\"name\") == adapter_name\n or adapter.get(\"display_name\") == adapter_name\n ):\n return adapter.get(\"path\", \"\")\n except Exception as e:\n logger.debug(f\"Could not resolve LoRA path for {adapter_name}: {e}\")\n return \"\"\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n if name in self.user_profiles:\n del self.user_profiles[name]\n return self._save_user_profiles()\n return False\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n profile = self.get_profile(profile_name)\n if not profile:\n logger.error(f\"Profile '{profile_name}' not found\")\n return False\n\n export_data = {\"version\": \"1.0\", \"profile\": profile}\n\n try:\n with open(filepath, \"w\") as f:\n json.dump(export_data, f, indent=2)\n logger.info(f\"Profile '{profile_name}' exported to {filepath}\")\n return True\n except Exception as e:\n logger.error(f\"Error exporting profile: {e}\")\n return False\n\n def import_profile(\n self,\n filepath: Path,\n new_name: Optional[str] = None,\n validate_config_func: Optional[Callable] = None,\n ) -> bool:\n \"\"\"\n Import a profile from a JSON file with comprehensive validation.\n\n Args:\n filepath: Path to the profile file\n new_name: Optional new name for the profile\n validate_config_func: Optional function to validate profile config\n\n Returns:\n True if imported successfully\n\n Raises:\n ProfileError: If import fails for any reason\n \"\"\"\n try:\n # Check file exists\n if not filepath.exists():\n raise ProfileError(\n f\"Profile file not found: {filepath}\",\n error_code=\"PROFILE_FILE_NOT_FOUND\",\n )\n\n # Load and parse file\n try:\n with open(filepath, \"r\") as f:\n data = json.load(f)\n except json.JSONDecodeError as e:\n raise ProfileError(\n f\"Invalid JSON in profile file: {e}\",\n error_code=\"PROFILE_INVALID_JSON\",\n ) from e\n\n # Validate file format\n if not isinstance(data, dict) or \"profile\" not in data:\n raise ProfileError(\n \"Invalid profile file format - missing 'profile' key\",\n error_code=\"PROFILE_INVALID_FORMAT\",\n )\n\n profile = data[\"profile\"]\n name = new_name or profile.get(\"name\", filepath.stem)\n\n # Validate profile configuration if function provided\n if validate_config_func and \"config\" in profile:\n is_valid, errors = validate_config_func(profile[\"config\"])\n if not is_valid:\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n # Save the profile\n return self.save_user_profile(name, profile)\n\n except ProfileError:\n raise\n except Exception as e:\n logger.error(f\"Unexpected error importing profile from {filepath}: {e}\")\n raise ProfileError(\n f\"Failed to import profile: {e}\", error_code=\"PROFILE_IMPORT_ERROR\"\n ) from e\n\n def list_profile_names(self) -> Dict[str, List[str]]:\n \"\"\"\n List all profile names categorized by type.\n\n Returns:\n Dictionary with 'default' and 'user' lists of profile names\n \"\"\"\n return {\n \"default\": list(self.default_profiles.keys()),\n \"user\": list(self.user_profiles.keys()),\n }\n\n def profile_exists(self, name: str) -> bool:\n \"\"\"Check if a profile exists (in either default or user profiles).\"\"\"\n return name in self.default_profiles or name in self.user_profiles\n\n def is_user_profile(self, name: str) -> bool:\n \"\"\"Check if a profile is a user-created profile.\"\"\"\n return name in self.user_profiles\n\n def has_user_override(self, name: str) -> bool:\n \"\"\"\n Check if a built-in profile has been overridden by a user profile.\n\n Args:\n name: Profile name to check\n\n Returns:\n True if this is a built-in profile that has a user override\n \"\"\"\n return name in self.default_profiles and name in self.user_profiles\n\n def get_original_default_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get the original default profile without any user overrides.\n\n Args:\n name: Profile name\n\n Returns:\n Original default profile if it exists, None otherwise\n \"\"\"\n if name in self.default_profiles:\n return deepcopy(self.default_profiles[name])\n return None\n\n def reset_to_default(self, name: str) -> bool:\n \"\"\"\n Reset a customized built-in profile to its default settings.\n\n This removes the user override for a built-in profile.\n\n Args:\n name: Profile name to reset\n\n Returns:\n True if reset successfully, False otherwise\n \"\"\"\n # Only reset if this is a built-in profile with a user override\n if self.has_user_override(name):\n return self.delete_user_profile(name)\n return False\n\n def get_profile_count(self) -> Dict[str, int]:\n \"\"\"Get count of profiles by type.\"\"\"\n return {\n \"default\": len(self.default_profiles),\n \"user\": len(self.user_profiles),\n \"total\": len(self.default_profiles) + len(self.user_profiles),\n }\n\n def apply_dynamic_defaults(self, profile_config: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Apply dynamic defaults to a profile configuration.\n\n This function intelligently sets tensor_parallel_size for multi-GPU systems.\n For single GPU systems, it allows vLLM to use its default behavior.\n\n Note: vLLM defaults to using only 1 GPU unless tensor_parallel_size is explicitly set.\n\n Args:\n profile_config: The profile configuration to enhance\n\n Returns:\n Enhanced profile configuration with dynamic defaults applied\n \"\"\"\n config = deepcopy(profile_config)\n\n # Apply dynamic tensor_parallel_size if not specified\n # Note: vLLM defaults to single GPU, so we only set this for multi-GPU systems\n # where tensor parallelism would be beneficial\n if \"tensor_parallel_size\" not in config:\n gpu_count = self._get_gpu_count()\n if gpu_count > 1:\n config[\"tensor_parallel_size\"] = gpu_count\n logger.debug(\n f\"Set tensor_parallel_size to {gpu_count} for multi-GPU system\"\n )\n # For single GPU, let vLLM use its default (no tensor_parallel_size needed)\n\n return config\n\n def _get_gpu_count(self) -> int:\n \"\"\"\n Get the number of available GPUs for tensor parallelism.\n\n Returns:\n Number of GPUs available, defaults to 1 if detection fails\n \"\"\"\n try:\n gpus = get_gpu_info()\n gpu_count = len(gpus) if gpus else 1\n logger.debug(f\"Detected {gpu_count} GPU(s)\")\n return gpu_count\n except Exception as e:\n logger.warning(f\"Failed to detect GPU count, defaulting to 1: {e}\")\n return 1", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 14008}, "tests/proxy/test_router.py::133": {"resolved_imports": ["src/vllm_cli/proxy/router.py"], "used_names": [], "enclosing_function": "test_simple_routing_scenario", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_config_manager.py::177": {"resolved_imports": ["src/vllm_cli/config/manager.py"], "used_names": ["ConfigManager", "Mock", "patch"], "enclosing_function": "test_validate_config_invalid", "extracted_code": "# Source: src/vllm_cli/config/manager.py\nclass ConfigManager:\n \"\"\"\n Enhanced configuration manager with comprehensive validation support.\n\n This class manages configuration files, profiles, and validation using\n the new validation framework. It provides a clean API for configuration\n operations while ensuring data integrity through comprehensive validation.\n\n Attributes:\n config_dir: Directory for configuration files\n validation_registry: Registry of validation rules\n compatibility_validator: Validator for parameter combinations\n \"\"\"\n\n def __init__(self):\n # Paths for configuration files\n self.config_dir = Path.home() / \".config\" / \"vllm-cli\"\n self.config_file = self.config_dir / \"config.yaml\"\n\n # Ensure config directory exists\n self.config_dir.mkdir(parents=True, exist_ok=True)\n\n # Initialize sub-managers\n self.schema_manager = SchemaManager()\n self.profile_manager = ProfileManager(self.config_dir)\n self.persistence_manager = PersistenceManager()\n self.shortcut_manager = ShortcutManager(self.config_dir)\n\n # Initialize validation system\n self.validation_registry = create_vllm_validation_registry()\n self.compatibility_validator = create_compatibility_validator(\n self.validation_registry\n )\n\n # Load main configuration\n self.config = self._load_config()\n\n def _load_config(self) -> Dict[str, Any]:\n \"\"\"Load main configuration file (legacy YAML support).\"\"\"\n return self.persistence_manager.load_yaml_file(self.config_file)\n\n def _save_config(self) -> None:\n \"\"\"Save main configuration file.\"\"\"\n self.persistence_manager.save_yaml_file(self.config_file, self.config)\n\n def get_argument_info(self, arg_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get detailed information about a specific argument.\"\"\"\n return self.schema_manager.get_argument_info(arg_name)\n\n def get_arguments_by_category(self, category: str) -> List[Dict[str, Any]]:\n \"\"\"Get all arguments belonging to a specific category.\"\"\"\n return self.schema_manager.get_arguments_by_category(category)\n\n def get_category_info(self, category: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get information about a specific category.\"\"\"\n return self.schema_manager.get_category_info(category)\n\n def get_ordered_categories(self) -> List[Tuple[str, Dict[str, Any]]]:\n \"\"\"Get categories ordered by their display order.\"\"\"\n return self.schema_manager.get_ordered_categories()\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n return self.profile_manager.get_all_profiles()\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name with dynamic defaults applied.\"\"\"\n profile = self.profile_manager.get_profile(name)\n if profile and \"config\" in profile:\n # Apply dynamic defaults to the profile configuration\n profile[\"config\"] = self.profile_manager.apply_dynamic_defaults(\n profile[\"config\"]\n )\n return profile\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"Save or update a user profile with validation.\"\"\"\n # Validate profile configuration if present\n if \"config\" in profile:\n is_valid, errors = self.validate_config(profile[\"config\"])\n if not is_valid:\n from ..errors import ProfileError\n\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n return self.profile_manager.save_user_profile(name, profile)\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n return self.profile_manager.delete_user_profile(name)\n\n @property\n def default_profiles(self) -> Dict[str, Any]:\n \"\"\"Get default profiles.\"\"\"\n return self.profile_manager.default_profiles\n\n @property\n def user_profiles(self) -> Dict[str, Any]:\n \"\"\"Get user profiles.\"\"\"\n return self.profile_manager.user_profiles\n\n def validate_config(self, config: Dict[str, Any]) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate a configuration using the new validation framework.\n\n This method uses the comprehensive validation system to check\n configuration values, types, ranges, and dependencies.\n\n Args:\n config: Configuration dictionary to validate\n\n Returns:\n Tuple of (is_valid, list_of_error_messages)\n\n Raises:\n ConfigurationError: If validation system fails\n \"\"\"\n try:\n # Use new validation system\n result = self.validation_registry.validate_config(config)\n\n # Convert validation errors to string messages for backward compatibility\n error_messages = result.get_error_messages()\n\n # Add warnings if any\n if result.warnings:\n for warning in result.warnings:\n logger.warning(f\"Configuration warning: {warning}\")\n\n return result.is_valid(), error_messages\n\n except Exception as e:\n logger.error(f\"Error during configuration validation: {e}\")\n raise ConfigurationError(\n f\"Validation system error: {e}\", error_code=\"VALIDATION_SYSTEM_ERROR\"\n ) from e\n\n def validate_argument_combination(\n self, config: Dict[str, Any]\n ) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate that argument combinations are compatible using the new compatibility validator.\n\n Args:\n config: Configuration dictionary to check for compatibility\n\n Returns:\n Tuple of (is_valid, list_of_warnings_or_errors)\n \"\"\"\n try:\n issues = self.compatibility_validator.validate_compatibility(config)\n\n warnings = []\n errors = []\n\n for issue in issues:\n message = issue[\"message\"]\n if issue[\"severity\"] == \"error\":\n errors.append(message)\n else:\n warnings.append(message)\n\n # Log warnings\n for warning in warnings:\n logger.warning(f\"Configuration compatibility warning: {warning}\")\n\n # Return all issues as warnings for backward compatibility\n # (errors are treated as warnings in the legacy interface)\n all_issues = errors + warnings\n\n return len(errors) == 0, all_issues\n\n except Exception as e:\n logger.error(f\"Error during compatibility validation: {e}\")\n return False, [f\"Compatibility validation error: {e}\"]\n\n def build_cli_args(self, config: Dict[str, Any]) -> List[str]:\n \"\"\"\n Build command-line arguments from a configuration dictionary.\n\n Only includes arguments that are explicitly set in the config.\n Handles special cases like LoRA modules.\n \"\"\"\n args = []\n\n # Special handling for model (positional argument)\n # Check if this is a GGUF/Ollama configuration\n if (\n isinstance(config.get(\"model\"), dict)\n and \"quantization\" in config[\"model\"]\n and config[\"model\"][\"quantization\"] == \"gguf\"\n ):\n # Extract GGUF model config\n gguf_config = config[\"model\"]\n model_path = gguf_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", model_path])\n\n # Set quantization to gguf\n config[\"quantization\"] = \"gguf\"\n\n # Add served-model-name if provided (for Ollama models)\n if \"served_model_name\" in gguf_config:\n config[\"served_model_name\"] = gguf_config[\"served_model_name\"]\n logger.info(\n f\"Configuring GGUF model: {model_path} as {gguf_config['served_model_name']}\"\n )\n else:\n logger.info(f\"Configuring GGUF model: {model_path}\")\n\n # Check if this is a LoRA configuration\n elif (\n isinstance(config.get(\"model\"), dict) and \"lora_modules\" in config[\"model\"]\n ):\n # Extract base model and LoRA config\n lora_config = config[\"model\"]\n base_model = lora_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", base_model])\n\n # Enable LoRA support when modules are present\n args.append(\"--enable-lora\")\n\n # Track maximum rank for all LoRA modules\n max_rank = 16 # Default minimum\n\n # Add LoRA modules\n for lora in lora_config.get(\"lora_modules\", []):\n lora_path = lora.get(\"path\", \"\")\n if lora_path:\n # vLLM expects --lora-modules with name=path format\n lora_name = lora.get(\"name\", \"adapter\")\n args.extend([\"--lora-modules\", f\"{lora_name}={lora_path}\"])\n\n # Track maximum rank\n lora_rank = lora.get(\"rank\", 16)\n max_rank = max(max_rank, lora_rank)\n\n # Add max-lora-rank parameter\n args.extend([\"--max-lora-rank\", str(max_rank)])\n\n elif \"model\" in config:\n args.extend([\"serve\", config[\"model\"]])\n\n # Handle lora_modules if present as a string (from CLI)\n if \"lora_modules\" in config and config[\"lora_modules\"]:\n # Enable LoRA support\n if \"--enable-lora\" not in args:\n args.append(\"--enable-lora\")\n\n # Parse and add LoRA modules\n lora_modules_str = config[\"lora_modules\"]\n if isinstance(lora_modules_str, str):\n # Split by space and add each module\n for module in lora_modules_str.split():\n args.extend([\"--lora-modules\", module])\n\n # Add max-lora-rank if not already added\n # Use a safe default of 64 which should cover most LoRA adapters\n if \"--max-lora-rank\" not in args:\n # Check if max_lora_rank is explicitly set in config\n if \"max_lora_rank\" not in config:\n args.extend([\"--max-lora-rank\", \"64\"])\n\n for arg_name, value in config.items():\n # Skip special keys and None values\n if (\n arg_name in [\"model\", \"name\", \"description\", \"icon\", \"lora_modules\"]\n or value is None\n ):\n continue\n\n arg_info = self.schema_manager.get_argument_info(arg_name)\n if not arg_info:\n logger.warning(f\"Unknown argument in config: {arg_name}\")\n continue\n\n cli_flag = arg_info.get(\"cli_flag\")\n if not cli_flag:\n continue\n\n arg_type = arg_info.get(\"type\")\n\n if arg_type == \"boolean\":\n if value: # Only add flag if True\n args.append(cli_flag)\n elif arg_type in [\"integer\", \"float\", \"string\", \"choice\"]:\n args.extend([cli_flag, str(value)])\n else:\n logger.warning(f\"Unknown argument type for {arg_name}: {arg_type}\")\n\n return args\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n return self.profile_manager.export_profile(profile_name, filepath)\n\n def import_profile(self, filepath: Path, new_name: Optional[str] = None) -> bool:\n \"\"\"Import a profile from a JSON file with comprehensive validation.\"\"\"\n return self.profile_manager.import_profile(\n filepath, new_name, self.validate_config\n )\n\n def get_last_config(self) -> Optional[Dict[str, Any]]:\n \"\"\"Get the last used server configuration.\"\"\"\n return self.config.get(\"last_config\")\n\n def save_last_config(self, config: Dict[str, Any]) -> None:\n \"\"\"Save the last used server configuration.\"\"\"\n self.config[\"last_config\"] = config\n self._save_config()\n\n def get_recent_models(self, limit: int = 5) -> List[str]:\n \"\"\"Get recently used models.\"\"\"\n return self.config.get(\"recent_models\", [])[:limit]\n\n def add_recent_model(self, model: str) -> None:\n \"\"\"Add a model to recent models list.\"\"\"\n recent = self.config.get(\"recent_models\", [])\n if model in recent:\n recent.remove(model)\n recent.insert(0, model)\n self.config[\"recent_models\"] = recent[:10] # Keep only last 10\n self._save_config()\n\n def clear_cache(self) -> None:\n \"\"\"Clear cached data.\"\"\"\n cache_file = self.config_dir / \"cache.json\"\n if cache_file.exists():\n cache_file.unlink()\n self.config.pop(\"last_config\", None)\n self.config.pop(\"recent_models\", None)\n self._save_config()\n logger.info(\"Cache cleared\")\n\n def get_server_defaults(self) -> Dict[str, Any]:\n \"\"\"Get default server settings.\"\"\"\n return self.config.get(\n \"server_defaults\",\n {\n \"default_port\": 8000,\n \"auto_restart\": False,\n \"log_level\": \"info\",\n \"cleanup_on_exit\": True, # Default to cleaning up servers on exit\n },\n )\n\n def save_server_defaults(self, defaults: Dict[str, Any]) -> None:\n \"\"\"Save default server settings.\"\"\"\n self.config[\"server_defaults\"] = defaults\n self._save_config()\n\n def get_ui_preferences(self) -> Dict[str, Any]:\n \"\"\"Get UI preferences including progress bar style and log display settings.\"\"\"\n return self.config.get(\n \"ui_preferences\",\n {\n \"progress_bar_style\": \"blocks\", # Default style\n \"show_gpu_in_monitor\": True,\n \"log_lines_startup\": 50, # Number of log lines to show during startup\n \"log_lines_monitor\": 50, # Number of log lines to show in server monitor\n \"startup_refresh_rate\": 4.0, # Hz for startup log refresh\n \"monitor_refresh_rate\": 1.0, # Hz for monitor log refresh\n },\n )\n\n def save_ui_preferences(self, preferences: Dict[str, Any]) -> None:\n \"\"\"Save UI preferences.\"\"\"\n self.config[\"ui_preferences\"] = preferences\n self._save_config()\n\n # Shortcut management methods\n def get_all_shortcuts(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all shortcuts.\"\"\"\n return self.shortcut_manager.get_all_shortcuts()\n\n def get_shortcut(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific shortcut by name.\"\"\"\n return self.shortcut_manager.get_shortcut(name)\n\n def save_shortcut(self, name: str, shortcut_data: Dict[str, Any]) -> bool:\n \"\"\"Save or update a shortcut.\"\"\"\n return self.shortcut_manager.save_shortcut(name, shortcut_data)\n\n def delete_shortcut(self, name: str) -> bool:\n \"\"\"Delete a shortcut.\"\"\"\n return self.shortcut_manager.delete_shortcut(name)\n\n def list_shortcuts(self) -> List[Dict[str, Any]]:\n \"\"\"List all shortcuts with summary information.\"\"\"\n return self.shortcut_manager.list_shortcuts()\n\n def get_recent_shortcuts(self, limit: int = 5) -> List[Dict[str, Any]]:\n \"\"\"Get recently used shortcuts.\"\"\"\n return self.shortcut_manager.get_recent_shortcuts(limit)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 15704}, "tests/test_profiles.py::160": {"resolved_imports": ["src/vllm_cli/config/profiles.py"], "used_names": ["ProfileManager", "patch"], "enclosing_function": "test_get_all_profiles", "extracted_code": "# Source: src/vllm_cli/config/profiles.py\nclass ProfileManager:\n \"\"\"\n Manages user profiles for vLLM configurations.\n\n Handles creation, retrieval, updating, and deletion of user profiles\n with validation and persistence.\n \"\"\"\n\n def __init__(self, config_dir: Path):\n self.config_dir = config_dir\n self.user_profiles_file = config_dir / \"user_profiles.json\"\n\n # Paths for schema files (packaged with application)\n schema_dir = Path(__file__).parent.parent / \"schemas\"\n self.default_profiles_file = schema_dir / \"default_profiles.json\"\n\n # Load profiles\n self.default_profiles = self._load_default_profiles()\n self.user_profiles = self._load_user_profiles()\n\n def _load_json_file(self, filepath: Path) -> Dict[str, Any]:\n \"\"\"Load a JSON file safely.\"\"\"\n if filepath.exists():\n try:\n with open(filepath, \"r\") as f:\n return json.load(f)\n except Exception as e:\n logger.error(f\"Error loading {filepath}: {e}\")\n return {}\n\n def _save_json_file(self, filepath: Path, data: Dict[str, Any]) -> bool:\n \"\"\"Save data to a JSON file.\"\"\"\n try:\n with open(filepath, \"w\") as f:\n json.dump(data, f, indent=2)\n return True\n except Exception as e:\n logger.error(f\"Error saving {filepath}: {e}\")\n return False\n\n def _load_default_profiles(self) -> Dict[str, Any]:\n \"\"\"Load default built-in profiles.\"\"\"\n profiles = self._load_json_file(self.default_profiles_file)\n return profiles.get(\"profiles\", {})\n\n def _load_user_profiles(self) -> Dict[str, Any]:\n \"\"\"Load user-created custom profiles.\"\"\"\n return self._load_json_file(self.user_profiles_file)\n\n def _save_user_profiles(self) -> bool:\n \"\"\"Save user profiles to file.\"\"\"\n return self._save_json_file(self.user_profiles_file, self.user_profiles)\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n all_profiles = deepcopy(self.default_profiles)\n all_profiles.update(self.user_profiles)\n return all_profiles\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name.\"\"\"\n # Check user profiles first, then default profiles\n if name in self.user_profiles:\n return deepcopy(self.user_profiles[name])\n elif name in self.default_profiles:\n return deepcopy(self.default_profiles[name])\n return None\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"\n Save or update a user profile with validation.\n\n Args:\n name: Profile name\n profile: Profile data to save\n\n Returns:\n True if saved successfully\n\n Raises:\n ProfileError: If profile validation fails or save fails\n \"\"\"\n try:\n # Validate profile structure\n if not isinstance(profile, dict):\n raise ProfileError(\n \"Profile must be a dictionary\",\n profile_name=name,\n error_code=\"INVALID_PROFILE_TYPE\",\n )\n\n # Process LoRA configuration if present\n if \"config\" in profile:\n config = profile[\"config\"]\n\n # Handle LoRA adapters in config\n if \"lora_adapters\" in config:\n # Validate LoRA adapter entries\n lora_adapters = config[\"lora_adapters\"]\n if isinstance(lora_adapters, list):\n # Ensure each adapter has required fields\n for adapter in lora_adapters:\n if not isinstance(adapter, dict):\n continue\n if \"path\" not in adapter and \"name\" in adapter:\n # Try to resolve adapter by name\n adapter[\"path\"] = self._resolve_lora_path(\n adapter[\"name\"]\n )\n\n # Convert to lora_modules format for vLLM\n if lora_adapters:\n config[\"enable_lora\"] = True\n lora_modules = []\n for adapter in lora_adapters:\n if isinstance(adapter, dict):\n name = adapter.get(\"name\", \"adapter\")\n path = adapter.get(\"path\", \"\")\n if path:\n lora_modules.append(f\"{name}={path}\")\n if lora_modules:\n config[\"lora_modules\"] = \" \".join(lora_modules)\n\n # Save the profile\n self.user_profiles[name] = deepcopy(profile)\n\n if not self._save_user_profiles():\n raise ProfileError(\n \"Failed to save profile to disk\",\n profile_name=name,\n error_code=\"PROFILE_SAVE_FAILED\",\n )\n\n logger.info(f\"Successfully saved user profile: {name}\")\n return True\n\n except ProfileError:\n raise\n except Exception as e:\n logger.error(f\"Unexpected error saving profile {name}: {e}\")\n raise ProfileError(\n f\"Unexpected error saving profile: {e}\",\n profile_name=name,\n error_code=\"PROFILE_SAVE_ERROR\",\n ) from e\n\n def _resolve_lora_path(self, adapter_name: str) -> str:\n \"\"\"\n Try to resolve a LoRA adapter path by name.\n\n Args:\n adapter_name: Name of the LoRA adapter\n\n Returns:\n Path to the adapter if found, empty string otherwise\n \"\"\"\n try:\n from ..models import scan_for_lora_adapters\n\n adapters = scan_for_lora_adapters()\n for adapter in adapters:\n if (\n adapter.get(\"name\") == adapter_name\n or adapter.get(\"display_name\") == adapter_name\n ):\n return adapter.get(\"path\", \"\")\n except Exception as e:\n logger.debug(f\"Could not resolve LoRA path for {adapter_name}: {e}\")\n return \"\"\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n if name in self.user_profiles:\n del self.user_profiles[name]\n return self._save_user_profiles()\n return False\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n profile = self.get_profile(profile_name)\n if not profile:\n logger.error(f\"Profile '{profile_name}' not found\")\n return False\n\n export_data = {\"version\": \"1.0\", \"profile\": profile}\n\n try:\n with open(filepath, \"w\") as f:\n json.dump(export_data, f, indent=2)\n logger.info(f\"Profile '{profile_name}' exported to {filepath}\")\n return True\n except Exception as e:\n logger.error(f\"Error exporting profile: {e}\")\n return False\n\n def import_profile(\n self,\n filepath: Path,\n new_name: Optional[str] = None,\n validate_config_func: Optional[Callable] = None,\n ) -> bool:\n \"\"\"\n Import a profile from a JSON file with comprehensive validation.\n\n Args:\n filepath: Path to the profile file\n new_name: Optional new name for the profile\n validate_config_func: Optional function to validate profile config\n\n Returns:\n True if imported successfully\n\n Raises:\n ProfileError: If import fails for any reason\n \"\"\"\n try:\n # Check file exists\n if not filepath.exists():\n raise ProfileError(\n f\"Profile file not found: {filepath}\",\n error_code=\"PROFILE_FILE_NOT_FOUND\",\n )\n\n # Load and parse file\n try:\n with open(filepath, \"r\") as f:\n data = json.load(f)\n except json.JSONDecodeError as e:\n raise ProfileError(\n f\"Invalid JSON in profile file: {e}\",\n error_code=\"PROFILE_INVALID_JSON\",\n ) from e\n\n # Validate file format\n if not isinstance(data, dict) or \"profile\" not in data:\n raise ProfileError(\n \"Invalid profile file format - missing 'profile' key\",\n error_code=\"PROFILE_INVALID_FORMAT\",\n )\n\n profile = data[\"profile\"]\n name = new_name or profile.get(\"name\", filepath.stem)\n\n # Validate profile configuration if function provided\n if validate_config_func and \"config\" in profile:\n is_valid, errors = validate_config_func(profile[\"config\"])\n if not is_valid:\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n # Save the profile\n return self.save_user_profile(name, profile)\n\n except ProfileError:\n raise\n except Exception as e:\n logger.error(f\"Unexpected error importing profile from {filepath}: {e}\")\n raise ProfileError(\n f\"Failed to import profile: {e}\", error_code=\"PROFILE_IMPORT_ERROR\"\n ) from e\n\n def list_profile_names(self) -> Dict[str, List[str]]:\n \"\"\"\n List all profile names categorized by type.\n\n Returns:\n Dictionary with 'default' and 'user' lists of profile names\n \"\"\"\n return {\n \"default\": list(self.default_profiles.keys()),\n \"user\": list(self.user_profiles.keys()),\n }\n\n def profile_exists(self, name: str) -> bool:\n \"\"\"Check if a profile exists (in either default or user profiles).\"\"\"\n return name in self.default_profiles or name in self.user_profiles\n\n def is_user_profile(self, name: str) -> bool:\n \"\"\"Check if a profile is a user-created profile.\"\"\"\n return name in self.user_profiles\n\n def has_user_override(self, name: str) -> bool:\n \"\"\"\n Check if a built-in profile has been overridden by a user profile.\n\n Args:\n name: Profile name to check\n\n Returns:\n True if this is a built-in profile that has a user override\n \"\"\"\n return name in self.default_profiles and name in self.user_profiles\n\n def get_original_default_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get the original default profile without any user overrides.\n\n Args:\n name: Profile name\n\n Returns:\n Original default profile if it exists, None otherwise\n \"\"\"\n if name in self.default_profiles:\n return deepcopy(self.default_profiles[name])\n return None\n\n def reset_to_default(self, name: str) -> bool:\n \"\"\"\n Reset a customized built-in profile to its default settings.\n\n This removes the user override for a built-in profile.\n\n Args:\n name: Profile name to reset\n\n Returns:\n True if reset successfully, False otherwise\n \"\"\"\n # Only reset if this is a built-in profile with a user override\n if self.has_user_override(name):\n return self.delete_user_profile(name)\n return False\n\n def get_profile_count(self) -> Dict[str, int]:\n \"\"\"Get count of profiles by type.\"\"\"\n return {\n \"default\": len(self.default_profiles),\n \"user\": len(self.user_profiles),\n \"total\": len(self.default_profiles) + len(self.user_profiles),\n }\n\n def apply_dynamic_defaults(self, profile_config: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Apply dynamic defaults to a profile configuration.\n\n This function intelligently sets tensor_parallel_size for multi-GPU systems.\n For single GPU systems, it allows vLLM to use its default behavior.\n\n Note: vLLM defaults to using only 1 GPU unless tensor_parallel_size is explicitly set.\n\n Args:\n profile_config: The profile configuration to enhance\n\n Returns:\n Enhanced profile configuration with dynamic defaults applied\n \"\"\"\n config = deepcopy(profile_config)\n\n # Apply dynamic tensor_parallel_size if not specified\n # Note: vLLM defaults to single GPU, so we only set this for multi-GPU systems\n # where tensor parallelism would be beneficial\n if \"tensor_parallel_size\" not in config:\n gpu_count = self._get_gpu_count()\n if gpu_count > 1:\n config[\"tensor_parallel_size\"] = gpu_count\n logger.debug(\n f\"Set tensor_parallel_size to {gpu_count} for multi-GPU system\"\n )\n # For single GPU, let vLLM use its default (no tensor_parallel_size needed)\n\n return config\n\n def _get_gpu_count(self) -> int:\n \"\"\"\n Get the number of available GPUs for tensor parallelism.\n\n Returns:\n Number of GPUs available, defaults to 1 if detection fails\n \"\"\"\n try:\n gpus = get_gpu_info()\n gpu_count = len(gpus) if gpus else 1\n logger.debug(f\"Detected {gpu_count} GPU(s)\")\n return gpu_count\n except Exception as e:\n logger.warning(f\"Failed to detect GPU count, defaulting to 1: {e}\")\n return 1", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 14008}, "tests/test_model_manager.py::30": {"resolved_imports": ["src/vllm_cli/models/cache.py", "src/vllm_cli/models/manager.py"], "used_names": ["ModelCache"], "enclosing_function": "test_cache_models_and_get", "extracted_code": "# Source: src/vllm_cli/models/cache.py\nclass ModelCache:\n \"\"\"\n Cache for model discovery results.\n\n Provides time-based caching of model listings to avoid expensive\n directory scanning operations when model data is accessed frequently.\n \"\"\"\n\n def __init__(self, ttl_seconds: float = 30.0):\n \"\"\"\n Initialize model cache.\n\n Args:\n ttl_seconds: Time-to-live for cached data in seconds\n \"\"\"\n self.ttl_seconds = ttl_seconds\n self._cache: Optional[Tuple[float, List[Dict[str, Any]]]] = None\n self._stats = {\"hits\": 0, \"misses\": 0, \"updates\": 0}\n\n def get_cached_models(self) -> Optional[List[Dict[str, Any]]]:\n \"\"\"\n Get cached model list if still valid.\n\n Returns:\n List of cached models if cache is valid, None if expired or empty\n \"\"\"\n if self._cache is None:\n self._stats[\"misses\"] += 1\n return None\n\n cache_time, cached_data = self._cache\n\n # Check if cache is still valid\n if time.time() - cache_time < self.ttl_seconds:\n self._stats[\"hits\"] += 1\n logger.debug(f\"Cache hit: returning {len(cached_data)} cached models\")\n return cached_data.copy() # Return copy to prevent modification\n else:\n # Cache expired\n self._stats[\"misses\"] += 1\n logger.debug(\"Cache expired\")\n self._cache = None\n return None\n\n def cache_models(self, models: List[Dict[str, Any]]) -> None:\n \"\"\"\n Cache a list of models.\n\n Args:\n models: List of model dictionaries to cache\n \"\"\"\n self._cache = (time.time(), models.copy())\n self._stats[\"updates\"] += 1\n logger.debug(f\"Cached {len(models)} models\")\n\n def clear_cache(self) -> None:\n \"\"\"Clear the model cache.\"\"\"\n self._cache = None\n # Increment misses to reflect that the next access will be a miss\n self._stats[\"misses\"] += 1\n logger.debug(\"Model cache cleared\")\n\n def is_cached(self) -> bool:\n \"\"\"\n Check if there is valid cached data.\n\n Returns:\n True if cache contains valid data, False otherwise\n \"\"\"\n if self._cache is None:\n return False\n\n cache_time, _ = self._cache\n return time.time() - cache_time < self.ttl_seconds\n\n def get_cache_age(self) -> Optional[float]:\n \"\"\"\n Get the age of cached data in seconds.\n\n Returns:\n Age in seconds if cache exists, None if no cache\n \"\"\"\n if self._cache is None:\n return None\n\n cache_time, _ = self._cache\n return time.time() - cache_time\n\n def get_cache_stats(self) -> Dict[str, Any]:\n \"\"\"\n Get cache statistics.\n\n Returns:\n Dictionary with cache performance statistics\n \"\"\"\n total_requests = self._stats[\"hits\"] + self._stats[\"misses\"]\n hit_rate = (\n (self._stats[\"hits\"] / total_requests * 100) if total_requests > 0 else 0\n )\n\n stats = {\n \"hits\": self._stats[\"hits\"],\n \"misses\": self._stats[\"misses\"],\n \"updates\": self._stats[\"updates\"],\n \"total_requests\": total_requests,\n \"hit_rate_percent\": round(hit_rate, 2),\n \"is_cached\": self.is_cached(),\n \"cache_age_seconds\": self.get_cache_age(),\n \"ttl_seconds\": self.ttl_seconds,\n }\n\n if self._cache:\n _, cached_data = self._cache\n stats[\"cached_models_count\"] = len(cached_data)\n else:\n stats[\"cached_models_count\"] = 0\n\n return stats\n\n def get_stats(self) -> Dict[str, Any]:\n \"\"\"\n Alias for get_cache_stats() for backward compatibility.\n\n Returns:\n Dictionary with cache performance statistics\n \"\"\"\n return self.get_cache_stats()\n\n def reset_stats(self) -> None:\n \"\"\"Reset cache statistics.\"\"\"\n self._stats = {\"hits\": 0, \"misses\": 0, \"updates\": 0}\n logger.debug(\"Cache statistics reset\")\n\n def set_ttl(self, ttl_seconds: float) -> None:\n \"\"\"\n Set new TTL for cache.\n\n Args:\n ttl_seconds: New time-to-live in seconds\n \"\"\"\n old_ttl = self.ttl_seconds\n self.ttl_seconds = ttl_seconds\n logger.debug(f\"Cache TTL changed from {old_ttl}s to {ttl_seconds}s\")\n\n def get_cached_model_count(self) -> int:\n \"\"\"\n Get the number of models currently cached.\n\n Returns:\n Number of cached models, 0 if no cache\n \"\"\"\n if self._cache is None:\n return 0\n\n _, cached_data = self._cache\n return len(cached_data)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 4761}, "tests/test_profiles.py::57": {"resolved_imports": ["src/vllm_cli/config/profiles.py"], "used_names": ["ProfileManager", "json"], "enclosing_function": "test_load_user_profiles_existing", "extracted_code": "# Source: src/vllm_cli/config/profiles.py\nclass ProfileManager:\n \"\"\"\n Manages user profiles for vLLM configurations.\n\n Handles creation, retrieval, updating, and deletion of user profiles\n with validation and persistence.\n \"\"\"\n\n def __init__(self, config_dir: Path):\n self.config_dir = config_dir\n self.user_profiles_file = config_dir / \"user_profiles.json\"\n\n # Paths for schema files (packaged with application)\n schema_dir = Path(__file__).parent.parent / \"schemas\"\n self.default_profiles_file = schema_dir / \"default_profiles.json\"\n\n # Load profiles\n self.default_profiles = self._load_default_profiles()\n self.user_profiles = self._load_user_profiles()\n\n def _load_json_file(self, filepath: Path) -> Dict[str, Any]:\n \"\"\"Load a JSON file safely.\"\"\"\n if filepath.exists():\n try:\n with open(filepath, \"r\") as f:\n return json.load(f)\n except Exception as e:\n logger.error(f\"Error loading {filepath}: {e}\")\n return {}\n\n def _save_json_file(self, filepath: Path, data: Dict[str, Any]) -> bool:\n \"\"\"Save data to a JSON file.\"\"\"\n try:\n with open(filepath, \"w\") as f:\n json.dump(data, f, indent=2)\n return True\n except Exception as e:\n logger.error(f\"Error saving {filepath}: {e}\")\n return False\n\n def _load_default_profiles(self) -> Dict[str, Any]:\n \"\"\"Load default built-in profiles.\"\"\"\n profiles = self._load_json_file(self.default_profiles_file)\n return profiles.get(\"profiles\", {})\n\n def _load_user_profiles(self) -> Dict[str, Any]:\n \"\"\"Load user-created custom profiles.\"\"\"\n return self._load_json_file(self.user_profiles_file)\n\n def _save_user_profiles(self) -> bool:\n \"\"\"Save user profiles to file.\"\"\"\n return self._save_json_file(self.user_profiles_file, self.user_profiles)\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n all_profiles = deepcopy(self.default_profiles)\n all_profiles.update(self.user_profiles)\n return all_profiles\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name.\"\"\"\n # Check user profiles first, then default profiles\n if name in self.user_profiles:\n return deepcopy(self.user_profiles[name])\n elif name in self.default_profiles:\n return deepcopy(self.default_profiles[name])\n return None\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"\n Save or update a user profile with validation.\n\n Args:\n name: Profile name\n profile: Profile data to save\n\n Returns:\n True if saved successfully\n\n Raises:\n ProfileError: If profile validation fails or save fails\n \"\"\"\n try:\n # Validate profile structure\n if not isinstance(profile, dict):\n raise ProfileError(\n \"Profile must be a dictionary\",\n profile_name=name,\n error_code=\"INVALID_PROFILE_TYPE\",\n )\n\n # Process LoRA configuration if present\n if \"config\" in profile:\n config = profile[\"config\"]\n\n # Handle LoRA adapters in config\n if \"lora_adapters\" in config:\n # Validate LoRA adapter entries\n lora_adapters = config[\"lora_adapters\"]\n if isinstance(lora_adapters, list):\n # Ensure each adapter has required fields\n for adapter in lora_adapters:\n if not isinstance(adapter, dict):\n continue\n if \"path\" not in adapter and \"name\" in adapter:\n # Try to resolve adapter by name\n adapter[\"path\"] = self._resolve_lora_path(\n adapter[\"name\"]\n )\n\n # Convert to lora_modules format for vLLM\n if lora_adapters:\n config[\"enable_lora\"] = True\n lora_modules = []\n for adapter in lora_adapters:\n if isinstance(adapter, dict):\n name = adapter.get(\"name\", \"adapter\")\n path = adapter.get(\"path\", \"\")\n if path:\n lora_modules.append(f\"{name}={path}\")\n if lora_modules:\n config[\"lora_modules\"] = \" \".join(lora_modules)\n\n # Save the profile\n self.user_profiles[name] = deepcopy(profile)\n\n if not self._save_user_profiles():\n raise ProfileError(\n \"Failed to save profile to disk\",\n profile_name=name,\n error_code=\"PROFILE_SAVE_FAILED\",\n )\n\n logger.info(f\"Successfully saved user profile: {name}\")\n return True\n\n except ProfileError:\n raise\n except Exception as e:\n logger.error(f\"Unexpected error saving profile {name}: {e}\")\n raise ProfileError(\n f\"Unexpected error saving profile: {e}\",\n profile_name=name,\n error_code=\"PROFILE_SAVE_ERROR\",\n ) from e\n\n def _resolve_lora_path(self, adapter_name: str) -> str:\n \"\"\"\n Try to resolve a LoRA adapter path by name.\n\n Args:\n adapter_name: Name of the LoRA adapter\n\n Returns:\n Path to the adapter if found, empty string otherwise\n \"\"\"\n try:\n from ..models import scan_for_lora_adapters\n\n adapters = scan_for_lora_adapters()\n for adapter in adapters:\n if (\n adapter.get(\"name\") == adapter_name\n or adapter.get(\"display_name\") == adapter_name\n ):\n return adapter.get(\"path\", \"\")\n except Exception as e:\n logger.debug(f\"Could not resolve LoRA path for {adapter_name}: {e}\")\n return \"\"\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n if name in self.user_profiles:\n del self.user_profiles[name]\n return self._save_user_profiles()\n return False\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n profile = self.get_profile(profile_name)\n if not profile:\n logger.error(f\"Profile '{profile_name}' not found\")\n return False\n\n export_data = {\"version\": \"1.0\", \"profile\": profile}\n\n try:\n with open(filepath, \"w\") as f:\n json.dump(export_data, f, indent=2)\n logger.info(f\"Profile '{profile_name}' exported to {filepath}\")\n return True\n except Exception as e:\n logger.error(f\"Error exporting profile: {e}\")\n return False\n\n def import_profile(\n self,\n filepath: Path,\n new_name: Optional[str] = None,\n validate_config_func: Optional[Callable] = None,\n ) -> bool:\n \"\"\"\n Import a profile from a JSON file with comprehensive validation.\n\n Args:\n filepath: Path to the profile file\n new_name: Optional new name for the profile\n validate_config_func: Optional function to validate profile config\n\n Returns:\n True if imported successfully\n\n Raises:\n ProfileError: If import fails for any reason\n \"\"\"\n try:\n # Check file exists\n if not filepath.exists():\n raise ProfileError(\n f\"Profile file not found: {filepath}\",\n error_code=\"PROFILE_FILE_NOT_FOUND\",\n )\n\n # Load and parse file\n try:\n with open(filepath, \"r\") as f:\n data = json.load(f)\n except json.JSONDecodeError as e:\n raise ProfileError(\n f\"Invalid JSON in profile file: {e}\",\n error_code=\"PROFILE_INVALID_JSON\",\n ) from e\n\n # Validate file format\n if not isinstance(data, dict) or \"profile\" not in data:\n raise ProfileError(\n \"Invalid profile file format - missing 'profile' key\",\n error_code=\"PROFILE_INVALID_FORMAT\",\n )\n\n profile = data[\"profile\"]\n name = new_name or profile.get(\"name\", filepath.stem)\n\n # Validate profile configuration if function provided\n if validate_config_func and \"config\" in profile:\n is_valid, errors = validate_config_func(profile[\"config\"])\n if not is_valid:\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n # Save the profile\n return self.save_user_profile(name, profile)\n\n except ProfileError:\n raise\n except Exception as e:\n logger.error(f\"Unexpected error importing profile from {filepath}: {e}\")\n raise ProfileError(\n f\"Failed to import profile: {e}\", error_code=\"PROFILE_IMPORT_ERROR\"\n ) from e\n\n def list_profile_names(self) -> Dict[str, List[str]]:\n \"\"\"\n List all profile names categorized by type.\n\n Returns:\n Dictionary with 'default' and 'user' lists of profile names\n \"\"\"\n return {\n \"default\": list(self.default_profiles.keys()),\n \"user\": list(self.user_profiles.keys()),\n }\n\n def profile_exists(self, name: str) -> bool:\n \"\"\"Check if a profile exists (in either default or user profiles).\"\"\"\n return name in self.default_profiles or name in self.user_profiles\n\n def is_user_profile(self, name: str) -> bool:\n \"\"\"Check if a profile is a user-created profile.\"\"\"\n return name in self.user_profiles\n\n def has_user_override(self, name: str) -> bool:\n \"\"\"\n Check if a built-in profile has been overridden by a user profile.\n\n Args:\n name: Profile name to check\n\n Returns:\n True if this is a built-in profile that has a user override\n \"\"\"\n return name in self.default_profiles and name in self.user_profiles\n\n def get_original_default_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get the original default profile without any user overrides.\n\n Args:\n name: Profile name\n\n Returns:\n Original default profile if it exists, None otherwise\n \"\"\"\n if name in self.default_profiles:\n return deepcopy(self.default_profiles[name])\n return None\n\n def reset_to_default(self, name: str) -> bool:\n \"\"\"\n Reset a customized built-in profile to its default settings.\n\n This removes the user override for a built-in profile.\n\n Args:\n name: Profile name to reset\n\n Returns:\n True if reset successfully, False otherwise\n \"\"\"\n # Only reset if this is a built-in profile with a user override\n if self.has_user_override(name):\n return self.delete_user_profile(name)\n return False\n\n def get_profile_count(self) -> Dict[str, int]:\n \"\"\"Get count of profiles by type.\"\"\"\n return {\n \"default\": len(self.default_profiles),\n \"user\": len(self.user_profiles),\n \"total\": len(self.default_profiles) + len(self.user_profiles),\n }\n\n def apply_dynamic_defaults(self, profile_config: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Apply dynamic defaults to a profile configuration.\n\n This function intelligently sets tensor_parallel_size for multi-GPU systems.\n For single GPU systems, it allows vLLM to use its default behavior.\n\n Note: vLLM defaults to using only 1 GPU unless tensor_parallel_size is explicitly set.\n\n Args:\n profile_config: The profile configuration to enhance\n\n Returns:\n Enhanced profile configuration with dynamic defaults applied\n \"\"\"\n config = deepcopy(profile_config)\n\n # Apply dynamic tensor_parallel_size if not specified\n # Note: vLLM defaults to single GPU, so we only set this for multi-GPU systems\n # where tensor parallelism would be beneficial\n if \"tensor_parallel_size\" not in config:\n gpu_count = self._get_gpu_count()\n if gpu_count > 1:\n config[\"tensor_parallel_size\"] = gpu_count\n logger.debug(\n f\"Set tensor_parallel_size to {gpu_count} for multi-GPU system\"\n )\n # For single GPU, let vLLM use its default (no tensor_parallel_size needed)\n\n return config\n\n def _get_gpu_count(self) -> int:\n \"\"\"\n Get the number of available GPUs for tensor parallelism.\n\n Returns:\n Number of GPUs available, defaults to 1 if detection fails\n \"\"\"\n try:\n gpus = get_gpu_info()\n gpu_count = len(gpus) if gpus else 1\n logger.debug(f\"Detected {gpu_count} GPU(s)\")\n return gpu_count\n except Exception as e:\n logger.warning(f\"Failed to detect GPU count, defaulting to 1: {e}\")\n return 1", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 14008}, "tests/test_profiles.py::68": {"resolved_imports": ["src/vllm_cli/config/profiles.py"], "used_names": ["ProfileManager"], "enclosing_function": "test_save_user_profile", "extracted_code": "# Source: src/vllm_cli/config/profiles.py\nclass ProfileManager:\n \"\"\"\n Manages user profiles for vLLM configurations.\n\n Handles creation, retrieval, updating, and deletion of user profiles\n with validation and persistence.\n \"\"\"\n\n def __init__(self, config_dir: Path):\n self.config_dir = config_dir\n self.user_profiles_file = config_dir / \"user_profiles.json\"\n\n # Paths for schema files (packaged with application)\n schema_dir = Path(__file__).parent.parent / \"schemas\"\n self.default_profiles_file = schema_dir / \"default_profiles.json\"\n\n # Load profiles\n self.default_profiles = self._load_default_profiles()\n self.user_profiles = self._load_user_profiles()\n\n def _load_json_file(self, filepath: Path) -> Dict[str, Any]:\n \"\"\"Load a JSON file safely.\"\"\"\n if filepath.exists():\n try:\n with open(filepath, \"r\") as f:\n return json.load(f)\n except Exception as e:\n logger.error(f\"Error loading {filepath}: {e}\")\n return {}\n\n def _save_json_file(self, filepath: Path, data: Dict[str, Any]) -> bool:\n \"\"\"Save data to a JSON file.\"\"\"\n try:\n with open(filepath, \"w\") as f:\n json.dump(data, f, indent=2)\n return True\n except Exception as e:\n logger.error(f\"Error saving {filepath}: {e}\")\n return False\n\n def _load_default_profiles(self) -> Dict[str, Any]:\n \"\"\"Load default built-in profiles.\"\"\"\n profiles = self._load_json_file(self.default_profiles_file)\n return profiles.get(\"profiles\", {})\n\n def _load_user_profiles(self) -> Dict[str, Any]:\n \"\"\"Load user-created custom profiles.\"\"\"\n return self._load_json_file(self.user_profiles_file)\n\n def _save_user_profiles(self) -> bool:\n \"\"\"Save user profiles to file.\"\"\"\n return self._save_json_file(self.user_profiles_file, self.user_profiles)\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n all_profiles = deepcopy(self.default_profiles)\n all_profiles.update(self.user_profiles)\n return all_profiles\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name.\"\"\"\n # Check user profiles first, then default profiles\n if name in self.user_profiles:\n return deepcopy(self.user_profiles[name])\n elif name in self.default_profiles:\n return deepcopy(self.default_profiles[name])\n return None\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"\n Save or update a user profile with validation.\n\n Args:\n name: Profile name\n profile: Profile data to save\n\n Returns:\n True if saved successfully\n\n Raises:\n ProfileError: If profile validation fails or save fails\n \"\"\"\n try:\n # Validate profile structure\n if not isinstance(profile, dict):\n raise ProfileError(\n \"Profile must be a dictionary\",\n profile_name=name,\n error_code=\"INVALID_PROFILE_TYPE\",\n )\n\n # Process LoRA configuration if present\n if \"config\" in profile:\n config = profile[\"config\"]\n\n # Handle LoRA adapters in config\n if \"lora_adapters\" in config:\n # Validate LoRA adapter entries\n lora_adapters = config[\"lora_adapters\"]\n if isinstance(lora_adapters, list):\n # Ensure each adapter has required fields\n for adapter in lora_adapters:\n if not isinstance(adapter, dict):\n continue\n if \"path\" not in adapter and \"name\" in adapter:\n # Try to resolve adapter by name\n adapter[\"path\"] = self._resolve_lora_path(\n adapter[\"name\"]\n )\n\n # Convert to lora_modules format for vLLM\n if lora_adapters:\n config[\"enable_lora\"] = True\n lora_modules = []\n for adapter in lora_adapters:\n if isinstance(adapter, dict):\n name = adapter.get(\"name\", \"adapter\")\n path = adapter.get(\"path\", \"\")\n if path:\n lora_modules.append(f\"{name}={path}\")\n if lora_modules:\n config[\"lora_modules\"] = \" \".join(lora_modules)\n\n # Save the profile\n self.user_profiles[name] = deepcopy(profile)\n\n if not self._save_user_profiles():\n raise ProfileError(\n \"Failed to save profile to disk\",\n profile_name=name,\n error_code=\"PROFILE_SAVE_FAILED\",\n )\n\n logger.info(f\"Successfully saved user profile: {name}\")\n return True\n\n except ProfileError:\n raise\n except Exception as e:\n logger.error(f\"Unexpected error saving profile {name}: {e}\")\n raise ProfileError(\n f\"Unexpected error saving profile: {e}\",\n profile_name=name,\n error_code=\"PROFILE_SAVE_ERROR\",\n ) from e\n\n def _resolve_lora_path(self, adapter_name: str) -> str:\n \"\"\"\n Try to resolve a LoRA adapter path by name.\n\n Args:\n adapter_name: Name of the LoRA adapter\n\n Returns:\n Path to the adapter if found, empty string otherwise\n \"\"\"\n try:\n from ..models import scan_for_lora_adapters\n\n adapters = scan_for_lora_adapters()\n for adapter in adapters:\n if (\n adapter.get(\"name\") == adapter_name\n or adapter.get(\"display_name\") == adapter_name\n ):\n return adapter.get(\"path\", \"\")\n except Exception as e:\n logger.debug(f\"Could not resolve LoRA path for {adapter_name}: {e}\")\n return \"\"\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n if name in self.user_profiles:\n del self.user_profiles[name]\n return self._save_user_profiles()\n return False\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n profile = self.get_profile(profile_name)\n if not profile:\n logger.error(f\"Profile '{profile_name}' not found\")\n return False\n\n export_data = {\"version\": \"1.0\", \"profile\": profile}\n\n try:\n with open(filepath, \"w\") as f:\n json.dump(export_data, f, indent=2)\n logger.info(f\"Profile '{profile_name}' exported to {filepath}\")\n return True\n except Exception as e:\n logger.error(f\"Error exporting profile: {e}\")\n return False\n\n def import_profile(\n self,\n filepath: Path,\n new_name: Optional[str] = None,\n validate_config_func: Optional[Callable] = None,\n ) -> bool:\n \"\"\"\n Import a profile from a JSON file with comprehensive validation.\n\n Args:\n filepath: Path to the profile file\n new_name: Optional new name for the profile\n validate_config_func: Optional function to validate profile config\n\n Returns:\n True if imported successfully\n\n Raises:\n ProfileError: If import fails for any reason\n \"\"\"\n try:\n # Check file exists\n if not filepath.exists():\n raise ProfileError(\n f\"Profile file not found: {filepath}\",\n error_code=\"PROFILE_FILE_NOT_FOUND\",\n )\n\n # Load and parse file\n try:\n with open(filepath, \"r\") as f:\n data = json.load(f)\n except json.JSONDecodeError as e:\n raise ProfileError(\n f\"Invalid JSON in profile file: {e}\",\n error_code=\"PROFILE_INVALID_JSON\",\n ) from e\n\n # Validate file format\n if not isinstance(data, dict) or \"profile\" not in data:\n raise ProfileError(\n \"Invalid profile file format - missing 'profile' key\",\n error_code=\"PROFILE_INVALID_FORMAT\",\n )\n\n profile = data[\"profile\"]\n name = new_name or profile.get(\"name\", filepath.stem)\n\n # Validate profile configuration if function provided\n if validate_config_func and \"config\" in profile:\n is_valid, errors = validate_config_func(profile[\"config\"])\n if not is_valid:\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n # Save the profile\n return self.save_user_profile(name, profile)\n\n except ProfileError:\n raise\n except Exception as e:\n logger.error(f\"Unexpected error importing profile from {filepath}: {e}\")\n raise ProfileError(\n f\"Failed to import profile: {e}\", error_code=\"PROFILE_IMPORT_ERROR\"\n ) from e\n\n def list_profile_names(self) -> Dict[str, List[str]]:\n \"\"\"\n List all profile names categorized by type.\n\n Returns:\n Dictionary with 'default' and 'user' lists of profile names\n \"\"\"\n return {\n \"default\": list(self.default_profiles.keys()),\n \"user\": list(self.user_profiles.keys()),\n }\n\n def profile_exists(self, name: str) -> bool:\n \"\"\"Check if a profile exists (in either default or user profiles).\"\"\"\n return name in self.default_profiles or name in self.user_profiles\n\n def is_user_profile(self, name: str) -> bool:\n \"\"\"Check if a profile is a user-created profile.\"\"\"\n return name in self.user_profiles\n\n def has_user_override(self, name: str) -> bool:\n \"\"\"\n Check if a built-in profile has been overridden by a user profile.\n\n Args:\n name: Profile name to check\n\n Returns:\n True if this is a built-in profile that has a user override\n \"\"\"\n return name in self.default_profiles and name in self.user_profiles\n\n def get_original_default_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get the original default profile without any user overrides.\n\n Args:\n name: Profile name\n\n Returns:\n Original default profile if it exists, None otherwise\n \"\"\"\n if name in self.default_profiles:\n return deepcopy(self.default_profiles[name])\n return None\n\n def reset_to_default(self, name: str) -> bool:\n \"\"\"\n Reset a customized built-in profile to its default settings.\n\n This removes the user override for a built-in profile.\n\n Args:\n name: Profile name to reset\n\n Returns:\n True if reset successfully, False otherwise\n \"\"\"\n # Only reset if this is a built-in profile with a user override\n if self.has_user_override(name):\n return self.delete_user_profile(name)\n return False\n\n def get_profile_count(self) -> Dict[str, int]:\n \"\"\"Get count of profiles by type.\"\"\"\n return {\n \"default\": len(self.default_profiles),\n \"user\": len(self.user_profiles),\n \"total\": len(self.default_profiles) + len(self.user_profiles),\n }\n\n def apply_dynamic_defaults(self, profile_config: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Apply dynamic defaults to a profile configuration.\n\n This function intelligently sets tensor_parallel_size for multi-GPU systems.\n For single GPU systems, it allows vLLM to use its default behavior.\n\n Note: vLLM defaults to using only 1 GPU unless tensor_parallel_size is explicitly set.\n\n Args:\n profile_config: The profile configuration to enhance\n\n Returns:\n Enhanced profile configuration with dynamic defaults applied\n \"\"\"\n config = deepcopy(profile_config)\n\n # Apply dynamic tensor_parallel_size if not specified\n # Note: vLLM defaults to single GPU, so we only set this for multi-GPU systems\n # where tensor parallelism would be beneficial\n if \"tensor_parallel_size\" not in config:\n gpu_count = self._get_gpu_count()\n if gpu_count > 1:\n config[\"tensor_parallel_size\"] = gpu_count\n logger.debug(\n f\"Set tensor_parallel_size to {gpu_count} for multi-GPU system\"\n )\n # For single GPU, let vLLM use its default (no tensor_parallel_size needed)\n\n return config\n\n def _get_gpu_count(self) -> int:\n \"\"\"\n Get the number of available GPUs for tensor parallelism.\n\n Returns:\n Number of GPUs available, defaults to 1 if detection fails\n \"\"\"\n try:\n gpus = get_gpu_info()\n gpu_count = len(gpus) if gpus else 1\n logger.debug(f\"Detected {gpu_count} GPU(s)\")\n return gpu_count\n except Exception as e:\n logger.warning(f\"Failed to detect GPU count, defaulting to 1: {e}\")\n return 1", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 14008}, "tests/test_custom_directory_integration.py::169": {"resolved_imports": ["src/vllm_cli/models/manager.py", "src/vllm_cli/models/manifest.py"], "used_names": ["apply_manifest_to_models", "load_manifest"], "enclosing_function": "test_manifest_loading", "extracted_code": "# Source: src/vllm_cli/models/manifest.py\ndef load_manifest(directory: Union[str, Path]) -> Optional[Dict[str, Any]]:\n \"\"\"\n Load manifest from a directory if it exists.\n\n Args:\n directory: Path to directory containing manifest\n\n Returns:\n Manifest data or None if not found/invalid\n \"\"\"\n directory = Path(directory)\n manifest_path = directory / MANIFEST_FILENAME\n\n if not manifest_path.exists():\n logger.debug(f\"No manifest found at {manifest_path}\")\n return None\n\n try:\n with open(manifest_path, \"r\") as f:\n manifest = json.load(f)\n\n logger.info(f\"Loaded manifest from {manifest_path}\")\n return manifest\n\n except (json.JSONDecodeError, OSError) as e:\n logger.error(f\"Error loading manifest from {manifest_path}: {e}\")\n return None\n\ndef apply_manifest_to_models(\n models: List[Dict[str, Any]], directory: Path\n) -> List[Dict[str, Any]]:\n \"\"\"\n Apply manifest data to discovered models if manifest exists.\n\n Args:\n models: List of discovered models\n directory: Directory to check for manifest\n\n Returns:\n Updated models list with manifest data applied\n \"\"\"\n manifest = load_manifest(directory)\n if not manifest:\n return models\n\n manifest_models = manifest.get(\"models\", [])\n manifest_by_path = {}\n\n # Build lookup by path\n for entry in manifest_models:\n if entry.get(\"enabled\", True):\n # Resolve path\n model_path = directory / entry[\"path\"]\n manifest_by_path[str(model_path)] = entry\n\n # Apply manifest data to models\n updated_models = []\n for model in models:\n model_path = model.get(\"path\", \"\")\n\n if model_path in manifest_by_path:\n manifest_entry = manifest_by_path[model_path]\n # Override with manifest data\n model[\"name\"] = manifest_entry.get(\"name\", model[\"name\"])\n model[\"display_name\"] = manifest_entry.get(\"name\", model[\"display_name\"])\n model[\"publisher\"] = manifest_entry.get(\n \"publisher\", model.get(\"publisher\", \"unknown\")\n )\n model[\"notes\"] = manifest_entry.get(\"notes\", \"\")\n model[\"from_manifest\"] = True\n\n updated_models.append(model)\n\n return updated_models", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 2316}, "tests/test_server_manager.py::36": {"resolved_imports": ["src/vllm_cli/server/__init__.py", "src/vllm_cli/server/process.py", "src/vllm_cli/server/manager.py"], "used_names": ["VLLMServer", "process"], "enclosing_function": "test_init", "extracted_code": "# Source: src/vllm_cli/server/__init__.py\n\nThis package provides comprehensive vLLM server management including\nprocess lifecycle, monitoring, discovery, and utilities.\n\nMain Components:\n- VLLMServer: Core server management class\n- Process management: Server registry and lifecycle\n- Discovery: External server detection\n- Monitoring: Health checks and metrics\n- Utils: Port management and cleanup utilities\n\"\"\"\n\n\n\n# Process management functions\nfrom .process import (\n add_server,\n cleanup_servers_on_exit,\n find_server_by_model,\n find_server_by_port,\n get_active_servers,\n remove_server,\n stop_all_servers,\n)\n\n\n\n# Source: src/vllm_cli/server/manager.py\nclass VLLMServer:\n \"\"\"\n Manages a vLLM server instance with comprehensive lifecycle control.\n\n This class handles the complete lifecycle of a vLLM server including\n configuration, process management, logging, monitoring, and cleanup.\n It supports both programmatically started servers and external server\n detection and management.\n\n Attributes:\n config: Server configuration dictionary\n model: Model name being served\n port: Port number the server is listening on\n process: Subprocess or external process reference\n log_file: File handle for server logs\n log_queue: Thread-safe queue for log lines\n log_thread: Background thread for log monitoring\n start_time: Timestamp when server was started\n log_path: Path to the server's log file\n \"\"\"\n\n def __init__(self, config: Dict[str, Any]) -> None:\n \"\"\"\n Initialize a vLLM server instance.\n\n Sets up the server configuration, logging infrastructure, and\n prepares the instance for server lifecycle management.\n\n Args:\n config: Server configuration dictionary containing model name,\n port, and other vLLM-specific parameters\n \"\"\"\n self.config: Dict[str, Any] = config\n\n # Extract model name - handle both string and dict (LoRA config) formats\n model_config = config.get(\"model\", \"unknown\")\n if isinstance(model_config, dict):\n # LoRA configuration - extract base model name\n self.model: str = model_config.get(\"model\", \"unknown\")\n else:\n # Regular string model name\n self.model: str = model_config\n\n self.port: int = config.get(\"port\", 8000)\n self.process: Optional[Union[subprocess.Popen, Any]] = None\n self.log_file: Optional[TextIO] = None\n self.log_queue: Queue[str] = Queue()\n self.log_thread: Optional[Thread] = None\n self.start_time: Optional[datetime] = None\n self.log_path: Path\n self._recent_logs: List[str] = []\n\n # Setup logging\n log_dir = Path.home() / \".vllm-cli\" / \"logs\"\n log_dir.mkdir(parents=True, exist_ok=True)\n\n timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n self.log_path = log_dir / f\"vllm_{self.model.replace('/', '_')}_{timestamp}.log\"\n\n def start(self) -> bool:\n \"\"\"\n Start the vLLM server.\n\n Returns:\n True if server started successfully, False otherwise\n \"\"\"\n if self.is_running():\n logger.warning(f\"Server already running for {self.model}\")\n return False\n\n try:\n # Build command - run directly without conda wrapper\n full_cmd = self._build_command()\n\n logger.info(f\"Starting vLLM server with command: {' '.join(full_cmd)}\")\n\n # Open log file for writing\n self.log_file = open(self.log_path, \"w\", buffering=1)\n\n # Start with parent environment\n env = os.environ.copy()\n # Note: No longer forcing PYTHONUNBUFFERED=1, let user control it\n\n # Layer 1: Apply universal environment variables from settings\n config_manager = ConfigManager()\n universal_env = config_manager.config.get(\"universal_environment\", {})\n if universal_env:\n logger.info(\n f\"Applying {len(universal_env)} universal environment variable(s)\"\n )\n for key, value in universal_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting universal {key}={value}\")\n else:\n logger.debug(f\"Setting universal {key}=\")\n\n # Layer 2: Apply profile environment variables (override universal)\n profile_env = self.config.get(\"profile_environment\", {})\n if profile_env:\n logger.info(\n f\"Applying {len(profile_env)} profile environment variable(s)\"\n )\n for key, value in profile_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting profile {key}={value}\")\n else:\n logger.debug(f\"Setting profile {key}=\")\n\n # Handle GPU device selection via CUDA_VISIBLE_DEVICES\n # This overrides any CUDA_VISIBLE_DEVICES from the profile\n if self.config.get(\"device\"):\n device_str = str(self.config[\"device\"])\n env[\"CUDA_VISIBLE_DEVICES\"] = device_str\n logger.info(f\"Setting CUDA_VISIBLE_DEVICES={device_str}\")\n\n # If using specific GPUs, adjust tensor parallel size if needed\n device_list = [d.strip() for d in device_str.split(\",\")]\n num_devices = len(device_list)\n\n # Check if tensor_parallel_size is set and compatible\n if self.config.get(\"tensor_parallel_size\"):\n tp_size = self.config[\"tensor_parallel_size\"]\n if tp_size > num_devices:\n logger.warning(\n f\"tensor_parallel_size ({tp_size}) > number of selected devices ({num_devices}). \"\n f\"Adjusting tensor_parallel_size to {num_devices}\"\n )\n self.config[\"tensor_parallel_size\"] = num_devices\n elif num_devices % tp_size != 0:\n logger.warning(\n f\"Number of GPUs ({num_devices}) is not evenly divisible by \"\n f\"tensor_parallel_size ({tp_size}). This may lead to inefficient GPU utilization. \"\n f\"Consider using tensor_parallel_size of: \"\n f\"{', '.join(str(i) for i in range(1, num_devices + 1) if num_devices % i == 0)}\"\n )\n\n # Add HuggingFace token if configured\n config_manager = ConfigManager()\n hf_token = config_manager.config.get(\"hf_token\")\n if hf_token:\n env[\"HF_TOKEN\"] = hf_token\n env[\"HUGGING_FACE_HUB_TOKEN\"] = hf_token # Some tools use this variant\n logger.info(\"HuggingFace token configured for server\")\n\n # Enable development mode for sleep endpoints if sleep mode is enabled\n if self.config.get(\"enable_sleep_mode\"):\n env[\"VLLM_SERVER_DEV_MODE\"] = \"1\"\n logger.info(\"Sleep mode enabled with development endpoints\")\n\n # Start the process with proper pipe configuration\n # Use start_new_session=True to create a new process group\n # This prevents the child process from receiving Ctrl+C signals\n self.process = subprocess.Popen(\n full_cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n text=True,\n bufsize=0, # Unbuffered\n universal_newlines=True,\n env=env,\n start_new_session=True, # Create new process group to isolate from parent signals\n )\n\n # Start log monitoring thread\n self._start_log_monitor()\n\n # Set start time and add to registry\n self.start_time = datetime.now()\n from .process import add_server\n\n add_server(self)\n\n # Return immediately - let the UI monitor the startup\n logger.info(\n f\"vLLM server process launched for {self.model} on port {self.port}\"\n )\n return True\n\n except Exception as e:\n logger.error(f\"Error starting vLLM server: {e}\")\n return False\n\n def _build_command(self) -> List[str]:\n \"\"\"\n Build the vLLM command from configuration using the schema.\n\n Returns:\n List of command arguments\n \"\"\"\n # Use the new ConfigManager to build CLI args\n config_manager = ConfigManager()\n\n # Start with the vllm command\n cmd = [\"vllm\"]\n\n # Add the arguments built from schema\n cli_args = config_manager.build_cli_args(self.config)\n cmd.extend(cli_args)\n\n # Handle extra_args if present (backward compatibility)\n if self.config.get(\"extra_args\"):\n self._add_extra_args_to_command(cmd)\n\n logger.debug(f\"Built command: {' '.join(cmd)}\")\n return cmd\n\n def _add_extra_args_to_command(self, cmd: List[str]) -> None:\n \"\"\"\n Add extra arguments to the vLLM command.\n\n Args:\n cmd: Command list to extend with extra arguments\n \"\"\"\n try:\n extra_args = shlex.split(self.config[\"extra_args\"])\n if extra_args:\n logger.info(f\"Adding extra arguments: {extra_args}\")\n cmd.extend(extra_args)\n except ValueError as e:\n logger.warning(f\"Failed to parse extra_args: {e}\")\n\n def _start_log_monitor(self) -> None:\n \"\"\"\n Start a thread to monitor log output from the vLLM server process.\n\n Creates a daemon thread that continuously reads stdout/stderr from\n the server process, writes to log files, and queues log lines for\n real-time display in the UI.\n \"\"\"\n self.log_thread = Thread(target=self._log_monitor_worker, daemon=True)\n self.log_thread.start()\n\n def _log_monitor_worker(self) -> None:\n \"\"\"\n Worker function for log monitoring thread.\n\n Continuously reads log output from the server process and handles\n file writing and queue management for UI display.\n \"\"\"\n try:\n self.log_queue.put(\"Starting vLLM server process...\")\n\n while self._should_continue_monitoring():\n if self._process_log_line():\n continue\n else:\n # No line read, check if process still running\n if self.process and self.process.poll() is not None:\n break\n time.sleep(0.01) # Small sleep to prevent busy waiting\n\n except Exception as e:\n logger.error(f\"Error in log monitor: {e}\")\n self.log_queue.put(f\"Log monitoring error: {e}\")\n\n def _should_continue_monitoring(self) -> bool:\n \"\"\"\n Check if log monitoring should continue.\n\n Returns:\n True if monitoring should continue, False otherwise\n \"\"\"\n return (\n self.is_running()\n and self.process\n and hasattr(self.process, \"stdout\")\n and self.process.stdout\n )\n\n def _process_log_line(self) -> bool:\n \"\"\"\n Process a single log line from the server output.\n\n Reads one line from the process stdout, writes it to the log file,\n and adds it to the queue for UI display after filtering and formatting.\n\n Returns:\n True if a line was processed, False if no line was available\n \"\"\"\n if not (self.process and self.process.stdout):\n return False\n\n line = self.process.stdout.readline()\n if not line:\n return False\n\n # Write to log file\n self._write_to_log_file(line)\n\n # Process for UI display\n line_stripped = line.strip()\n if line_stripped and self._should_display_log_line(line_stripped):\n # Truncate overly long lines\n if len(line_stripped) > 200:\n line_stripped = line_stripped[:197] + \"...\"\n\n self.log_queue.put(line_stripped)\n logger.debug(f\"Log captured: {line_stripped[:50]}...\")\n\n return True\n\n def _write_to_log_file(self, line: str) -> None:\n \"\"\"\n Write a log line to the log file.\n\n Args:\n line: Log line to write\n \"\"\"\n if self.log_file and not self.log_file.closed:\n self.log_file.write(line)\n self.log_file.flush()\n\n def _should_display_log_line(self, line: str) -> bool:\n \"\"\"\n Determine if a log line should be displayed in the UI.\n\n Filters out certain system messages that are not useful for users.\n\n Args:\n line: Stripped log line to check\n\n Returns:\n True if the line should be displayed, False otherwise\n \"\"\"\n # Filter out conda activation and system messages\n filtered_messages = [\n \"Activated CUDA\",\n \"Using nvcc from:\",\n \"Cuda compilation tools\",\n ]\n return not any(skip in line for skip in filtered_messages)\n\n def stop(self) -> bool:\n \"\"\"\n Stop the vLLM server.\n\n Returns:\n True if server stopped successfully, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n try:\n # Check if this is an external server\n if hasattr(self.process, \"terminate\"):\n # Normal subprocess\n # Since we created a new session, we need to terminate the entire process group\n try:\n # Get the process group ID (pgid)\n # Since we used start_new_session=True, the pgid is the same as the pid\n pgid = self.process.pid\n\n # Send SIGTERM to the entire process group for graceful shutdown\n logger.info(f\"Sending SIGTERM to process group {pgid}\")\n os.killpg(pgid, signal.SIGTERM)\n\n # Wait for process to terminate\n try:\n self.process.wait(timeout=10)\n logger.info(f\"Process group {pgid} terminated gracefully\")\n except subprocess.TimeoutExpired:\n # Force kill if not terminated\n logger.warning(\n f\"Process group {pgid} did not terminate, sending SIGKILL\"\n )\n os.killpg(pgid, signal.SIGKILL)\n self.process.wait()\n logger.info(f\"Process group {pgid} force killed\")\n\n except ProcessLookupError:\n # Process already dead\n logger.info(\"Process already terminated\")\n except PermissionError as e:\n # Fall back to terminating just the process\n logger.warning(\n f\"Permission denied for process group kill: {e}, falling back to process termination\"\n )\n self.process.terminate()\n try:\n self.process.wait(timeout=10)\n except subprocess.TimeoutExpired:\n self.process.kill()\n self.process.wait()\n elif hasattr(self.process, \"pid\"):\n # External server - kill entire process group or individual process\n try:\n pgid = self.process.pid\n killed = False\n\n # First attempt: try to kill process group\n try:\n os.killpg(pgid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process group {pgid}\")\n killed = True\n except (OSError, ProcessLookupError) as e:\n # Process group kill failed, try individual process\n logger.debug(\n f\"Process group kill failed: {e}, trying individual process\"\n )\n try:\n # Ensure pid is an integer (handle Mock objects)\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process {self.process.pid}\")\n killed = True\n except ProcessLookupError:\n # Process already dead\n logger.info(\n f\"Process {self.process.pid} already terminated\"\n )\n except OSError as e:\n logger.warning(\n f\"Failed to send SIGTERM to {self.process.pid}: {e}\"\n )\n\n if killed:\n # Wait for graceful shutdown\n time.sleep(2)\n\n # Check if still running and force kill if needed\n if self.is_running():\n try:\n os.killpg(pgid, signal.SIGKILL)\n logger.info(f\"Force killed process group {pgid}\")\n except (OSError, ProcessLookupError):\n # Process group kill failed, try individual\n try:\n # Ensure pid is an integer (handle Mock objects in tests)\n if hasattr(self.process, \"pid\"):\n try:\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGKILL)\n logger.info(f\"Force killed process {pid}\")\n except (TypeError, ValueError):\n # PID is not a valid integer (might be Mock)\n pass\n except ProcessLookupError:\n pass # Already dead\n except OSError as e:\n logger.error(\n f\"Failed to force kill {self.process.pid}: {e}\"\n )\n\n except Exception as e:\n logger.error(f\"Unexpected error stopping external server: {e}\")\n\n # Close log file if we have one\n if hasattr(self, \"log_file\") and self.log_file:\n self.log_file.close()\n\n # Remove from registry\n from .process import remove_server\n\n remove_server(self)\n\n logger.info(f\"vLLM server stopped for {self.model}\")\n return True\n\n except Exception as e:\n logger.error(f\"Error stopping vLLM server: {e}\")\n return False\n\n def is_running(self) -> bool:\n \"\"\"\n Check if the server is running.\n\n Returns:\n True if server is running, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n # Check if this is an external server (detected, not started by us)\n if hasattr(self.process, \"poll\"):\n # Normal subprocess\n return self.process.poll() is None\n elif hasattr(self.process, \"pid\"):\n # External server - check if PID still exists\n try:\n import psutil\n\n return psutil.pid_exists(self.process.pid)\n except ImportError:\n # Fallback to os method\n try:\n os.kill(self.process.pid, 0)\n return True\n except (OSError, ProcessLookupError):\n return False\n\n return False\n\n def get_status(self) -> Dict[str, Any]:\n \"\"\"\n Get server status information.\n\n Returns:\n Dictionary with status information\n \"\"\"\n status = {\n \"model\": self.model,\n \"port\": self.port,\n \"running\": self.is_running(),\n \"pid\": self.process.pid if self.process else None,\n \"start_time\": self.start_time.isoformat() if self.start_time else None,\n \"log_path\": str(self.log_path) if self.log_path else None,\n }\n\n if self.is_running() and self.start_time:\n uptime = datetime.now() - self.start_time\n status[\"uptime_seconds\"] = uptime.total_seconds()\n status[\"uptime_str\"] = str(uptime).split(\".\")[0]\n\n return status\n\n def wait_for_startup(self) -> bool:\n \"\"\"\n Wait for the server to complete startup.\n\n Monitors the server logs for startup completion indicators and verifies\n via HTTP endpoint. Will wait indefinitely until either startup completes\n or the process terminates.\n\n Returns:\n True if server started successfully, False if process terminated\n \"\"\"\n import time\n\n logger.info(f\"Waiting for {self.model} server to complete startup...\")\n\n # Track if we've seen startup indicators in logs\n log_indicates_ready = False\n\n while True:\n # Check if server is still running\n if not self.is_running():\n logger.error(\n f\"Server process for {self.model} terminated during startup\"\n )\n return False\n\n # Get recent logs to check for startup completion\n recent_logs = self.get_recent_logs(50)\n\n if recent_logs and not log_indicates_ready:\n # Check for startup completion indicators\n for log in recent_logs:\n log_lower = log.lower()\n # Look for the explicit \"Application startup complete\" message\n if \"application startup complete\" in log_lower:\n logger.debug(f\"Server {self.model} startup detected in logs\")\n log_indicates_ready = True\n break\n\n # Also check for other ready indicators as fallback\n if any(\n indicator in log_lower\n for indicator in [\n \"uvicorn running on\",\n \"started server process\",\n \"server is ready\",\n \"api server started\",\n ]\n ):\n logger.debug(\n f\"Server {self.model} startup detected via ready indicator\"\n )\n log_indicates_ready = True\n break\n\n # If logs indicate ready, verify via HTTP\n if log_indicates_ready:\n # Try to verify server is actually ready via HTTP\n port = self.config.get(\"port\")\n if port:\n try:\n import httpx\n\n with httpx.Client() as client:\n # Try /v1/models endpoint first (most reliable)\n response = client.get(\n f\"http://localhost:{port}/v1/models\", timeout=5.0\n )\n if response.status_code == 200:\n logger.info(\n f\"Server {self.model} startup complete \"\n \"(verified via HTTP)\"\n )\n return True\n except httpx.ConnectError:\n # Server not ready yet, continue waiting\n logger.debug(\n f\"Server {self.model} not accepting connections yet\"\n )\n except Exception as e:\n # Log but continue, might be network issue\n logger.debug(f\"HTTP verification failed: {e}\")\n else:\n # No port configured, trust the logs\n logger.info(\n f\"Server {self.model} startup complete (no port for verification)\"\n )\n return True\n\n # Small sleep to avoid busy waiting\n time.sleep(0.5)\n\n def get_recent_logs(self, n: int = 20) -> List[str]:\n \"\"\"\n Get recent log lines from the server output.\n\n Retrieves the most recent log lines from either the in-memory queue\n or the log file on disk. This method ensures logs are available even\n after the monitoring thread has processed them.\n\n Args:\n n: Number of recent lines to return (default: 20)\n\n Returns:\n List of recent log lines, with the most recent last\n \"\"\"\n # Update recent logs from queue\n self._update_recent_logs_from_queue()\n\n # Return from memory if available\n if self._recent_logs:\n return self._recent_logs[-n:]\n\n # Fallback to reading from file\n return self._read_logs_from_file(n)\n\n def _update_recent_logs_from_queue(self) -> None:\n \"\"\"\n Update the recent logs cache from the log queue.\n\n Drains all available log lines from the queue and adds them\n to the recent logs cache, maintaining a maximum of 100 lines.\n \"\"\"\n temp_logs = []\n\n # Get all available logs from queue (don't block)\n while not self.log_queue.empty():\n try:\n log_line = self.log_queue.get_nowait()\n temp_logs.append(log_line)\n except Empty:\n break\n\n if temp_logs:\n self._recent_logs.extend(temp_logs)\n # Keep only the last 100 logs in memory to prevent unbounded growth\n self._recent_logs = self._recent_logs[-100:]\n\n def _read_logs_from_file(self, n: int) -> List[str]:\n \"\"\"\n Read recent log lines from the log file.\n\n Args:\n n: Number of lines to read\n\n Returns:\n List of log lines from file\n \"\"\"\n if not (self.log_path and self.log_path.exists()):\n return []\n\n try:\n with open(self.log_path, \"r\") as f:\n file_logs = f.readlines()\n if file_logs:\n # Get last n lines, strip them\n logs = [line.strip() for line in file_logs[-n:]]\n # Update recent logs cache\n self._recent_logs = logs[-100:]\n return logs\n except Exception as e:\n logger.debug(f\"Error reading log file: {e}\")\n\n return []\n\n def restart(self) -> bool:\n \"\"\"\n Restart the server with the same configuration.\n\n Returns:\n True if restart successful, False otherwise\n \"\"\"\n logger.info(f\"Restarting vLLM server for {self.model}\")\n\n # Stop if running\n if self.is_running():\n self.stop()\n time.sleep(2) # Wait a bit before restarting\n\n # Start again\n return self.start()\n\n def health_check(self) -> bool:\n \"\"\"\n Perform a health check on the server.\n\n Returns:\n True if server is healthy, False otherwise\n \"\"\"\n if not self.is_running():\n return False\n\n try:\n import requests\n\n # Try to connect to the server\n response = requests.get(f\"http://localhost:{self.port}/health\", timeout=5)\n\n return response.status_code == 200\n\n except Exception:\n # If requests fails, just check process\n return self.is_running()", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 28614}, "tests/test_config_manager.py::195": {"resolved_imports": ["src/vllm_cli/config/manager.py"], "used_names": ["ConfigManager", "patch", "yaml"], "enclosing_function": "test_get_model_directories", "extracted_code": "# Source: src/vllm_cli/config/manager.py\nclass ConfigManager:\n \"\"\"\n Enhanced configuration manager with comprehensive validation support.\n\n This class manages configuration files, profiles, and validation using\n the new validation framework. It provides a clean API for configuration\n operations while ensuring data integrity through comprehensive validation.\n\n Attributes:\n config_dir: Directory for configuration files\n validation_registry: Registry of validation rules\n compatibility_validator: Validator for parameter combinations\n \"\"\"\n\n def __init__(self):\n # Paths for configuration files\n self.config_dir = Path.home() / \".config\" / \"vllm-cli\"\n self.config_file = self.config_dir / \"config.yaml\"\n\n # Ensure config directory exists\n self.config_dir.mkdir(parents=True, exist_ok=True)\n\n # Initialize sub-managers\n self.schema_manager = SchemaManager()\n self.profile_manager = ProfileManager(self.config_dir)\n self.persistence_manager = PersistenceManager()\n self.shortcut_manager = ShortcutManager(self.config_dir)\n\n # Initialize validation system\n self.validation_registry = create_vllm_validation_registry()\n self.compatibility_validator = create_compatibility_validator(\n self.validation_registry\n )\n\n # Load main configuration\n self.config = self._load_config()\n\n def _load_config(self) -> Dict[str, Any]:\n \"\"\"Load main configuration file (legacy YAML support).\"\"\"\n return self.persistence_manager.load_yaml_file(self.config_file)\n\n def _save_config(self) -> None:\n \"\"\"Save main configuration file.\"\"\"\n self.persistence_manager.save_yaml_file(self.config_file, self.config)\n\n def get_argument_info(self, arg_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get detailed information about a specific argument.\"\"\"\n return self.schema_manager.get_argument_info(arg_name)\n\n def get_arguments_by_category(self, category: str) -> List[Dict[str, Any]]:\n \"\"\"Get all arguments belonging to a specific category.\"\"\"\n return self.schema_manager.get_arguments_by_category(category)\n\n def get_category_info(self, category: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get information about a specific category.\"\"\"\n return self.schema_manager.get_category_info(category)\n\n def get_ordered_categories(self) -> List[Tuple[str, Dict[str, Any]]]:\n \"\"\"Get categories ordered by their display order.\"\"\"\n return self.schema_manager.get_ordered_categories()\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n return self.profile_manager.get_all_profiles()\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name with dynamic defaults applied.\"\"\"\n profile = self.profile_manager.get_profile(name)\n if profile and \"config\" in profile:\n # Apply dynamic defaults to the profile configuration\n profile[\"config\"] = self.profile_manager.apply_dynamic_defaults(\n profile[\"config\"]\n )\n return profile\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"Save or update a user profile with validation.\"\"\"\n # Validate profile configuration if present\n if \"config\" in profile:\n is_valid, errors = self.validate_config(profile[\"config\"])\n if not is_valid:\n from ..errors import ProfileError\n\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n return self.profile_manager.save_user_profile(name, profile)\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n return self.profile_manager.delete_user_profile(name)\n\n @property\n def default_profiles(self) -> Dict[str, Any]:\n \"\"\"Get default profiles.\"\"\"\n return self.profile_manager.default_profiles\n\n @property\n def user_profiles(self) -> Dict[str, Any]:\n \"\"\"Get user profiles.\"\"\"\n return self.profile_manager.user_profiles\n\n def validate_config(self, config: Dict[str, Any]) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate a configuration using the new validation framework.\n\n This method uses the comprehensive validation system to check\n configuration values, types, ranges, and dependencies.\n\n Args:\n config: Configuration dictionary to validate\n\n Returns:\n Tuple of (is_valid, list_of_error_messages)\n\n Raises:\n ConfigurationError: If validation system fails\n \"\"\"\n try:\n # Use new validation system\n result = self.validation_registry.validate_config(config)\n\n # Convert validation errors to string messages for backward compatibility\n error_messages = result.get_error_messages()\n\n # Add warnings if any\n if result.warnings:\n for warning in result.warnings:\n logger.warning(f\"Configuration warning: {warning}\")\n\n return result.is_valid(), error_messages\n\n except Exception as e:\n logger.error(f\"Error during configuration validation: {e}\")\n raise ConfigurationError(\n f\"Validation system error: {e}\", error_code=\"VALIDATION_SYSTEM_ERROR\"\n ) from e\n\n def validate_argument_combination(\n self, config: Dict[str, Any]\n ) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate that argument combinations are compatible using the new compatibility validator.\n\n Args:\n config: Configuration dictionary to check for compatibility\n\n Returns:\n Tuple of (is_valid, list_of_warnings_or_errors)\n \"\"\"\n try:\n issues = self.compatibility_validator.validate_compatibility(config)\n\n warnings = []\n errors = []\n\n for issue in issues:\n message = issue[\"message\"]\n if issue[\"severity\"] == \"error\":\n errors.append(message)\n else:\n warnings.append(message)\n\n # Log warnings\n for warning in warnings:\n logger.warning(f\"Configuration compatibility warning: {warning}\")\n\n # Return all issues as warnings for backward compatibility\n # (errors are treated as warnings in the legacy interface)\n all_issues = errors + warnings\n\n return len(errors) == 0, all_issues\n\n except Exception as e:\n logger.error(f\"Error during compatibility validation: {e}\")\n return False, [f\"Compatibility validation error: {e}\"]\n\n def build_cli_args(self, config: Dict[str, Any]) -> List[str]:\n \"\"\"\n Build command-line arguments from a configuration dictionary.\n\n Only includes arguments that are explicitly set in the config.\n Handles special cases like LoRA modules.\n \"\"\"\n args = []\n\n # Special handling for model (positional argument)\n # Check if this is a GGUF/Ollama configuration\n if (\n isinstance(config.get(\"model\"), dict)\n and \"quantization\" in config[\"model\"]\n and config[\"model\"][\"quantization\"] == \"gguf\"\n ):\n # Extract GGUF model config\n gguf_config = config[\"model\"]\n model_path = gguf_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", model_path])\n\n # Set quantization to gguf\n config[\"quantization\"] = \"gguf\"\n\n # Add served-model-name if provided (for Ollama models)\n if \"served_model_name\" in gguf_config:\n config[\"served_model_name\"] = gguf_config[\"served_model_name\"]\n logger.info(\n f\"Configuring GGUF model: {model_path} as {gguf_config['served_model_name']}\"\n )\n else:\n logger.info(f\"Configuring GGUF model: {model_path}\")\n\n # Check if this is a LoRA configuration\n elif (\n isinstance(config.get(\"model\"), dict) and \"lora_modules\" in config[\"model\"]\n ):\n # Extract base model and LoRA config\n lora_config = config[\"model\"]\n base_model = lora_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", base_model])\n\n # Enable LoRA support when modules are present\n args.append(\"--enable-lora\")\n\n # Track maximum rank for all LoRA modules\n max_rank = 16 # Default minimum\n\n # Add LoRA modules\n for lora in lora_config.get(\"lora_modules\", []):\n lora_path = lora.get(\"path\", \"\")\n if lora_path:\n # vLLM expects --lora-modules with name=path format\n lora_name = lora.get(\"name\", \"adapter\")\n args.extend([\"--lora-modules\", f\"{lora_name}={lora_path}\"])\n\n # Track maximum rank\n lora_rank = lora.get(\"rank\", 16)\n max_rank = max(max_rank, lora_rank)\n\n # Add max-lora-rank parameter\n args.extend([\"--max-lora-rank\", str(max_rank)])\n\n elif \"model\" in config:\n args.extend([\"serve\", config[\"model\"]])\n\n # Handle lora_modules if present as a string (from CLI)\n if \"lora_modules\" in config and config[\"lora_modules\"]:\n # Enable LoRA support\n if \"--enable-lora\" not in args:\n args.append(\"--enable-lora\")\n\n # Parse and add LoRA modules\n lora_modules_str = config[\"lora_modules\"]\n if isinstance(lora_modules_str, str):\n # Split by space and add each module\n for module in lora_modules_str.split():\n args.extend([\"--lora-modules\", module])\n\n # Add max-lora-rank if not already added\n # Use a safe default of 64 which should cover most LoRA adapters\n if \"--max-lora-rank\" not in args:\n # Check if max_lora_rank is explicitly set in config\n if \"max_lora_rank\" not in config:\n args.extend([\"--max-lora-rank\", \"64\"])\n\n for arg_name, value in config.items():\n # Skip special keys and None values\n if (\n arg_name in [\"model\", \"name\", \"description\", \"icon\", \"lora_modules\"]\n or value is None\n ):\n continue\n\n arg_info = self.schema_manager.get_argument_info(arg_name)\n if not arg_info:\n logger.warning(f\"Unknown argument in config: {arg_name}\")\n continue\n\n cli_flag = arg_info.get(\"cli_flag\")\n if not cli_flag:\n continue\n\n arg_type = arg_info.get(\"type\")\n\n if arg_type == \"boolean\":\n if value: # Only add flag if True\n args.append(cli_flag)\n elif arg_type in [\"integer\", \"float\", \"string\", \"choice\"]:\n args.extend([cli_flag, str(value)])\n else:\n logger.warning(f\"Unknown argument type for {arg_name}: {arg_type}\")\n\n return args\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n return self.profile_manager.export_profile(profile_name, filepath)\n\n def import_profile(self, filepath: Path, new_name: Optional[str] = None) -> bool:\n \"\"\"Import a profile from a JSON file with comprehensive validation.\"\"\"\n return self.profile_manager.import_profile(\n filepath, new_name, self.validate_config\n )\n\n def get_last_config(self) -> Optional[Dict[str, Any]]:\n \"\"\"Get the last used server configuration.\"\"\"\n return self.config.get(\"last_config\")\n\n def save_last_config(self, config: Dict[str, Any]) -> None:\n \"\"\"Save the last used server configuration.\"\"\"\n self.config[\"last_config\"] = config\n self._save_config()\n\n def get_recent_models(self, limit: int = 5) -> List[str]:\n \"\"\"Get recently used models.\"\"\"\n return self.config.get(\"recent_models\", [])[:limit]\n\n def add_recent_model(self, model: str) -> None:\n \"\"\"Add a model to recent models list.\"\"\"\n recent = self.config.get(\"recent_models\", [])\n if model in recent:\n recent.remove(model)\n recent.insert(0, model)\n self.config[\"recent_models\"] = recent[:10] # Keep only last 10\n self._save_config()\n\n def clear_cache(self) -> None:\n \"\"\"Clear cached data.\"\"\"\n cache_file = self.config_dir / \"cache.json\"\n if cache_file.exists():\n cache_file.unlink()\n self.config.pop(\"last_config\", None)\n self.config.pop(\"recent_models\", None)\n self._save_config()\n logger.info(\"Cache cleared\")\n\n def get_server_defaults(self) -> Dict[str, Any]:\n \"\"\"Get default server settings.\"\"\"\n return self.config.get(\n \"server_defaults\",\n {\n \"default_port\": 8000,\n \"auto_restart\": False,\n \"log_level\": \"info\",\n \"cleanup_on_exit\": True, # Default to cleaning up servers on exit\n },\n )\n\n def save_server_defaults(self, defaults: Dict[str, Any]) -> None:\n \"\"\"Save default server settings.\"\"\"\n self.config[\"server_defaults\"] = defaults\n self._save_config()\n\n def get_ui_preferences(self) -> Dict[str, Any]:\n \"\"\"Get UI preferences including progress bar style and log display settings.\"\"\"\n return self.config.get(\n \"ui_preferences\",\n {\n \"progress_bar_style\": \"blocks\", # Default style\n \"show_gpu_in_monitor\": True,\n \"log_lines_startup\": 50, # Number of log lines to show during startup\n \"log_lines_monitor\": 50, # Number of log lines to show in server monitor\n \"startup_refresh_rate\": 4.0, # Hz for startup log refresh\n \"monitor_refresh_rate\": 1.0, # Hz for monitor log refresh\n },\n )\n\n def save_ui_preferences(self, preferences: Dict[str, Any]) -> None:\n \"\"\"Save UI preferences.\"\"\"\n self.config[\"ui_preferences\"] = preferences\n self._save_config()\n\n # Shortcut management methods\n def get_all_shortcuts(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all shortcuts.\"\"\"\n return self.shortcut_manager.get_all_shortcuts()\n\n def get_shortcut(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific shortcut by name.\"\"\"\n return self.shortcut_manager.get_shortcut(name)\n\n def save_shortcut(self, name: str, shortcut_data: Dict[str, Any]) -> bool:\n \"\"\"Save or update a shortcut.\"\"\"\n return self.shortcut_manager.save_shortcut(name, shortcut_data)\n\n def delete_shortcut(self, name: str) -> bool:\n \"\"\"Delete a shortcut.\"\"\"\n return self.shortcut_manager.delete_shortcut(name)\n\n def list_shortcuts(self) -> List[Dict[str, Any]]:\n \"\"\"List all shortcuts with summary information.\"\"\"\n return self.shortcut_manager.list_shortcuts()\n\n def get_recent_shortcuts(self, limit: int = 5) -> List[Dict[str, Any]]:\n \"\"\"Get recently used shortcuts.\"\"\"\n return self.shortcut_manager.get_recent_shortcuts(limit)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 15704}, "tests/proxy/test_integration.py::273": {"resolved_imports": ["src/vllm_cli/proxy/config.py", "src/vllm_cli/proxy/manager.py", "src/vllm_cli/proxy/models.py", "src/vllm_cli/proxy/server_process.py"], "used_names": ["MagicMock", "ModelConfig", "ProxyConfig", "ProxyManager", "patch"], "enclosing_function": "test_gpu_assignment_integration", "extracted_code": "# Source: src/vllm_cli/proxy/manager.py\nclass ProxyManager:\n \"\"\"\n Manages the lifecycle of multiple vLLM servers and the proxy server.\n \"\"\"\n\n def __init__(self, config: Optional[ProxyConfig] = None):\n \"\"\"\n Initialize the proxy manager.\n\n Args:\n config: Proxy configuration (uses defaults if not provided)\n \"\"\"\n self.proxy_config = config or ProxyConfig()\n self.proxy_process: Optional[ProxyServerProcess] = None\n self.vllm_servers: Dict[str, VLLMServer] = {}\n self.config_manager = ConfigManager()\n\n def _proxy_api_request(\n self,\n method: str,\n endpoint: str,\n json_data: Optional[Dict] = None,\n timeout: float = 5.0,\n ) -> Optional[Any]:\n \"\"\"\n Helper method for making HTTP requests to the proxy API.\n\n Args:\n method: HTTP method (POST, DELETE, GET)\n endpoint: API endpoint path\n json_data: Optional JSON data for request body\n timeout: Request timeout in seconds\n\n Returns:\n Response object if successful, None if failed\n \"\"\"\n try:\n import httpx\n\n url = f\"http://localhost:{self.proxy_config.port}{endpoint}\"\n with httpx.Client() as client:\n if method == \"POST\":\n response = client.post(url, json=json_data, timeout=timeout)\n elif method == \"DELETE\":\n response = client.delete(url, timeout=timeout)\n elif method == \"GET\":\n response = client.get(url, timeout=timeout)\n else:\n logger.error(f\"Unsupported HTTP method: {method}\")\n return None\n\n if response.status_code == 200:\n return response\n else:\n logger.warning(\n f\"API request failed: {method} {endpoint} - \"\n f\"{response.status_code}: {response.text}\"\n )\n return None\n\n except Exception as e:\n logger.warning(f\"API request error: {method} {endpoint} - {e}\")\n return None\n\n def start_proxy(self) -> bool:\n \"\"\"\n Start the proxy server.\n\n Returns:\n True if proxy started successfully\n \"\"\"\n try:\n # Create proxy server process instance\n self.proxy_process = ProxyServerProcess(self.proxy_config)\n\n # Start proxy as a subprocess\n if not self.proxy_process.start():\n logger.error(\"Failed to start proxy server process\")\n return False\n\n # Give it a moment to fully initialize\n time.sleep(2)\n\n # Register all running models with the proxy\n # Note: We'll need to update this to work with subprocess\n # For now, models will register when they start\n\n logger.info(\n f\"Proxy server started on \"\n f\"{self.proxy_config.host}:{self.proxy_config.port}\"\n )\n return True\n\n except Exception as e:\n logger.error(f\"Failed to start proxy server: {e}\")\n return False\n\n def stop_proxy(self):\n \"\"\"Stop the proxy server and all vLLM instances.\"\"\"\n logger.info(\"Stopping proxy server and all model servers...\")\n\n # Stop all vLLM servers\n for model_name in list(self.vllm_servers.keys()):\n self.stop_model(model_name)\n\n # Stop proxy server process\n if self.proxy_process:\n self.proxy_process.stop()\n self.proxy_process = None\n logger.info(\"Proxy server stopped\")\n\n def start_model(self, model_config: ModelConfig) -> bool:\n \"\"\"\n Start a vLLM server for a specific model.\n\n Args:\n model_config: Configuration for the model\n\n Returns:\n True if server started successfully\n \"\"\"\n try:\n # Check if model is already running\n if model_config.name in self.vllm_servers:\n logger.warning(f\"Model '{model_config.name}' is already running\")\n return False\n\n # Build vLLM server configuration\n vllm_config = self._build_vllm_config(model_config)\n\n # Pre-register with proxy if it's running\n if self.proxy_process and self.proxy_process.is_running():\n pre_register_data = {\n \"port\": model_config.port,\n \"gpu_ids\": model_config.gpu_ids,\n \"config_name\": model_config.name,\n }\n\n response = self._proxy_api_request(\n \"POST\", \"/proxy/pre_register\", pre_register_data\n )\n if response:\n logger.info(\n f\"Pre-registered model '{model_config.name}' with proxy\"\n )\n else:\n logger.warning(\n f\"Failed to pre-register model '{model_config.name}' with proxy\"\n )\n\n # Create and start vLLM server\n server = VLLMServer(vllm_config)\n if not server.start():\n logger.error(f\"Failed to start vLLM server for '{model_config.name}'\")\n return False\n\n # Store server reference\n self.vllm_servers[model_config.name] = server\n\n logger.info(\n f\"Started vLLM server process for '{model_config.name}' \"\n f\"on port {model_config.port} using GPUs {model_config.gpu_ids}\"\n )\n\n # Note: Registration with proxy will happen after startup completes\n # Registration happens during wait_and_register_model()\n\n return True\n\n except Exception as e:\n logger.error(f\"Failed to start model '{model_config.name}': {e}\")\n return False\n\n def wait_and_register_model(self, model_config: ModelConfig) -> bool:\n \"\"\"\n Wait for a model to complete startup and trigger proxy refresh.\n\n Args:\n model_config: Configuration for the model\n\n Returns:\n True if model started and registered successfully\n \"\"\"\n if model_config.name not in self.vllm_servers:\n logger.error(f\"Model '{model_config.name}' not found in servers\")\n return False\n\n server = self.vllm_servers[model_config.name]\n\n # Wait for server to complete startup\n if not server.wait_for_startup():\n logger.error(f\"Server '{model_config.name}' failed to complete startup\")\n # Clean up the failed server\n server.stop()\n del self.vllm_servers[model_config.name]\n return False\n\n # Trigger proxy refresh to verify and activate the model\n if self.proxy_process and self.proxy_process.is_running():\n # Call refresh to verify the pre-registered model\n response = self._proxy_api_request(\n \"POST\", \"/proxy/refresh_models\", timeout=10.0\n )\n if response:\n try:\n result = response.json()\n summary = result.get(\"summary\", {})\n if summary.get(\"registered\", 0) > 0:\n logger.info(\n f\"Model '{model_config.name}' successfully activated \"\n f\"on port {model_config.port}\"\n )\n return True\n else:\n logger.warning(\n f\"Model '{model_config.name}' started but \"\n f\"not activated in proxy\"\n )\n return True # Model is running, just not registered\n except Exception as e:\n logger.error(f\"Failed to parse refresh response: {e}\")\n return True # Model is running\n else:\n logger.warning(\n f\"Failed to refresh proxy after starting \"\n f\"model '{model_config.name}'\"\n )\n return True # Model is running even if refresh failed\n\n logger.info(f\"Model '{model_config.name}' is ready\")\n return True\n\n def refresh_model_registrations(self) -> Dict[str, Any]:\n \"\"\"\n Refresh model registrations with the proxy.\n\n Calls the proxy's refresh endpoint to verify all models in the registry.\n\n Returns:\n Dictionary with registration results\n \"\"\"\n if not self.proxy_process or not self.proxy_process.is_running():\n logger.warning(\"Proxy is not running, cannot refresh registrations\")\n return {\"status\": \"error\", \"message\": \"Proxy server is not running\"}\n\n # Call the refresh endpoint\n response = self._proxy_api_request(\n \"POST\", \"/proxy/refresh_models\", timeout=10.0\n )\n\n if response:\n try:\n result = response.json()\n summary = result.get(\"summary\", {})\n logger.info(\n f\"Model registration refresh completed: \"\n f\"{summary.get('registered', 0)} newly registered, \"\n f\"{summary.get('failed', 0)} newly failed, \"\n f\"{summary.get('already_available', 0)} already available, \"\n f\"{summary.get('removed', 0)} removed\"\n )\n return result\n except Exception as e:\n logger.error(f\"Failed to parse refresh response: {e}\")\n return {\"status\": \"error\", \"message\": f\"Failed to parse response: {e}\"}\n else:\n logger.error(\"Failed to refresh model registrations\")\n return {\n \"status\": \"error\",\n \"message\": \"Failed to connect to proxy refresh endpoint\",\n }\n\n def get_proxy_registry_status(self) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get full model registry status from proxy.\n\n Returns:\n Dictionary containing proxy status and all registered models,\n or None if proxy is not running\n \"\"\"\n if not self.proxy_process or not self.proxy_process.is_running():\n logger.warning(\"Proxy is not running, cannot get registry status\")\n return None\n\n response = self._proxy_api_request(\"GET\", \"/proxy/registry\")\n if response:\n try:\n return response.json()\n except Exception as e:\n logger.error(f\"Failed to parse proxy status response: {e}\")\n return None\n return None\n\n def sleep_model(self, model_name: str, level: int = 1) -> bool:\n \"\"\"\n Put a model to sleep, freeing GPU memory but keeping the port.\n Runs asynchronously and returns immediately.\n\n Args:\n model_name: Name of the model to sleep\n level: Sleep level (1=offload weights, 2=discard weights)\n\n Returns:\n True if sleep request was initiated successfully\n \"\"\"\n if model_name not in self.vllm_servers:\n logger.warning(f\"Model '{model_name}' is not running\")\n return False\n\n server = self.vllm_servers[model_name]\n port = server.port\n\n try:\n import threading\n\n import httpx\n\n def sleep_thread():\n try:\n # Use 10 minute timeout for very slow operations\n client = httpx.Client(timeout=600.0)\n logger.info(\n f\"Sending sleep request to model '{model_name}' \"\n f\"(level {level})...\"\n )\n response = client.post(\n f\"http://localhost:{port}/sleep?level={level}\"\n )\n client.close()\n\n if response.status_code == 200:\n logger.info(\n f\"Model '{model_name}' successfully put to sleep \"\n f\"(level {level})\"\n )\n\n # Update proxy registry state\n if self.proxy_process and self.proxy_process.is_running():\n state_data = {\n \"port\": port,\n \"state\": \"sleeping\",\n \"sleep_level\": level,\n }\n self._proxy_api_request(\"POST\", \"/proxy/state\", state_data)\n else:\n logger.error(\n f\"Failed to sleep model '{model_name}': \"\n f\"HTTP {response.status_code}\"\n )\n\n except Exception as e:\n logger.error(f\"Failed to sleep model '{model_name}': {e}\")\n\n # Start in background thread\n thread = threading.Thread(target=sleep_thread, daemon=True)\n thread.start()\n logger.info(f\"Sleep operation initiated for '{model_name}'\")\n return True\n\n except Exception as e:\n logger.error(f\"Failed to initiate sleep for '{model_name}': {e}\")\n return False\n\n def wake_model(self, model_name: str) -> bool:\n \"\"\"\n Wake up a sleeping model.\n Runs asynchronously and returns immediately.\n\n Args:\n model_name: Name of the model to wake\n\n Returns:\n True if wake request was initiated successfully\n \"\"\"\n if model_name not in self.vllm_servers:\n logger.warning(f\"Model '{model_name}' is not running\")\n return False\n\n server = self.vllm_servers[model_name]\n port = server.port\n\n try:\n import threading\n\n import httpx\n\n def wake_thread():\n try:\n # Use 10 minute timeout for very slow operations\n client = httpx.Client(timeout=600.0)\n logger.info(f\"Sending wake-up request to model '{model_name}'...\")\n response = client.post(f\"http://localhost:{port}/wake_up\")\n client.close()\n\n # Accept both 200 (OK) and 202 (Accepted) as success\n if response.status_code in [200, 202]:\n logger.info(f\"Model '{model_name}' successfully woken up\")\n\n # Update proxy registry state\n if self.proxy_process and self.proxy_process.is_running():\n state_data = {\n \"port\": port,\n \"state\": \"running\",\n \"sleep_level\": 0,\n }\n self._proxy_api_request(\"POST\", \"/proxy/state\", state_data)\n else:\n logger.error(\n f\"Failed to wake model '{model_name}': \"\n f\"HTTP {response.status_code}\"\n )\n\n except Exception as e:\n logger.error(f\"Failed to wake model '{model_name}': {e}\")\n\n # Start in background thread\n thread = threading.Thread(target=wake_thread, daemon=True)\n thread.start()\n logger.info(f\"Wake operation initiated for '{model_name}'\")\n return True\n\n except Exception as e:\n logger.error(f\"Failed to initiate wake for '{model_name}': {e}\")\n return False\n\n def is_sleeping(self, model_name: str) -> bool:\n \"\"\"\n Check if a model is sleeping.\n\n Args:\n model_name: Name of the model to check\n\n Returns:\n True if model is sleeping\n \"\"\"\n if model_name not in self.vllm_servers:\n return False\n\n server = self.vllm_servers[model_name]\n port = server.port\n\n try:\n import httpx\n\n client = httpx.Client(timeout=5.0)\n response = client.get(f\"http://localhost:{port}/is_sleeping\")\n client.close()\n\n if response.status_code == 200:\n data = response.json()\n return data.get(\"is_sleeping\", False)\n except Exception:\n pass\n\n return False\n\n def stop_model(self, model_name: str) -> bool:\n \"\"\"\n Stop a vLLM server for a specific model.\n\n Args:\n model_name: Name of the model to stop\n\n Returns:\n True if server stopped successfully\n \"\"\"\n if model_name not in self.vllm_servers:\n logger.warning(f\"Model '{model_name}' is not running\")\n return False\n\n try:\n # Get the port before stopping\n server = self.vllm_servers[model_name]\n port = server.port\n\n # Stop the vLLM server\n server.stop()\n\n # Remove from tracking\n del self.vllm_servers[model_name]\n\n # Unregister from proxy if it's running\n if self.proxy_process and self.proxy_process.is_running():\n # Use the new registry endpoint with port\n if self._proxy_api_request(\"DELETE\", f\"/proxy/models/{port}\"):\n logger.debug(f\"Unregistered model on port {port} from proxy\")\n\n logger.info(f\"Stopped vLLM server for '{model_name}'\")\n return True\n\n except Exception as e:\n logger.error(f\"Failed to stop model '{model_name}': {e}\")\n return False\n\n def unregister_model_from_proxy(self, port: int) -> bool:\n \"\"\"\n Unregister a model from the proxy registry by port.\n This is useful for cleaning up stopped models.\n\n Args:\n port: Port number of the model to unregister\n\n Returns:\n True if successfully unregistered or proxy not running\n \"\"\"\n if self.proxy_process and self.proxy_process.is_running():\n if self._proxy_api_request(\"DELETE\", f\"/proxy/models/{port}\"):\n logger.debug(f\"Unregistered model on port {port} from proxy\")\n return True\n return False\n return True # If proxy not running, consider it success\n\n def start_all_models_no_wait(self) -> int:\n \"\"\"\n Start all model processes without waiting for startup completion.\n\n This method starts all model servers concurrently and returns immediately,\n allowing the caller to monitor startup progress in real-time.\n\n Returns:\n Number of model processes successfully launched\n \"\"\"\n started_count = 0\n for model_config in self.proxy_config.models:\n if model_config.enabled:\n if self.start_model(model_config):\n started_count += 1\n # Small delay to avoid resource conflicts\n time.sleep(0.5)\n\n return started_count\n\n def start_models_with_priorities(self):\n \"\"\"\n Start models sequentially based on loading_priority.\n\n Models are grouped by priority (lower numbers first). Models within\n the same priority group start in parallel. This is a generator that\n yields each priority group after starting its models, allowing the\n UI layer to monitor startup progress with live feedback.\n\n This is useful for GPU-shared deployments where models with low\n gpu-memory-utilization should load first to claim KV cache space.\n\n Yields:\n Dictionary for each priority group:\n - priority: Priority number (or float('inf') for None)\n - priority_label: Human-readable priority label\n - models: List of ModelConfig instances in this group\n - started_models: List of ModelConfig instances that started successfully\n - failed_models: List of model names that failed to start\n - group_index: Current group number (1-indexed)\n - total_groups: Total number of priority groups\n - total_models: Total number of models across all groups\n \"\"\"\n from collections import defaultdict\n\n # Group models by loading_priority\n priority_groups = defaultdict(list)\n for model_config in self.proxy_config.models:\n if model_config.enabled:\n priority = model_config.loading_priority\n # Use a large number for None priority (load last)\n effective_priority = priority if priority is not None else float(\"inf\")\n priority_groups[effective_priority].append(model_config)\n\n # Sort priority groups (ascending order)\n sorted_priorities = sorted(priority_groups.keys())\n\n total_models = sum(len(models) for models in priority_groups.values())\n\n logger.info(\n f\"Starting {total_models} models in {len(sorted_priorities)} \"\n f\"priority group(s)\"\n )\n\n # Process each priority group sequentially\n for priority_idx, priority in enumerate(sorted_priorities, 1):\n models = priority_groups[priority]\n priority_label = (\n f\"Priority {int(priority)}\"\n if priority != float(\"inf\")\n else \"No Priority (Parallel)\"\n )\n\n logger.info(\n f\"Starting priority group {priority_idx}/{len(sorted_priorities)}: \"\n f\"{priority_label} ({len(models)} model(s))\"\n )\n\n # Start all models in this priority group (non-blocking)\n group_started = []\n group_failed = []\n\n for model_config in models:\n if self.start_model(model_config):\n group_started.append(model_config)\n logger.info(\n f\"Started {model_config.name} (port {model_config.port})\"\n )\n # Small delay to avoid resource conflicts\n time.sleep(0.5)\n else:\n group_failed.append(model_config.name)\n logger.error(f\"Failed to start {model_config.name}\")\n\n # Yield this group for UI monitoring (non-blocking)\n yield {\n \"priority\": priority,\n \"priority_label\": priority_label,\n \"models\": models,\n \"started_models\": group_started,\n \"failed_models\": group_failed,\n \"group_index\": priority_idx,\n \"total_groups\": len(sorted_priorities),\n \"total_models\": total_models,\n }\n\n # Control returns here after UI finishes monitoring this group\n\n def _build_vllm_config(self, model_config: ModelConfig) -> Dict[str, Any]:\n \"\"\"\n Build vLLM server configuration from model configuration.\n\n Args:\n model_config: Model configuration\n\n Returns:\n vLLM server configuration dictionary\n \"\"\"\n # Start with profile configuration if specified\n config = {}\n if model_config.profile:\n profile = self.config_manager.get_profile(model_config.profile)\n if profile:\n config = profile.get(\"config\", {}).copy()\n\n # Set model, port, and host\n config[\"model\"] = model_config.model_path\n config[\"port\"] = model_config.port\n config[\"host\"] = self.proxy_config.host # Use host from proxy configuration\n\n # Enable sleep mode for better resource management\n config[\"enable_sleep_mode\"] = True\n\n # Handle GPU assignment\n if model_config.gpu_ids:\n # Set CUDA_VISIBLE_DEVICES via device field\n config[\"device\"] = \",\".join(str(gpu) for gpu in model_config.gpu_ids)\n\n num_gpus = len(model_config.gpu_ids)\n\n # For single GPU assignment, override any parallel settings from profile\n if num_gpus == 1:\n # Remove parallel configuration that conflicts with single GPU\n conflicting_settings = [\n \"tensor_parallel_size\",\n \"pipeline_parallel_size\",\n \"distributed_executor_backend\",\n ]\n\n removed_settings = []\n for setting in conflicting_settings:\n if setting in config:\n removed_settings.append(f\"{setting}={config[setting]}\")\n del config[setting]\n\n # Disable expert parallelism for single GPU\n if config.get(\"enable_expert_parallel\"):\n removed_settings.append(\"enable_expert_parallel=True\")\n config[\"enable_expert_parallel\"] = False\n\n if removed_settings:\n logger.warning(\n f\"Model '{model_config.name}' assigned single GPU. \"\n f\"Overriding profile settings: {', '.join(removed_settings)}\"\n )\n\n elif num_gpus > 1:\n # For multi-GPU, set tensor_parallel_size if not already set\n if \"tensor_parallel_size\" not in config:\n config[\"tensor_parallel_size\"] = num_gpus\n elif config[\"tensor_parallel_size\"] > num_gpus:\n # Adjust if profile expects more GPUs than assigned\n logger.warning(\n f\"Model '{model_config.name}': Adjusting tensor_parallel_size \"\n f\"from {config['tensor_parallel_size']} to {num_gpus} \"\n f\"(assigned GPUs)\"\n )\n config[\"tensor_parallel_size\"] = num_gpus\n\n # Apply any config overrides\n config.update(model_config.config_overrides)\n\n return config\n\n def get_status(self) -> Dict[str, Any]:\n \"\"\"\n Get status of proxy and all model servers.\n\n Returns:\n Status dictionary\n \"\"\"\n status = {\n \"proxy_running\": self.proxy_process and self.proxy_process.is_running(),\n \"proxy_host\": self.proxy_config.host,\n \"proxy_port\": self.proxy_config.port,\n \"models\": [],\n }\n\n for model_name, server in self.vllm_servers.items():\n model_status = {\n \"name\": model_name,\n \"running\": server.is_running(),\n \"port\": server.port,\n \"uptime\": None,\n }\n\n if server.is_running() and server.start_time:\n uptime = time.time() - server.start_time.timestamp()\n model_status[\"uptime\"] = uptime\n\n status[\"models\"].append(model_status)\n\n return status\n\n def reload_model(self, model_name: str) -> bool:\n \"\"\"\n Reload a model (stop and start again).\n\n Args:\n model_name: Name of the model to reload\n\n Returns:\n True if reload successful\n \"\"\"\n # Find the model config\n model_config = None\n for config in self.proxy_config.models:\n if config.name == model_name:\n model_config = config\n break\n\n if not model_config:\n logger.error(f\"Model '{model_name}' not found in configuration\")\n return False\n\n # Stop if running\n if model_name in self.vllm_servers:\n self.stop_model(model_name)\n time.sleep(2) # Wait before restarting\n\n # Start the model\n if not self.start_model(model_config):\n return False\n\n # Wait for startup and register\n return self.wait_and_register_model(model_config)\n\n def allocate_gpus_automatically(self) -> List[ModelConfig]:\n \"\"\"\n Automatically allocate GPUs to models based on available resources.\n\n Returns:\n List of model configurations with GPU allocations\n \"\"\"\n from ..system import get_gpu_info\n\n # Get available GPUs\n gpu_info = get_gpu_info()\n if not gpu_info:\n logger.warning(\"No GPUs available for allocation\")\n return []\n\n num_gpus = len(gpu_info)\n models = self.proxy_config.models\n\n # Simple allocation strategy: distribute GPUs evenly\n allocated_configs = []\n\n if len(models) <= num_gpus:\n # Each model gets at least one GPU\n gpus_per_model = num_gpus // len(models)\n remaining_gpus = num_gpus % len(models)\n\n gpu_index = 0\n for i, model in enumerate(models):\n num_gpus_for_model = gpus_per_model\n if i < remaining_gpus:\n num_gpus_for_model += 1\n\n model.gpu_ids = list(range(gpu_index, gpu_index + num_gpus_for_model))\n gpu_index += num_gpus_for_model\n\n # Allocate port if not specified\n if not model.port:\n model.port = get_next_available_port(8001 + i)\n\n allocated_configs.append(model)\n else:\n # More models than GPUs - some models won't be allocated\n logger.warning(\n f\"More models ({len(models)}) than GPUs ({num_gpus}). \"\n f\"Only first {num_gpus} models will be allocated.\"\n )\n for i in range(num_gpus):\n models[i].gpu_ids = [i]\n if not models[i].port:\n models[i].port = get_next_available_port(8001 + i)\n allocated_configs.append(models[i])\n\n return allocated_configs\n\n def _get_model_config_by_name(self, model_name: str) -> Optional[ModelConfig]:\n \"\"\"\n Get model configuration by model name.\n\n Args:\n model_name: Name of the model\n\n Returns:\n ModelConfig if found, None otherwise\n \"\"\"\n for model_config in self.proxy_config.models:\n if model_config.name == model_name:\n return model_config\n return None\n\n @classmethod\n def from_config_file(cls, config_path: Path) -> \"ProxyManager\":\n \"\"\"\n Create ProxyManager from a configuration file.\n\n Args:\n config_path: Path to configuration file (YAML or JSON)\n\n Returns:\n ProxyManager instance\n \"\"\"\n import json\n\n import yaml\n\n with open(config_path, \"r\") as f:\n if config_path.suffix in [\".yaml\", \".yml\"]:\n config_dict = yaml.safe_load(f)\n else:\n config_dict = json.load(f)\n\n # Parse proxy configuration\n proxy_config = ProxyConfig(**config_dict.get(\"proxy\", {}))\n\n # Parse model configurations\n models = []\n for model_dict in config_dict.get(\"models\", []):\n models.append(ModelConfig(**model_dict))\n proxy_config.models = models\n\n return cls(proxy_config)\n\n\n# Source: src/vllm_cli/proxy/models.py\nclass ModelConfig(BaseModel):\n \"\"\"Configuration for a single model in the proxy.\"\"\"\n\n name: str = Field(..., description=\"Model identifier for API requests\")\n model_path: str = Field(..., description=\"Path or HuggingFace model ID\")\n gpu_ids: List[int] = Field(default_factory=list, description=\"GPU IDs to use\")\n port: int = Field(..., description=\"Port for the vLLM server\")\n profile: Optional[str] = Field(None, description=\"vLLM CLI profile to use\")\n config_overrides: Dict[str, Any] = Field(\n default_factory=dict, description=\"Additional vLLM configuration\"\n )\n enabled: bool = Field(True, description=\"Whether model is enabled\")\n loading_priority: Optional[int] = Field(\n None,\n description=\"Loading priority (lower numbers load first). \"\n \"Models with same priority load in parallel. \"\n \"Models with None priority load after all prioritized models.\",\n )\n\nclass ProxyConfig(BaseModel):\n \"\"\"Configuration for the proxy server.\"\"\"\n\n host: str = Field(\"0.0.0.0\", description=\"Proxy server host\") # nosec B104\n port: int = Field(8000, description=\"Proxy server port\")\n models: List[ModelConfig] = Field(\n default_factory=list, description=\"List of models to serve\"\n )\n enable_cors: bool = Field(True, description=\"Enable CORS headers\")\n enable_metrics: bool = Field(True, description=\"Enable metrics endpoint\")\n log_requests: bool = Field(False, description=\"Log all requests\")", "n_imports_parsed": 9, "n_files_resolved": 4, "n_chars_extracted": 32708}, "tests/test_cli_parser.py::113": {"resolved_imports": ["src/vllm_cli/cli/parser.py"], "used_names": ["create_parser"], "enclosing_function": "test_stop_command_with_port", "extracted_code": "# Source: src/vllm_cli/cli/parser.py\ndef create_parser() -> argparse.ArgumentParser:\n \"\"\"\n Create the main argument parser for vLLM CLI.\n\n Sets up the main parser with all subcommands and their arguments.\n\n Returns:\n Configured ArgumentParser instance\n \"\"\"\n parser = argparse.ArgumentParser(\n prog=\"vllm-cli\",\n description=\"vLLM CLI - Convenient LLM serving tool\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"Examples:\n vllm-cli # Interactive mode\n vllm-cli serve MODEL --profile standard # Serve with profile\n vllm-cli serve MODEL --quantization awq # Serve with AWQ quantization\n vllm-cli serve MODEL --extra-args \"--seed 42\" # With custom vLLM args\n vllm-cli info # System information\n vllm-cli models # List available models\n vllm-cli status # Show active servers\"\"\",\n )\n\n # Global options\n from .. import __version__\n\n parser.add_argument(\n \"--version\", action=\"version\", version=f\"vLLM CLI {__version__}\"\n )\n\n # Create subparsers for commands\n subparsers = parser.add_subparsers(\n dest=\"command\",\n help=\"Available commands\",\n metavar=\"{serve,proxy,info,models,shortcuts,status,stop,dirs}\",\n )\n\n # Add individual command parsers\n _add_serve_parser(subparsers)\n _add_proxy_parser(subparsers)\n _add_info_parser(subparsers)\n _add_models_parser(subparsers)\n _add_shortcuts_parser(subparsers)\n _add_status_parser(subparsers)\n _add_stop_parser(subparsers)\n _add_dirs_parser(subparsers)\n\n return parser", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1705}, "tests/test_server_manager.py::151": {"resolved_imports": ["src/vllm_cli/server/__init__.py", "src/vllm_cli/server/process.py", "src/vllm_cli/server/manager.py"], "used_names": ["VLLMServer"], "enclosing_function": "test_get_recent_logs", "extracted_code": "# Source: src/vllm_cli/server/manager.py\nclass VLLMServer:\n \"\"\"\n Manages a vLLM server instance with comprehensive lifecycle control.\n\n This class handles the complete lifecycle of a vLLM server including\n configuration, process management, logging, monitoring, and cleanup.\n It supports both programmatically started servers and external server\n detection and management.\n\n Attributes:\n config: Server configuration dictionary\n model: Model name being served\n port: Port number the server is listening on\n process: Subprocess or external process reference\n log_file: File handle for server logs\n log_queue: Thread-safe queue for log lines\n log_thread: Background thread for log monitoring\n start_time: Timestamp when server was started\n log_path: Path to the server's log file\n \"\"\"\n\n def __init__(self, config: Dict[str, Any]) -> None:\n \"\"\"\n Initialize a vLLM server instance.\n\n Sets up the server configuration, logging infrastructure, and\n prepares the instance for server lifecycle management.\n\n Args:\n config: Server configuration dictionary containing model name,\n port, and other vLLM-specific parameters\n \"\"\"\n self.config: Dict[str, Any] = config\n\n # Extract model name - handle both string and dict (LoRA config) formats\n model_config = config.get(\"model\", \"unknown\")\n if isinstance(model_config, dict):\n # LoRA configuration - extract base model name\n self.model: str = model_config.get(\"model\", \"unknown\")\n else:\n # Regular string model name\n self.model: str = model_config\n\n self.port: int = config.get(\"port\", 8000)\n self.process: Optional[Union[subprocess.Popen, Any]] = None\n self.log_file: Optional[TextIO] = None\n self.log_queue: Queue[str] = Queue()\n self.log_thread: Optional[Thread] = None\n self.start_time: Optional[datetime] = None\n self.log_path: Path\n self._recent_logs: List[str] = []\n\n # Setup logging\n log_dir = Path.home() / \".vllm-cli\" / \"logs\"\n log_dir.mkdir(parents=True, exist_ok=True)\n\n timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n self.log_path = log_dir / f\"vllm_{self.model.replace('/', '_')}_{timestamp}.log\"\n\n def start(self) -> bool:\n \"\"\"\n Start the vLLM server.\n\n Returns:\n True if server started successfully, False otherwise\n \"\"\"\n if self.is_running():\n logger.warning(f\"Server already running for {self.model}\")\n return False\n\n try:\n # Build command - run directly without conda wrapper\n full_cmd = self._build_command()\n\n logger.info(f\"Starting vLLM server with command: {' '.join(full_cmd)}\")\n\n # Open log file for writing\n self.log_file = open(self.log_path, \"w\", buffering=1)\n\n # Start with parent environment\n env = os.environ.copy()\n # Note: No longer forcing PYTHONUNBUFFERED=1, let user control it\n\n # Layer 1: Apply universal environment variables from settings\n config_manager = ConfigManager()\n universal_env = config_manager.config.get(\"universal_environment\", {})\n if universal_env:\n logger.info(\n f\"Applying {len(universal_env)} universal environment variable(s)\"\n )\n for key, value in universal_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting universal {key}={value}\")\n else:\n logger.debug(f\"Setting universal {key}=\")\n\n # Layer 2: Apply profile environment variables (override universal)\n profile_env = self.config.get(\"profile_environment\", {})\n if profile_env:\n logger.info(\n f\"Applying {len(profile_env)} profile environment variable(s)\"\n )\n for key, value in profile_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting profile {key}={value}\")\n else:\n logger.debug(f\"Setting profile {key}=\")\n\n # Handle GPU device selection via CUDA_VISIBLE_DEVICES\n # This overrides any CUDA_VISIBLE_DEVICES from the profile\n if self.config.get(\"device\"):\n device_str = str(self.config[\"device\"])\n env[\"CUDA_VISIBLE_DEVICES\"] = device_str\n logger.info(f\"Setting CUDA_VISIBLE_DEVICES={device_str}\")\n\n # If using specific GPUs, adjust tensor parallel size if needed\n device_list = [d.strip() for d in device_str.split(\",\")]\n num_devices = len(device_list)\n\n # Check if tensor_parallel_size is set and compatible\n if self.config.get(\"tensor_parallel_size\"):\n tp_size = self.config[\"tensor_parallel_size\"]\n if tp_size > num_devices:\n logger.warning(\n f\"tensor_parallel_size ({tp_size}) > number of selected devices ({num_devices}). \"\n f\"Adjusting tensor_parallel_size to {num_devices}\"\n )\n self.config[\"tensor_parallel_size\"] = num_devices\n elif num_devices % tp_size != 0:\n logger.warning(\n f\"Number of GPUs ({num_devices}) is not evenly divisible by \"\n f\"tensor_parallel_size ({tp_size}). This may lead to inefficient GPU utilization. \"\n f\"Consider using tensor_parallel_size of: \"\n f\"{', '.join(str(i) for i in range(1, num_devices + 1) if num_devices % i == 0)}\"\n )\n\n # Add HuggingFace token if configured\n config_manager = ConfigManager()\n hf_token = config_manager.config.get(\"hf_token\")\n if hf_token:\n env[\"HF_TOKEN\"] = hf_token\n env[\"HUGGING_FACE_HUB_TOKEN\"] = hf_token # Some tools use this variant\n logger.info(\"HuggingFace token configured for server\")\n\n # Enable development mode for sleep endpoints if sleep mode is enabled\n if self.config.get(\"enable_sleep_mode\"):\n env[\"VLLM_SERVER_DEV_MODE\"] = \"1\"\n logger.info(\"Sleep mode enabled with development endpoints\")\n\n # Start the process with proper pipe configuration\n # Use start_new_session=True to create a new process group\n # This prevents the child process from receiving Ctrl+C signals\n self.process = subprocess.Popen(\n full_cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n text=True,\n bufsize=0, # Unbuffered\n universal_newlines=True,\n env=env,\n start_new_session=True, # Create new process group to isolate from parent signals\n )\n\n # Start log monitoring thread\n self._start_log_monitor()\n\n # Set start time and add to registry\n self.start_time = datetime.now()\n from .process import add_server\n\n add_server(self)\n\n # Return immediately - let the UI monitor the startup\n logger.info(\n f\"vLLM server process launched for {self.model} on port {self.port}\"\n )\n return True\n\n except Exception as e:\n logger.error(f\"Error starting vLLM server: {e}\")\n return False\n\n def _build_command(self) -> List[str]:\n \"\"\"\n Build the vLLM command from configuration using the schema.\n\n Returns:\n List of command arguments\n \"\"\"\n # Use the new ConfigManager to build CLI args\n config_manager = ConfigManager()\n\n # Start with the vllm command\n cmd = [\"vllm\"]\n\n # Add the arguments built from schema\n cli_args = config_manager.build_cli_args(self.config)\n cmd.extend(cli_args)\n\n # Handle extra_args if present (backward compatibility)\n if self.config.get(\"extra_args\"):\n self._add_extra_args_to_command(cmd)\n\n logger.debug(f\"Built command: {' '.join(cmd)}\")\n return cmd\n\n def _add_extra_args_to_command(self, cmd: List[str]) -> None:\n \"\"\"\n Add extra arguments to the vLLM command.\n\n Args:\n cmd: Command list to extend with extra arguments\n \"\"\"\n try:\n extra_args = shlex.split(self.config[\"extra_args\"])\n if extra_args:\n logger.info(f\"Adding extra arguments: {extra_args}\")\n cmd.extend(extra_args)\n except ValueError as e:\n logger.warning(f\"Failed to parse extra_args: {e}\")\n\n def _start_log_monitor(self) -> None:\n \"\"\"\n Start a thread to monitor log output from the vLLM server process.\n\n Creates a daemon thread that continuously reads stdout/stderr from\n the server process, writes to log files, and queues log lines for\n real-time display in the UI.\n \"\"\"\n self.log_thread = Thread(target=self._log_monitor_worker, daemon=True)\n self.log_thread.start()\n\n def _log_monitor_worker(self) -> None:\n \"\"\"\n Worker function for log monitoring thread.\n\n Continuously reads log output from the server process and handles\n file writing and queue management for UI display.\n \"\"\"\n try:\n self.log_queue.put(\"Starting vLLM server process...\")\n\n while self._should_continue_monitoring():\n if self._process_log_line():\n continue\n else:\n # No line read, check if process still running\n if self.process and self.process.poll() is not None:\n break\n time.sleep(0.01) # Small sleep to prevent busy waiting\n\n except Exception as e:\n logger.error(f\"Error in log monitor: {e}\")\n self.log_queue.put(f\"Log monitoring error: {e}\")\n\n def _should_continue_monitoring(self) -> bool:\n \"\"\"\n Check if log monitoring should continue.\n\n Returns:\n True if monitoring should continue, False otherwise\n \"\"\"\n return (\n self.is_running()\n and self.process\n and hasattr(self.process, \"stdout\")\n and self.process.stdout\n )\n\n def _process_log_line(self) -> bool:\n \"\"\"\n Process a single log line from the server output.\n\n Reads one line from the process stdout, writes it to the log file,\n and adds it to the queue for UI display after filtering and formatting.\n\n Returns:\n True if a line was processed, False if no line was available\n \"\"\"\n if not (self.process and self.process.stdout):\n return False\n\n line = self.process.stdout.readline()\n if not line:\n return False\n\n # Write to log file\n self._write_to_log_file(line)\n\n # Process for UI display\n line_stripped = line.strip()\n if line_stripped and self._should_display_log_line(line_stripped):\n # Truncate overly long lines\n if len(line_stripped) > 200:\n line_stripped = line_stripped[:197] + \"...\"\n\n self.log_queue.put(line_stripped)\n logger.debug(f\"Log captured: {line_stripped[:50]}...\")\n\n return True\n\n def _write_to_log_file(self, line: str) -> None:\n \"\"\"\n Write a log line to the log file.\n\n Args:\n line: Log line to write\n \"\"\"\n if self.log_file and not self.log_file.closed:\n self.log_file.write(line)\n self.log_file.flush()\n\n def _should_display_log_line(self, line: str) -> bool:\n \"\"\"\n Determine if a log line should be displayed in the UI.\n\n Filters out certain system messages that are not useful for users.\n\n Args:\n line: Stripped log line to check\n\n Returns:\n True if the line should be displayed, False otherwise\n \"\"\"\n # Filter out conda activation and system messages\n filtered_messages = [\n \"Activated CUDA\",\n \"Using nvcc from:\",\n \"Cuda compilation tools\",\n ]\n return not any(skip in line for skip in filtered_messages)\n\n def stop(self) -> bool:\n \"\"\"\n Stop the vLLM server.\n\n Returns:\n True if server stopped successfully, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n try:\n # Check if this is an external server\n if hasattr(self.process, \"terminate\"):\n # Normal subprocess\n # Since we created a new session, we need to terminate the entire process group\n try:\n # Get the process group ID (pgid)\n # Since we used start_new_session=True, the pgid is the same as the pid\n pgid = self.process.pid\n\n # Send SIGTERM to the entire process group for graceful shutdown\n logger.info(f\"Sending SIGTERM to process group {pgid}\")\n os.killpg(pgid, signal.SIGTERM)\n\n # Wait for process to terminate\n try:\n self.process.wait(timeout=10)\n logger.info(f\"Process group {pgid} terminated gracefully\")\n except subprocess.TimeoutExpired:\n # Force kill if not terminated\n logger.warning(\n f\"Process group {pgid} did not terminate, sending SIGKILL\"\n )\n os.killpg(pgid, signal.SIGKILL)\n self.process.wait()\n logger.info(f\"Process group {pgid} force killed\")\n\n except ProcessLookupError:\n # Process already dead\n logger.info(\"Process already terminated\")\n except PermissionError as e:\n # Fall back to terminating just the process\n logger.warning(\n f\"Permission denied for process group kill: {e}, falling back to process termination\"\n )\n self.process.terminate()\n try:\n self.process.wait(timeout=10)\n except subprocess.TimeoutExpired:\n self.process.kill()\n self.process.wait()\n elif hasattr(self.process, \"pid\"):\n # External server - kill entire process group or individual process\n try:\n pgid = self.process.pid\n killed = False\n\n # First attempt: try to kill process group\n try:\n os.killpg(pgid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process group {pgid}\")\n killed = True\n except (OSError, ProcessLookupError) as e:\n # Process group kill failed, try individual process\n logger.debug(\n f\"Process group kill failed: {e}, trying individual process\"\n )\n try:\n # Ensure pid is an integer (handle Mock objects)\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process {self.process.pid}\")\n killed = True\n except ProcessLookupError:\n # Process already dead\n logger.info(\n f\"Process {self.process.pid} already terminated\"\n )\n except OSError as e:\n logger.warning(\n f\"Failed to send SIGTERM to {self.process.pid}: {e}\"\n )\n\n if killed:\n # Wait for graceful shutdown\n time.sleep(2)\n\n # Check if still running and force kill if needed\n if self.is_running():\n try:\n os.killpg(pgid, signal.SIGKILL)\n logger.info(f\"Force killed process group {pgid}\")\n except (OSError, ProcessLookupError):\n # Process group kill failed, try individual\n try:\n # Ensure pid is an integer (handle Mock objects in tests)\n if hasattr(self.process, \"pid\"):\n try:\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGKILL)\n logger.info(f\"Force killed process {pid}\")\n except (TypeError, ValueError):\n # PID is not a valid integer (might be Mock)\n pass\n except ProcessLookupError:\n pass # Already dead\n except OSError as e:\n logger.error(\n f\"Failed to force kill {self.process.pid}: {e}\"\n )\n\n except Exception as e:\n logger.error(f\"Unexpected error stopping external server: {e}\")\n\n # Close log file if we have one\n if hasattr(self, \"log_file\") and self.log_file:\n self.log_file.close()\n\n # Remove from registry\n from .process import remove_server\n\n remove_server(self)\n\n logger.info(f\"vLLM server stopped for {self.model}\")\n return True\n\n except Exception as e:\n logger.error(f\"Error stopping vLLM server: {e}\")\n return False\n\n def is_running(self) -> bool:\n \"\"\"\n Check if the server is running.\n\n Returns:\n True if server is running, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n # Check if this is an external server (detected, not started by us)\n if hasattr(self.process, \"poll\"):\n # Normal subprocess\n return self.process.poll() is None\n elif hasattr(self.process, \"pid\"):\n # External server - check if PID still exists\n try:\n import psutil\n\n return psutil.pid_exists(self.process.pid)\n except ImportError:\n # Fallback to os method\n try:\n os.kill(self.process.pid, 0)\n return True\n except (OSError, ProcessLookupError):\n return False\n\n return False\n\n def get_status(self) -> Dict[str, Any]:\n \"\"\"\n Get server status information.\n\n Returns:\n Dictionary with status information\n \"\"\"\n status = {\n \"model\": self.model,\n \"port\": self.port,\n \"running\": self.is_running(),\n \"pid\": self.process.pid if self.process else None,\n \"start_time\": self.start_time.isoformat() if self.start_time else None,\n \"log_path\": str(self.log_path) if self.log_path else None,\n }\n\n if self.is_running() and self.start_time:\n uptime = datetime.now() - self.start_time\n status[\"uptime_seconds\"] = uptime.total_seconds()\n status[\"uptime_str\"] = str(uptime).split(\".\")[0]\n\n return status\n\n def wait_for_startup(self) -> bool:\n \"\"\"\n Wait for the server to complete startup.\n\n Monitors the server logs for startup completion indicators and verifies\n via HTTP endpoint. Will wait indefinitely until either startup completes\n or the process terminates.\n\n Returns:\n True if server started successfully, False if process terminated\n \"\"\"\n import time\n\n logger.info(f\"Waiting for {self.model} server to complete startup...\")\n\n # Track if we've seen startup indicators in logs\n log_indicates_ready = False\n\n while True:\n # Check if server is still running\n if not self.is_running():\n logger.error(\n f\"Server process for {self.model} terminated during startup\"\n )\n return False\n\n # Get recent logs to check for startup completion\n recent_logs = self.get_recent_logs(50)\n\n if recent_logs and not log_indicates_ready:\n # Check for startup completion indicators\n for log in recent_logs:\n log_lower = log.lower()\n # Look for the explicit \"Application startup complete\" message\n if \"application startup complete\" in log_lower:\n logger.debug(f\"Server {self.model} startup detected in logs\")\n log_indicates_ready = True\n break\n\n # Also check for other ready indicators as fallback\n if any(\n indicator in log_lower\n for indicator in [\n \"uvicorn running on\",\n \"started server process\",\n \"server is ready\",\n \"api server started\",\n ]\n ):\n logger.debug(\n f\"Server {self.model} startup detected via ready indicator\"\n )\n log_indicates_ready = True\n break\n\n # If logs indicate ready, verify via HTTP\n if log_indicates_ready:\n # Try to verify server is actually ready via HTTP\n port = self.config.get(\"port\")\n if port:\n try:\n import httpx\n\n with httpx.Client() as client:\n # Try /v1/models endpoint first (most reliable)\n response = client.get(\n f\"http://localhost:{port}/v1/models\", timeout=5.0\n )\n if response.status_code == 200:\n logger.info(\n f\"Server {self.model} startup complete \"\n \"(verified via HTTP)\"\n )\n return True\n except httpx.ConnectError:\n # Server not ready yet, continue waiting\n logger.debug(\n f\"Server {self.model} not accepting connections yet\"\n )\n except Exception as e:\n # Log but continue, might be network issue\n logger.debug(f\"HTTP verification failed: {e}\")\n else:\n # No port configured, trust the logs\n logger.info(\n f\"Server {self.model} startup complete (no port for verification)\"\n )\n return True\n\n # Small sleep to avoid busy waiting\n time.sleep(0.5)\n\n def get_recent_logs(self, n: int = 20) -> List[str]:\n \"\"\"\n Get recent log lines from the server output.\n\n Retrieves the most recent log lines from either the in-memory queue\n or the log file on disk. This method ensures logs are available even\n after the monitoring thread has processed them.\n\n Args:\n n: Number of recent lines to return (default: 20)\n\n Returns:\n List of recent log lines, with the most recent last\n \"\"\"\n # Update recent logs from queue\n self._update_recent_logs_from_queue()\n\n # Return from memory if available\n if self._recent_logs:\n return self._recent_logs[-n:]\n\n # Fallback to reading from file\n return self._read_logs_from_file(n)\n\n def _update_recent_logs_from_queue(self) -> None:\n \"\"\"\n Update the recent logs cache from the log queue.\n\n Drains all available log lines from the queue and adds them\n to the recent logs cache, maintaining a maximum of 100 lines.\n \"\"\"\n temp_logs = []\n\n # Get all available logs from queue (don't block)\n while not self.log_queue.empty():\n try:\n log_line = self.log_queue.get_nowait()\n temp_logs.append(log_line)\n except Empty:\n break\n\n if temp_logs:\n self._recent_logs.extend(temp_logs)\n # Keep only the last 100 logs in memory to prevent unbounded growth\n self._recent_logs = self._recent_logs[-100:]\n\n def _read_logs_from_file(self, n: int) -> List[str]:\n \"\"\"\n Read recent log lines from the log file.\n\n Args:\n n: Number of lines to read\n\n Returns:\n List of log lines from file\n \"\"\"\n if not (self.log_path and self.log_path.exists()):\n return []\n\n try:\n with open(self.log_path, \"r\") as f:\n file_logs = f.readlines()\n if file_logs:\n # Get last n lines, strip them\n logs = [line.strip() for line in file_logs[-n:]]\n # Update recent logs cache\n self._recent_logs = logs[-100:]\n return logs\n except Exception as e:\n logger.debug(f\"Error reading log file: {e}\")\n\n return []\n\n def restart(self) -> bool:\n \"\"\"\n Restart the server with the same configuration.\n\n Returns:\n True if restart successful, False otherwise\n \"\"\"\n logger.info(f\"Restarting vLLM server for {self.model}\")\n\n # Stop if running\n if self.is_running():\n self.stop()\n time.sleep(2) # Wait a bit before restarting\n\n # Start again\n return self.start()\n\n def health_check(self) -> bool:\n \"\"\"\n Perform a health check on the server.\n\n Returns:\n True if server is healthy, False otherwise\n \"\"\"\n if not self.is_running():\n return False\n\n try:\n import requests\n\n # Try to connect to the server\n response = requests.get(f\"http://localhost:{self.port}/health\", timeout=5)\n\n return response.status_code == 200\n\n except Exception:\n # If requests fails, just check process\n return self.is_running()", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 27979}, "tests/test_environment_variables.py::882": {"resolved_imports": ["src/vllm_cli/config/manager.py", "src/vllm_cli/server/manager.py"], "used_names": ["Mock", "VLLMServer", "os", "patch"], "enclosing_function": "test_full_environment_stack", "extracted_code": "# Source: src/vllm_cli/server/manager.py\nclass VLLMServer:\n \"\"\"\n Manages a vLLM server instance with comprehensive lifecycle control.\n\n This class handles the complete lifecycle of a vLLM server including\n configuration, process management, logging, monitoring, and cleanup.\n It supports both programmatically started servers and external server\n detection and management.\n\n Attributes:\n config: Server configuration dictionary\n model: Model name being served\n port: Port number the server is listening on\n process: Subprocess or external process reference\n log_file: File handle for server logs\n log_queue: Thread-safe queue for log lines\n log_thread: Background thread for log monitoring\n start_time: Timestamp when server was started\n log_path: Path to the server's log file\n \"\"\"\n\n def __init__(self, config: Dict[str, Any]) -> None:\n \"\"\"\n Initialize a vLLM server instance.\n\n Sets up the server configuration, logging infrastructure, and\n prepares the instance for server lifecycle management.\n\n Args:\n config: Server configuration dictionary containing model name,\n port, and other vLLM-specific parameters\n \"\"\"\n self.config: Dict[str, Any] = config\n\n # Extract model name - handle both string and dict (LoRA config) formats\n model_config = config.get(\"model\", \"unknown\")\n if isinstance(model_config, dict):\n # LoRA configuration - extract base model name\n self.model: str = model_config.get(\"model\", \"unknown\")\n else:\n # Regular string model name\n self.model: str = model_config\n\n self.port: int = config.get(\"port\", 8000)\n self.process: Optional[Union[subprocess.Popen, Any]] = None\n self.log_file: Optional[TextIO] = None\n self.log_queue: Queue[str] = Queue()\n self.log_thread: Optional[Thread] = None\n self.start_time: Optional[datetime] = None\n self.log_path: Path\n self._recent_logs: List[str] = []\n\n # Setup logging\n log_dir = Path.home() / \".vllm-cli\" / \"logs\"\n log_dir.mkdir(parents=True, exist_ok=True)\n\n timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n self.log_path = log_dir / f\"vllm_{self.model.replace('/', '_')}_{timestamp}.log\"\n\n def start(self) -> bool:\n \"\"\"\n Start the vLLM server.\n\n Returns:\n True if server started successfully, False otherwise\n \"\"\"\n if self.is_running():\n logger.warning(f\"Server already running for {self.model}\")\n return False\n\n try:\n # Build command - run directly without conda wrapper\n full_cmd = self._build_command()\n\n logger.info(f\"Starting vLLM server with command: {' '.join(full_cmd)}\")\n\n # Open log file for writing\n self.log_file = open(self.log_path, \"w\", buffering=1)\n\n # Start with parent environment\n env = os.environ.copy()\n # Note: No longer forcing PYTHONUNBUFFERED=1, let user control it\n\n # Layer 1: Apply universal environment variables from settings\n config_manager = ConfigManager()\n universal_env = config_manager.config.get(\"universal_environment\", {})\n if universal_env:\n logger.info(\n f\"Applying {len(universal_env)} universal environment variable(s)\"\n )\n for key, value in universal_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting universal {key}={value}\")\n else:\n logger.debug(f\"Setting universal {key}=\")\n\n # Layer 2: Apply profile environment variables (override universal)\n profile_env = self.config.get(\"profile_environment\", {})\n if profile_env:\n logger.info(\n f\"Applying {len(profile_env)} profile environment variable(s)\"\n )\n for key, value in profile_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting profile {key}={value}\")\n else:\n logger.debug(f\"Setting profile {key}=\")\n\n # Handle GPU device selection via CUDA_VISIBLE_DEVICES\n # This overrides any CUDA_VISIBLE_DEVICES from the profile\n if self.config.get(\"device\"):\n device_str = str(self.config[\"device\"])\n env[\"CUDA_VISIBLE_DEVICES\"] = device_str\n logger.info(f\"Setting CUDA_VISIBLE_DEVICES={device_str}\")\n\n # If using specific GPUs, adjust tensor parallel size if needed\n device_list = [d.strip() for d in device_str.split(\",\")]\n num_devices = len(device_list)\n\n # Check if tensor_parallel_size is set and compatible\n if self.config.get(\"tensor_parallel_size\"):\n tp_size = self.config[\"tensor_parallel_size\"]\n if tp_size > num_devices:\n logger.warning(\n f\"tensor_parallel_size ({tp_size}) > number of selected devices ({num_devices}). \"\n f\"Adjusting tensor_parallel_size to {num_devices}\"\n )\n self.config[\"tensor_parallel_size\"] = num_devices\n elif num_devices % tp_size != 0:\n logger.warning(\n f\"Number of GPUs ({num_devices}) is not evenly divisible by \"\n f\"tensor_parallel_size ({tp_size}). This may lead to inefficient GPU utilization. \"\n f\"Consider using tensor_parallel_size of: \"\n f\"{', '.join(str(i) for i in range(1, num_devices + 1) if num_devices % i == 0)}\"\n )\n\n # Add HuggingFace token if configured\n config_manager = ConfigManager()\n hf_token = config_manager.config.get(\"hf_token\")\n if hf_token:\n env[\"HF_TOKEN\"] = hf_token\n env[\"HUGGING_FACE_HUB_TOKEN\"] = hf_token # Some tools use this variant\n logger.info(\"HuggingFace token configured for server\")\n\n # Enable development mode for sleep endpoints if sleep mode is enabled\n if self.config.get(\"enable_sleep_mode\"):\n env[\"VLLM_SERVER_DEV_MODE\"] = \"1\"\n logger.info(\"Sleep mode enabled with development endpoints\")\n\n # Start the process with proper pipe configuration\n # Use start_new_session=True to create a new process group\n # This prevents the child process from receiving Ctrl+C signals\n self.process = subprocess.Popen(\n full_cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n text=True,\n bufsize=0, # Unbuffered\n universal_newlines=True,\n env=env,\n start_new_session=True, # Create new process group to isolate from parent signals\n )\n\n # Start log monitoring thread\n self._start_log_monitor()\n\n # Set start time and add to registry\n self.start_time = datetime.now()\n from .process import add_server\n\n add_server(self)\n\n # Return immediately - let the UI monitor the startup\n logger.info(\n f\"vLLM server process launched for {self.model} on port {self.port}\"\n )\n return True\n\n except Exception as e:\n logger.error(f\"Error starting vLLM server: {e}\")\n return False\n\n def _build_command(self) -> List[str]:\n \"\"\"\n Build the vLLM command from configuration using the schema.\n\n Returns:\n List of command arguments\n \"\"\"\n # Use the new ConfigManager to build CLI args\n config_manager = ConfigManager()\n\n # Start with the vllm command\n cmd = [\"vllm\"]\n\n # Add the arguments built from schema\n cli_args = config_manager.build_cli_args(self.config)\n cmd.extend(cli_args)\n\n # Handle extra_args if present (backward compatibility)\n if self.config.get(\"extra_args\"):\n self._add_extra_args_to_command(cmd)\n\n logger.debug(f\"Built command: {' '.join(cmd)}\")\n return cmd\n\n def _add_extra_args_to_command(self, cmd: List[str]) -> None:\n \"\"\"\n Add extra arguments to the vLLM command.\n\n Args:\n cmd: Command list to extend with extra arguments\n \"\"\"\n try:\n extra_args = shlex.split(self.config[\"extra_args\"])\n if extra_args:\n logger.info(f\"Adding extra arguments: {extra_args}\")\n cmd.extend(extra_args)\n except ValueError as e:\n logger.warning(f\"Failed to parse extra_args: {e}\")\n\n def _start_log_monitor(self) -> None:\n \"\"\"\n Start a thread to monitor log output from the vLLM server process.\n\n Creates a daemon thread that continuously reads stdout/stderr from\n the server process, writes to log files, and queues log lines for\n real-time display in the UI.\n \"\"\"\n self.log_thread = Thread(target=self._log_monitor_worker, daemon=True)\n self.log_thread.start()\n\n def _log_monitor_worker(self) -> None:\n \"\"\"\n Worker function for log monitoring thread.\n\n Continuously reads log output from the server process and handles\n file writing and queue management for UI display.\n \"\"\"\n try:\n self.log_queue.put(\"Starting vLLM server process...\")\n\n while self._should_continue_monitoring():\n if self._process_log_line():\n continue\n else:\n # No line read, check if process still running\n if self.process and self.process.poll() is not None:\n break\n time.sleep(0.01) # Small sleep to prevent busy waiting\n\n except Exception as e:\n logger.error(f\"Error in log monitor: {e}\")\n self.log_queue.put(f\"Log monitoring error: {e}\")\n\n def _should_continue_monitoring(self) -> bool:\n \"\"\"\n Check if log monitoring should continue.\n\n Returns:\n True if monitoring should continue, False otherwise\n \"\"\"\n return (\n self.is_running()\n and self.process\n and hasattr(self.process, \"stdout\")\n and self.process.stdout\n )\n\n def _process_log_line(self) -> bool:\n \"\"\"\n Process a single log line from the server output.\n\n Reads one line from the process stdout, writes it to the log file,\n and adds it to the queue for UI display after filtering and formatting.\n\n Returns:\n True if a line was processed, False if no line was available\n \"\"\"\n if not (self.process and self.process.stdout):\n return False\n\n line = self.process.stdout.readline()\n if not line:\n return False\n\n # Write to log file\n self._write_to_log_file(line)\n\n # Process for UI display\n line_stripped = line.strip()\n if line_stripped and self._should_display_log_line(line_stripped):\n # Truncate overly long lines\n if len(line_stripped) > 200:\n line_stripped = line_stripped[:197] + \"...\"\n\n self.log_queue.put(line_stripped)\n logger.debug(f\"Log captured: {line_stripped[:50]}...\")\n\n return True\n\n def _write_to_log_file(self, line: str) -> None:\n \"\"\"\n Write a log line to the log file.\n\n Args:\n line: Log line to write\n \"\"\"\n if self.log_file and not self.log_file.closed:\n self.log_file.write(line)\n self.log_file.flush()\n\n def _should_display_log_line(self, line: str) -> bool:\n \"\"\"\n Determine if a log line should be displayed in the UI.\n\n Filters out certain system messages that are not useful for users.\n\n Args:\n line: Stripped log line to check\n\n Returns:\n True if the line should be displayed, False otherwise\n \"\"\"\n # Filter out conda activation and system messages\n filtered_messages = [\n \"Activated CUDA\",\n \"Using nvcc from:\",\n \"Cuda compilation tools\",\n ]\n return not any(skip in line for skip in filtered_messages)\n\n def stop(self) -> bool:\n \"\"\"\n Stop the vLLM server.\n\n Returns:\n True if server stopped successfully, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n try:\n # Check if this is an external server\n if hasattr(self.process, \"terminate\"):\n # Normal subprocess\n # Since we created a new session, we need to terminate the entire process group\n try:\n # Get the process group ID (pgid)\n # Since we used start_new_session=True, the pgid is the same as the pid\n pgid = self.process.pid\n\n # Send SIGTERM to the entire process group for graceful shutdown\n logger.info(f\"Sending SIGTERM to process group {pgid}\")\n os.killpg(pgid, signal.SIGTERM)\n\n # Wait for process to terminate\n try:\n self.process.wait(timeout=10)\n logger.info(f\"Process group {pgid} terminated gracefully\")\n except subprocess.TimeoutExpired:\n # Force kill if not terminated\n logger.warning(\n f\"Process group {pgid} did not terminate, sending SIGKILL\"\n )\n os.killpg(pgid, signal.SIGKILL)\n self.process.wait()\n logger.info(f\"Process group {pgid} force killed\")\n\n except ProcessLookupError:\n # Process already dead\n logger.info(\"Process already terminated\")\n except PermissionError as e:\n # Fall back to terminating just the process\n logger.warning(\n f\"Permission denied for process group kill: {e}, falling back to process termination\"\n )\n self.process.terminate()\n try:\n self.process.wait(timeout=10)\n except subprocess.TimeoutExpired:\n self.process.kill()\n self.process.wait()\n elif hasattr(self.process, \"pid\"):\n # External server - kill entire process group or individual process\n try:\n pgid = self.process.pid\n killed = False\n\n # First attempt: try to kill process group\n try:\n os.killpg(pgid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process group {pgid}\")\n killed = True\n except (OSError, ProcessLookupError) as e:\n # Process group kill failed, try individual process\n logger.debug(\n f\"Process group kill failed: {e}, trying individual process\"\n )\n try:\n # Ensure pid is an integer (handle Mock objects)\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process {self.process.pid}\")\n killed = True\n except ProcessLookupError:\n # Process already dead\n logger.info(\n f\"Process {self.process.pid} already terminated\"\n )\n except OSError as e:\n logger.warning(\n f\"Failed to send SIGTERM to {self.process.pid}: {e}\"\n )\n\n if killed:\n # Wait for graceful shutdown\n time.sleep(2)\n\n # Check if still running and force kill if needed\n if self.is_running():\n try:\n os.killpg(pgid, signal.SIGKILL)\n logger.info(f\"Force killed process group {pgid}\")\n except (OSError, ProcessLookupError):\n # Process group kill failed, try individual\n try:\n # Ensure pid is an integer (handle Mock objects in tests)\n if hasattr(self.process, \"pid\"):\n try:\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGKILL)\n logger.info(f\"Force killed process {pid}\")\n except (TypeError, ValueError):\n # PID is not a valid integer (might be Mock)\n pass\n except ProcessLookupError:\n pass # Already dead\n except OSError as e:\n logger.error(\n f\"Failed to force kill {self.process.pid}: {e}\"\n )\n\n except Exception as e:\n logger.error(f\"Unexpected error stopping external server: {e}\")\n\n # Close log file if we have one\n if hasattr(self, \"log_file\") and self.log_file:\n self.log_file.close()\n\n # Remove from registry\n from .process import remove_server\n\n remove_server(self)\n\n logger.info(f\"vLLM server stopped for {self.model}\")\n return True\n\n except Exception as e:\n logger.error(f\"Error stopping vLLM server: {e}\")\n return False\n\n def is_running(self) -> bool:\n \"\"\"\n Check if the server is running.\n\n Returns:\n True if server is running, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n # Check if this is an external server (detected, not started by us)\n if hasattr(self.process, \"poll\"):\n # Normal subprocess\n return self.process.poll() is None\n elif hasattr(self.process, \"pid\"):\n # External server - check if PID still exists\n try:\n import psutil\n\n return psutil.pid_exists(self.process.pid)\n except ImportError:\n # Fallback to os method\n try:\n os.kill(self.process.pid, 0)\n return True\n except (OSError, ProcessLookupError):\n return False\n\n return False\n\n def get_status(self) -> Dict[str, Any]:\n \"\"\"\n Get server status information.\n\n Returns:\n Dictionary with status information\n \"\"\"\n status = {\n \"model\": self.model,\n \"port\": self.port,\n \"running\": self.is_running(),\n \"pid\": self.process.pid if self.process else None,\n \"start_time\": self.start_time.isoformat() if self.start_time else None,\n \"log_path\": str(self.log_path) if self.log_path else None,\n }\n\n if self.is_running() and self.start_time:\n uptime = datetime.now() - self.start_time\n status[\"uptime_seconds\"] = uptime.total_seconds()\n status[\"uptime_str\"] = str(uptime).split(\".\")[0]\n\n return status\n\n def wait_for_startup(self) -> bool:\n \"\"\"\n Wait for the server to complete startup.\n\n Monitors the server logs for startup completion indicators and verifies\n via HTTP endpoint. Will wait indefinitely until either startup completes\n or the process terminates.\n\n Returns:\n True if server started successfully, False if process terminated\n \"\"\"\n import time\n\n logger.info(f\"Waiting for {self.model} server to complete startup...\")\n\n # Track if we've seen startup indicators in logs\n log_indicates_ready = False\n\n while True:\n # Check if server is still running\n if not self.is_running():\n logger.error(\n f\"Server process for {self.model} terminated during startup\"\n )\n return False\n\n # Get recent logs to check for startup completion\n recent_logs = self.get_recent_logs(50)\n\n if recent_logs and not log_indicates_ready:\n # Check for startup completion indicators\n for log in recent_logs:\n log_lower = log.lower()\n # Look for the explicit \"Application startup complete\" message\n if \"application startup complete\" in log_lower:\n logger.debug(f\"Server {self.model} startup detected in logs\")\n log_indicates_ready = True\n break\n\n # Also check for other ready indicators as fallback\n if any(\n indicator in log_lower\n for indicator in [\n \"uvicorn running on\",\n \"started server process\",\n \"server is ready\",\n \"api server started\",\n ]\n ):\n logger.debug(\n f\"Server {self.model} startup detected via ready indicator\"\n )\n log_indicates_ready = True\n break\n\n # If logs indicate ready, verify via HTTP\n if log_indicates_ready:\n # Try to verify server is actually ready via HTTP\n port = self.config.get(\"port\")\n if port:\n try:\n import httpx\n\n with httpx.Client() as client:\n # Try /v1/models endpoint first (most reliable)\n response = client.get(\n f\"http://localhost:{port}/v1/models\", timeout=5.0\n )\n if response.status_code == 200:\n logger.info(\n f\"Server {self.model} startup complete \"\n \"(verified via HTTP)\"\n )\n return True\n except httpx.ConnectError:\n # Server not ready yet, continue waiting\n logger.debug(\n f\"Server {self.model} not accepting connections yet\"\n )\n except Exception as e:\n # Log but continue, might be network issue\n logger.debug(f\"HTTP verification failed: {e}\")\n else:\n # No port configured, trust the logs\n logger.info(\n f\"Server {self.model} startup complete (no port for verification)\"\n )\n return True\n\n # Small sleep to avoid busy waiting\n time.sleep(0.5)\n\n def get_recent_logs(self, n: int = 20) -> List[str]:\n \"\"\"\n Get recent log lines from the server output.\n\n Retrieves the most recent log lines from either the in-memory queue\n or the log file on disk. This method ensures logs are available even\n after the monitoring thread has processed them.\n\n Args:\n n: Number of recent lines to return (default: 20)\n\n Returns:\n List of recent log lines, with the most recent last\n \"\"\"\n # Update recent logs from queue\n self._update_recent_logs_from_queue()\n\n # Return from memory if available\n if self._recent_logs:\n return self._recent_logs[-n:]\n\n # Fallback to reading from file\n return self._read_logs_from_file(n)\n\n def _update_recent_logs_from_queue(self) -> None:\n \"\"\"\n Update the recent logs cache from the log queue.\n\n Drains all available log lines from the queue and adds them\n to the recent logs cache, maintaining a maximum of 100 lines.\n \"\"\"\n temp_logs = []\n\n # Get all available logs from queue (don't block)\n while not self.log_queue.empty():\n try:\n log_line = self.log_queue.get_nowait()\n temp_logs.append(log_line)\n except Empty:\n break\n\n if temp_logs:\n self._recent_logs.extend(temp_logs)\n # Keep only the last 100 logs in memory to prevent unbounded growth\n self._recent_logs = self._recent_logs[-100:]\n\n def _read_logs_from_file(self, n: int) -> List[str]:\n \"\"\"\n Read recent log lines from the log file.\n\n Args:\n n: Number of lines to read\n\n Returns:\n List of log lines from file\n \"\"\"\n if not (self.log_path and self.log_path.exists()):\n return []\n\n try:\n with open(self.log_path, \"r\") as f:\n file_logs = f.readlines()\n if file_logs:\n # Get last n lines, strip them\n logs = [line.strip() for line in file_logs[-n:]]\n # Update recent logs cache\n self._recent_logs = logs[-100:]\n return logs\n except Exception as e:\n logger.debug(f\"Error reading log file: {e}\")\n\n return []\n\n def restart(self) -> bool:\n \"\"\"\n Restart the server with the same configuration.\n\n Returns:\n True if restart successful, False otherwise\n \"\"\"\n logger.info(f\"Restarting vLLM server for {self.model}\")\n\n # Stop if running\n if self.is_running():\n self.stop()\n time.sleep(2) # Wait a bit before restarting\n\n # Start again\n return self.start()\n\n def health_check(self) -> bool:\n \"\"\"\n Perform a health check on the server.\n\n Returns:\n True if server is healthy, False otherwise\n \"\"\"\n if not self.is_running():\n return False\n\n try:\n import requests\n\n # Try to connect to the server\n response = requests.get(f\"http://localhost:{self.port}/health\", timeout=5)\n\n return response.status_code == 200\n\n except Exception:\n # If requests fails, just check process\n return self.is_running()", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 27979}, "tests/proxy/test_manager.py::276": {"resolved_imports": ["src/vllm_cli/proxy/manager.py", "src/vllm_cli/proxy/models.py"], "used_names": ["MagicMock", "patch"], "enclosing_function": "test_start_all_models_no_wait_some_disabled", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_cli_parser.py::48": {"resolved_imports": ["src/vllm_cli/cli/parser.py"], "used_names": ["create_parser"], "enclosing_function": "test_serve_command_with_port", "extracted_code": "# Source: src/vllm_cli/cli/parser.py\ndef create_parser() -> argparse.ArgumentParser:\n \"\"\"\n Create the main argument parser for vLLM CLI.\n\n Sets up the main parser with all subcommands and their arguments.\n\n Returns:\n Configured ArgumentParser instance\n \"\"\"\n parser = argparse.ArgumentParser(\n prog=\"vllm-cli\",\n description=\"vLLM CLI - Convenient LLM serving tool\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"Examples:\n vllm-cli # Interactive mode\n vllm-cli serve MODEL --profile standard # Serve with profile\n vllm-cli serve MODEL --quantization awq # Serve with AWQ quantization\n vllm-cli serve MODEL --extra-args \"--seed 42\" # With custom vLLM args\n vllm-cli info # System information\n vllm-cli models # List available models\n vllm-cli status # Show active servers\"\"\",\n )\n\n # Global options\n from .. import __version__\n\n parser.add_argument(\n \"--version\", action=\"version\", version=f\"vLLM CLI {__version__}\"\n )\n\n # Create subparsers for commands\n subparsers = parser.add_subparsers(\n dest=\"command\",\n help=\"Available commands\",\n metavar=\"{serve,proxy,info,models,shortcuts,status,stop,dirs}\",\n )\n\n # Add individual command parsers\n _add_serve_parser(subparsers)\n _add_proxy_parser(subparsers)\n _add_info_parser(subparsers)\n _add_models_parser(subparsers)\n _add_shortcuts_parser(subparsers)\n _add_status_parser(subparsers)\n _add_stop_parser(subparsers)\n _add_dirs_parser(subparsers)\n\n return parser", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1705}, "tests/proxy/test_server.py::101": {"resolved_imports": ["src/vllm_cli/proxy/models.py", "src/vllm_cli/proxy/registry.py", "src/vllm_cli/proxy/server.py"], "used_names": [], "enclosing_function": "test_list_models_with_backends", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/proxy/test_models.py::291": {"resolved_imports": ["src/vllm_cli/proxy/models.py"], "used_names": ["ModelStatus", "ProxyStatus"], "enclosing_function": "test_proxy_status_serialization", "extracted_code": "# Source: src/vllm_cli/proxy/models.py\nclass ModelStatus(BaseModel):\n \"\"\"Status information for a model.\"\"\"\n\n name: str\n model_path: str\n port: int\n gpu_ids: List[int]\n status: str # \"running\", \"starting\", \"stopped\", \"error\"\n registration_status: Optional[str] = None # \"pending\", \"available\", \"error\"\n uptime: Optional[float] = None\n error_message: Optional[str] = None\n request_count: int = 0\n last_request_time: Optional[str] = None\n\nclass ProxyStatus(BaseModel):\n \"\"\"Overall proxy server status.\"\"\"\n\n proxy_running: bool\n proxy_port: int\n proxy_host: str\n models: List[ModelStatus]\n total_requests: int = 0\n start_time: Optional[str] = None", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 700}, "tests/test_validation_simple.py::28": {"resolved_imports": ["src/vllm_cli/validation/base.py", "src/vllm_cli/validation/registry.py", "src/vllm_cli/validation/types.py"], "used_names": ["BooleanValidator", "ChoiceValidator", "FloatValidator", "IntegerValidator", "StringValidator"], "enclosing_function": "test_validators_exist", "extracted_code": "# Source: src/vllm_cli/validation/types.py\nclass IntegerValidator(BaseValidator):\n \"\"\"\n Validates integer values with optional range constraints.\n\n Supports minimum/maximum bounds and provides clear error messages\n for out-of-range values and type mismatches.\n \"\"\"\n\n def __init__(\n self,\n field_name: str,\n min_value: Optional[int] = None,\n max_value: Optional[int] = None,\n **kwargs,\n ):\n super().__init__(field_name, **kwargs)\n self.min_value = min_value\n self.max_value = max_value\n\n def validate(self, value: Any) -> ValidationResult:\n \"\"\"Validate integer value and range constraints.\"\"\"\n result = ValidationResult()\n\n if value is None:\n if self.required:\n result.add_error(\n self._create_error(value, \"is required\", \"REQUIRED_ERROR\")\n )\n return result\n\n # Type checking with conversion attempt\n if isinstance(value, bool):\n # Booleans are technically int subclass in Python, but reject them\n result.add_error(\n self._create_error(\n value, \"must be an integer, not boolean\", \"TYPE_ERROR\"\n )\n )\n return result\n\n if not isinstance(value, int):\n # Try to convert string to int\n if isinstance(value, str) and value.strip().isdigit():\n try:\n value = int(value.strip())\n except ValueError:\n result.add_error(\n self._create_error(value, \"must be an integer\", \"TYPE_ERROR\")\n )\n return result\n else:\n result.add_error(\n self._create_error(value, \"must be an integer\", \"TYPE_ERROR\")\n )\n return result\n\n # Range validation\n if self.min_value is not None and value < self.min_value:\n result.add_error(\n self._create_error(value, f\"must be >= {self.min_value}\", \"RANGE_ERROR\")\n )\n\n if self.max_value is not None and value > self.max_value:\n result.add_error(\n self._create_error(value, f\"must be <= {self.max_value}\", \"RANGE_ERROR\")\n )\n\n return result\n\nclass FloatValidator(BaseValidator):\n \"\"\"\n Validates floating-point values with optional range constraints.\n\n Handles both float and int inputs, with customizable precision\n and range validation.\n \"\"\"\n\n def __init__(\n self,\n field_name: str,\n min_value: Optional[float] = None,\n max_value: Optional[float] = None,\n **kwargs,\n ):\n super().__init__(field_name, **kwargs)\n self.min_value = min_value\n self.max_value = max_value\n\n def validate(self, value: Any) -> ValidationResult:\n \"\"\"Validate float value and range constraints.\"\"\"\n result = ValidationResult()\n\n if value is None:\n if self.required:\n result.add_error(\n self._create_error(value, \"is required\", \"REQUIRED_ERROR\")\n )\n return result\n\n # Type checking with conversion\n if isinstance(value, bool):\n result.add_error(\n self._create_error(value, \"must be a number, not boolean\", \"TYPE_ERROR\")\n )\n return result\n\n if not isinstance(value, (int, float)):\n # Try to convert string to float\n if isinstance(value, str):\n try:\n value = float(value.strip())\n except ValueError:\n result.add_error(\n self._create_error(value, \"must be a number\", \"TYPE_ERROR\")\n )\n return result\n else:\n result.add_error(\n self._create_error(value, \"must be a number\", \"TYPE_ERROR\")\n )\n return result\n\n # Convert to float for consistent comparison\n float_value = float(value)\n\n # Range validation\n if self.min_value is not None and float_value < self.min_value:\n result.add_error(\n self._create_error(value, f\"must be >= {self.min_value}\", \"RANGE_ERROR\")\n )\n\n if self.max_value is not None and float_value > self.max_value:\n result.add_error(\n self._create_error(value, f\"must be <= {self.max_value}\", \"RANGE_ERROR\")\n )\n\n return result\n\nclass StringValidator(BaseValidator):\n \"\"\"\n Validates string values with length and pattern constraints.\n\n Supports minimum/maximum length validation and regex pattern matching\n for complex string validation requirements.\n \"\"\"\n\n def __init__(\n self,\n field_name: str,\n min_length: Optional[int] = None,\n max_length: Optional[int] = None,\n pattern: Optional[Union[str, Pattern]] = None,\n **kwargs,\n ):\n super().__init__(field_name, **kwargs)\n self.min_length = min_length\n self.max_length = max_length\n\n # Compile pattern if provided as string\n if isinstance(pattern, str):\n self.pattern = re.compile(pattern)\n else:\n self.pattern = pattern\n\n def validate(self, value: Any) -> ValidationResult:\n \"\"\"Validate string value, length, and pattern constraints.\"\"\"\n result = ValidationResult()\n\n if value is None:\n if self.required:\n result.add_error(\n self._create_error(value, \"is required\", \"REQUIRED_ERROR\")\n )\n return result\n\n # Convert to string if not already\n if not isinstance(value, str):\n value = str(value)\n\n # Length validation\n if self.min_length is not None and len(value) < self.min_length:\n result.add_error(\n self._create_error(\n value,\n f\"must be at least {self.min_length} characters long\",\n \"LENGTH_ERROR\",\n )\n )\n\n if self.max_length is not None and len(value) > self.max_length:\n result.add_error(\n self._create_error(\n value,\n f\"must be at most {self.max_length} characters long\",\n \"LENGTH_ERROR\",\n )\n )\n\n # Pattern validation\n if self.pattern and not self.pattern.match(value):\n result.add_error(\n self._create_error(\n value, \"does not match required pattern\", \"PATTERN_ERROR\"\n )\n )\n\n return result\n\nclass BooleanValidator(BaseValidator):\n \"\"\"\n Validates boolean values with flexible input acceptance.\n\n Accepts actual booleans, common string representations,\n and numeric equivalents (0/1).\n \"\"\"\n\n def validate(self, value: Any) -> ValidationResult:\n \"\"\"Validate boolean value with flexible input handling.\"\"\"\n result = ValidationResult()\n\n if value is None:\n if self.required:\n result.add_error(\n self._create_error(value, \"is required\", \"REQUIRED_ERROR\")\n )\n return result\n\n # Accept actual booleans\n if isinstance(value, bool):\n return result\n\n # Accept string representations\n if isinstance(value, str):\n lower_value = value.lower().strip()\n if lower_value in (\"true\", \"yes\", \"1\", \"on\", \"enabled\"):\n return result\n elif lower_value in (\"false\", \"no\", \"0\", \"of\", \"disabled\"):\n return result\n else:\n result.add_error(\n self._create_error(\n value,\n \"must be true/false, yes/no, 1/0, or on/of\",\n \"TYPE_ERROR\",\n )\n )\n return result\n\n # Accept numeric 0/1\n if isinstance(value, int) and value in (0, 1):\n return result\n\n result.add_error(\n self._create_error(value, \"must be a boolean value\", \"TYPE_ERROR\")\n )\n return result\n\nclass ChoiceValidator(BaseValidator):\n \"\"\"\n Validates that a value is one of a predefined set of choices.\n\n Supports case-insensitive matching and provides helpful error\n messages listing valid options.\n \"\"\"\n\n def __init__(\n self, field_name: str, choices: List[Any], case_sensitive: bool = True, **kwargs\n ):\n super().__init__(field_name, **kwargs)\n self.choices = choices\n self.case_sensitive = case_sensitive\n\n # Create normalized choices for case-insensitive comparison\n if not case_sensitive:\n self.normalized_choices = [\n str(choice).lower() if choice is not None else None\n for choice in choices\n ]\n\n def validate(self, value: Any) -> ValidationResult:\n \"\"\"Validate that value is in the allowed choices.\"\"\"\n result = ValidationResult()\n\n if value is None:\n if self.required:\n result.add_error(\n self._create_error(value, \"is required\", \"REQUIRED_ERROR\")\n )\n return result\n\n # Check if value is in choices\n if self.case_sensitive:\n if value in self.choices:\n return result\n else:\n # Case-insensitive comparison\n normalized_value = str(value).lower()\n if normalized_value in self.normalized_choices:\n return result\n\n # Format choices for error message\n choices_str = \", \".join(str(choice) for choice in self.choices)\n result.add_error(\n self._create_error(value, f\"must be one of: {choices_str}\", \"CHOICE_ERROR\")\n )\n\n return result", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 10047}, "tests/proxy/test_router.py::26": {"resolved_imports": ["src/vllm_cli/proxy/router.py"], "used_names": [], "enclosing_function": "test_add_backend", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_config_manager.py::101": {"resolved_imports": ["src/vllm_cli/config/manager.py"], "used_names": ["ConfigManager", "patch", "yaml"], "enclosing_function": "test_get_last_config", "extracted_code": "# Source: src/vllm_cli/config/manager.py\nclass ConfigManager:\n \"\"\"\n Enhanced configuration manager with comprehensive validation support.\n\n This class manages configuration files, profiles, and validation using\n the new validation framework. It provides a clean API for configuration\n operations while ensuring data integrity through comprehensive validation.\n\n Attributes:\n config_dir: Directory for configuration files\n validation_registry: Registry of validation rules\n compatibility_validator: Validator for parameter combinations\n \"\"\"\n\n def __init__(self):\n # Paths for configuration files\n self.config_dir = Path.home() / \".config\" / \"vllm-cli\"\n self.config_file = self.config_dir / \"config.yaml\"\n\n # Ensure config directory exists\n self.config_dir.mkdir(parents=True, exist_ok=True)\n\n # Initialize sub-managers\n self.schema_manager = SchemaManager()\n self.profile_manager = ProfileManager(self.config_dir)\n self.persistence_manager = PersistenceManager()\n self.shortcut_manager = ShortcutManager(self.config_dir)\n\n # Initialize validation system\n self.validation_registry = create_vllm_validation_registry()\n self.compatibility_validator = create_compatibility_validator(\n self.validation_registry\n )\n\n # Load main configuration\n self.config = self._load_config()\n\n def _load_config(self) -> Dict[str, Any]:\n \"\"\"Load main configuration file (legacy YAML support).\"\"\"\n return self.persistence_manager.load_yaml_file(self.config_file)\n\n def _save_config(self) -> None:\n \"\"\"Save main configuration file.\"\"\"\n self.persistence_manager.save_yaml_file(self.config_file, self.config)\n\n def get_argument_info(self, arg_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get detailed information about a specific argument.\"\"\"\n return self.schema_manager.get_argument_info(arg_name)\n\n def get_arguments_by_category(self, category: str) -> List[Dict[str, Any]]:\n \"\"\"Get all arguments belonging to a specific category.\"\"\"\n return self.schema_manager.get_arguments_by_category(category)\n\n def get_category_info(self, category: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get information about a specific category.\"\"\"\n return self.schema_manager.get_category_info(category)\n\n def get_ordered_categories(self) -> List[Tuple[str, Dict[str, Any]]]:\n \"\"\"Get categories ordered by their display order.\"\"\"\n return self.schema_manager.get_ordered_categories()\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n return self.profile_manager.get_all_profiles()\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name with dynamic defaults applied.\"\"\"\n profile = self.profile_manager.get_profile(name)\n if profile and \"config\" in profile:\n # Apply dynamic defaults to the profile configuration\n profile[\"config\"] = self.profile_manager.apply_dynamic_defaults(\n profile[\"config\"]\n )\n return profile\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"Save or update a user profile with validation.\"\"\"\n # Validate profile configuration if present\n if \"config\" in profile:\n is_valid, errors = self.validate_config(profile[\"config\"])\n if not is_valid:\n from ..errors import ProfileError\n\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n return self.profile_manager.save_user_profile(name, profile)\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n return self.profile_manager.delete_user_profile(name)\n\n @property\n def default_profiles(self) -> Dict[str, Any]:\n \"\"\"Get default profiles.\"\"\"\n return self.profile_manager.default_profiles\n\n @property\n def user_profiles(self) -> Dict[str, Any]:\n \"\"\"Get user profiles.\"\"\"\n return self.profile_manager.user_profiles\n\n def validate_config(self, config: Dict[str, Any]) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate a configuration using the new validation framework.\n\n This method uses the comprehensive validation system to check\n configuration values, types, ranges, and dependencies.\n\n Args:\n config: Configuration dictionary to validate\n\n Returns:\n Tuple of (is_valid, list_of_error_messages)\n\n Raises:\n ConfigurationError: If validation system fails\n \"\"\"\n try:\n # Use new validation system\n result = self.validation_registry.validate_config(config)\n\n # Convert validation errors to string messages for backward compatibility\n error_messages = result.get_error_messages()\n\n # Add warnings if any\n if result.warnings:\n for warning in result.warnings:\n logger.warning(f\"Configuration warning: {warning}\")\n\n return result.is_valid(), error_messages\n\n except Exception as e:\n logger.error(f\"Error during configuration validation: {e}\")\n raise ConfigurationError(\n f\"Validation system error: {e}\", error_code=\"VALIDATION_SYSTEM_ERROR\"\n ) from e\n\n def validate_argument_combination(\n self, config: Dict[str, Any]\n ) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate that argument combinations are compatible using the new compatibility validator.\n\n Args:\n config: Configuration dictionary to check for compatibility\n\n Returns:\n Tuple of (is_valid, list_of_warnings_or_errors)\n \"\"\"\n try:\n issues = self.compatibility_validator.validate_compatibility(config)\n\n warnings = []\n errors = []\n\n for issue in issues:\n message = issue[\"message\"]\n if issue[\"severity\"] == \"error\":\n errors.append(message)\n else:\n warnings.append(message)\n\n # Log warnings\n for warning in warnings:\n logger.warning(f\"Configuration compatibility warning: {warning}\")\n\n # Return all issues as warnings for backward compatibility\n # (errors are treated as warnings in the legacy interface)\n all_issues = errors + warnings\n\n return len(errors) == 0, all_issues\n\n except Exception as e:\n logger.error(f\"Error during compatibility validation: {e}\")\n return False, [f\"Compatibility validation error: {e}\"]\n\n def build_cli_args(self, config: Dict[str, Any]) -> List[str]:\n \"\"\"\n Build command-line arguments from a configuration dictionary.\n\n Only includes arguments that are explicitly set in the config.\n Handles special cases like LoRA modules.\n \"\"\"\n args = []\n\n # Special handling for model (positional argument)\n # Check if this is a GGUF/Ollama configuration\n if (\n isinstance(config.get(\"model\"), dict)\n and \"quantization\" in config[\"model\"]\n and config[\"model\"][\"quantization\"] == \"gguf\"\n ):\n # Extract GGUF model config\n gguf_config = config[\"model\"]\n model_path = gguf_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", model_path])\n\n # Set quantization to gguf\n config[\"quantization\"] = \"gguf\"\n\n # Add served-model-name if provided (for Ollama models)\n if \"served_model_name\" in gguf_config:\n config[\"served_model_name\"] = gguf_config[\"served_model_name\"]\n logger.info(\n f\"Configuring GGUF model: {model_path} as {gguf_config['served_model_name']}\"\n )\n else:\n logger.info(f\"Configuring GGUF model: {model_path}\")\n\n # Check if this is a LoRA configuration\n elif (\n isinstance(config.get(\"model\"), dict) and \"lora_modules\" in config[\"model\"]\n ):\n # Extract base model and LoRA config\n lora_config = config[\"model\"]\n base_model = lora_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", base_model])\n\n # Enable LoRA support when modules are present\n args.append(\"--enable-lora\")\n\n # Track maximum rank for all LoRA modules\n max_rank = 16 # Default minimum\n\n # Add LoRA modules\n for lora in lora_config.get(\"lora_modules\", []):\n lora_path = lora.get(\"path\", \"\")\n if lora_path:\n # vLLM expects --lora-modules with name=path format\n lora_name = lora.get(\"name\", \"adapter\")\n args.extend([\"--lora-modules\", f\"{lora_name}={lora_path}\"])\n\n # Track maximum rank\n lora_rank = lora.get(\"rank\", 16)\n max_rank = max(max_rank, lora_rank)\n\n # Add max-lora-rank parameter\n args.extend([\"--max-lora-rank\", str(max_rank)])\n\n elif \"model\" in config:\n args.extend([\"serve\", config[\"model\"]])\n\n # Handle lora_modules if present as a string (from CLI)\n if \"lora_modules\" in config and config[\"lora_modules\"]:\n # Enable LoRA support\n if \"--enable-lora\" not in args:\n args.append(\"--enable-lora\")\n\n # Parse and add LoRA modules\n lora_modules_str = config[\"lora_modules\"]\n if isinstance(lora_modules_str, str):\n # Split by space and add each module\n for module in lora_modules_str.split():\n args.extend([\"--lora-modules\", module])\n\n # Add max-lora-rank if not already added\n # Use a safe default of 64 which should cover most LoRA adapters\n if \"--max-lora-rank\" not in args:\n # Check if max_lora_rank is explicitly set in config\n if \"max_lora_rank\" not in config:\n args.extend([\"--max-lora-rank\", \"64\"])\n\n for arg_name, value in config.items():\n # Skip special keys and None values\n if (\n arg_name in [\"model\", \"name\", \"description\", \"icon\", \"lora_modules\"]\n or value is None\n ):\n continue\n\n arg_info = self.schema_manager.get_argument_info(arg_name)\n if not arg_info:\n logger.warning(f\"Unknown argument in config: {arg_name}\")\n continue\n\n cli_flag = arg_info.get(\"cli_flag\")\n if not cli_flag:\n continue\n\n arg_type = arg_info.get(\"type\")\n\n if arg_type == \"boolean\":\n if value: # Only add flag if True\n args.append(cli_flag)\n elif arg_type in [\"integer\", \"float\", \"string\", \"choice\"]:\n args.extend([cli_flag, str(value)])\n else:\n logger.warning(f\"Unknown argument type for {arg_name}: {arg_type}\")\n\n return args\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n return self.profile_manager.export_profile(profile_name, filepath)\n\n def import_profile(self, filepath: Path, new_name: Optional[str] = None) -> bool:\n \"\"\"Import a profile from a JSON file with comprehensive validation.\"\"\"\n return self.profile_manager.import_profile(\n filepath, new_name, self.validate_config\n )\n\n def get_last_config(self) -> Optional[Dict[str, Any]]:\n \"\"\"Get the last used server configuration.\"\"\"\n return self.config.get(\"last_config\")\n\n def save_last_config(self, config: Dict[str, Any]) -> None:\n \"\"\"Save the last used server configuration.\"\"\"\n self.config[\"last_config\"] = config\n self._save_config()\n\n def get_recent_models(self, limit: int = 5) -> List[str]:\n \"\"\"Get recently used models.\"\"\"\n return self.config.get(\"recent_models\", [])[:limit]\n\n def add_recent_model(self, model: str) -> None:\n \"\"\"Add a model to recent models list.\"\"\"\n recent = self.config.get(\"recent_models\", [])\n if model in recent:\n recent.remove(model)\n recent.insert(0, model)\n self.config[\"recent_models\"] = recent[:10] # Keep only last 10\n self._save_config()\n\n def clear_cache(self) -> None:\n \"\"\"Clear cached data.\"\"\"\n cache_file = self.config_dir / \"cache.json\"\n if cache_file.exists():\n cache_file.unlink()\n self.config.pop(\"last_config\", None)\n self.config.pop(\"recent_models\", None)\n self._save_config()\n logger.info(\"Cache cleared\")\n\n def get_server_defaults(self) -> Dict[str, Any]:\n \"\"\"Get default server settings.\"\"\"\n return self.config.get(\n \"server_defaults\",\n {\n \"default_port\": 8000,\n \"auto_restart\": False,\n \"log_level\": \"info\",\n \"cleanup_on_exit\": True, # Default to cleaning up servers on exit\n },\n )\n\n def save_server_defaults(self, defaults: Dict[str, Any]) -> None:\n \"\"\"Save default server settings.\"\"\"\n self.config[\"server_defaults\"] = defaults\n self._save_config()\n\n def get_ui_preferences(self) -> Dict[str, Any]:\n \"\"\"Get UI preferences including progress bar style and log display settings.\"\"\"\n return self.config.get(\n \"ui_preferences\",\n {\n \"progress_bar_style\": \"blocks\", # Default style\n \"show_gpu_in_monitor\": True,\n \"log_lines_startup\": 50, # Number of log lines to show during startup\n \"log_lines_monitor\": 50, # Number of log lines to show in server monitor\n \"startup_refresh_rate\": 4.0, # Hz for startup log refresh\n \"monitor_refresh_rate\": 1.0, # Hz for monitor log refresh\n },\n )\n\n def save_ui_preferences(self, preferences: Dict[str, Any]) -> None:\n \"\"\"Save UI preferences.\"\"\"\n self.config[\"ui_preferences\"] = preferences\n self._save_config()\n\n # Shortcut management methods\n def get_all_shortcuts(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all shortcuts.\"\"\"\n return self.shortcut_manager.get_all_shortcuts()\n\n def get_shortcut(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific shortcut by name.\"\"\"\n return self.shortcut_manager.get_shortcut(name)\n\n def save_shortcut(self, name: str, shortcut_data: Dict[str, Any]) -> bool:\n \"\"\"Save or update a shortcut.\"\"\"\n return self.shortcut_manager.save_shortcut(name, shortcut_data)\n\n def delete_shortcut(self, name: str) -> bool:\n \"\"\"Delete a shortcut.\"\"\"\n return self.shortcut_manager.delete_shortcut(name)\n\n def list_shortcuts(self) -> List[Dict[str, Any]]:\n \"\"\"List all shortcuts with summary information.\"\"\"\n return self.shortcut_manager.list_shortcuts()\n\n def get_recent_shortcuts(self, limit: int = 5) -> List[Dict[str, Any]]:\n \"\"\"Get recently used shortcuts.\"\"\"\n return self.shortcut_manager.get_recent_shortcuts(limit)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 15704}, "tests/test_config_manager.py::77": {"resolved_imports": ["src/vllm_cli/config/manager.py"], "used_names": ["ConfigManager", "patch", "yaml"], "enclosing_function": "test_save_config", "extracted_code": "# Source: src/vllm_cli/config/manager.py\nclass ConfigManager:\n \"\"\"\n Enhanced configuration manager with comprehensive validation support.\n\n This class manages configuration files, profiles, and validation using\n the new validation framework. It provides a clean API for configuration\n operations while ensuring data integrity through comprehensive validation.\n\n Attributes:\n config_dir: Directory for configuration files\n validation_registry: Registry of validation rules\n compatibility_validator: Validator for parameter combinations\n \"\"\"\n\n def __init__(self):\n # Paths for configuration files\n self.config_dir = Path.home() / \".config\" / \"vllm-cli\"\n self.config_file = self.config_dir / \"config.yaml\"\n\n # Ensure config directory exists\n self.config_dir.mkdir(parents=True, exist_ok=True)\n\n # Initialize sub-managers\n self.schema_manager = SchemaManager()\n self.profile_manager = ProfileManager(self.config_dir)\n self.persistence_manager = PersistenceManager()\n self.shortcut_manager = ShortcutManager(self.config_dir)\n\n # Initialize validation system\n self.validation_registry = create_vllm_validation_registry()\n self.compatibility_validator = create_compatibility_validator(\n self.validation_registry\n )\n\n # Load main configuration\n self.config = self._load_config()\n\n def _load_config(self) -> Dict[str, Any]:\n \"\"\"Load main configuration file (legacy YAML support).\"\"\"\n return self.persistence_manager.load_yaml_file(self.config_file)\n\n def _save_config(self) -> None:\n \"\"\"Save main configuration file.\"\"\"\n self.persistence_manager.save_yaml_file(self.config_file, self.config)\n\n def get_argument_info(self, arg_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get detailed information about a specific argument.\"\"\"\n return self.schema_manager.get_argument_info(arg_name)\n\n def get_arguments_by_category(self, category: str) -> List[Dict[str, Any]]:\n \"\"\"Get all arguments belonging to a specific category.\"\"\"\n return self.schema_manager.get_arguments_by_category(category)\n\n def get_category_info(self, category: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get information about a specific category.\"\"\"\n return self.schema_manager.get_category_info(category)\n\n def get_ordered_categories(self) -> List[Tuple[str, Dict[str, Any]]]:\n \"\"\"Get categories ordered by their display order.\"\"\"\n return self.schema_manager.get_ordered_categories()\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n return self.profile_manager.get_all_profiles()\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name with dynamic defaults applied.\"\"\"\n profile = self.profile_manager.get_profile(name)\n if profile and \"config\" in profile:\n # Apply dynamic defaults to the profile configuration\n profile[\"config\"] = self.profile_manager.apply_dynamic_defaults(\n profile[\"config\"]\n )\n return profile\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"Save or update a user profile with validation.\"\"\"\n # Validate profile configuration if present\n if \"config\" in profile:\n is_valid, errors = self.validate_config(profile[\"config\"])\n if not is_valid:\n from ..errors import ProfileError\n\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n return self.profile_manager.save_user_profile(name, profile)\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n return self.profile_manager.delete_user_profile(name)\n\n @property\n def default_profiles(self) -> Dict[str, Any]:\n \"\"\"Get default profiles.\"\"\"\n return self.profile_manager.default_profiles\n\n @property\n def user_profiles(self) -> Dict[str, Any]:\n \"\"\"Get user profiles.\"\"\"\n return self.profile_manager.user_profiles\n\n def validate_config(self, config: Dict[str, Any]) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate a configuration using the new validation framework.\n\n This method uses the comprehensive validation system to check\n configuration values, types, ranges, and dependencies.\n\n Args:\n config: Configuration dictionary to validate\n\n Returns:\n Tuple of (is_valid, list_of_error_messages)\n\n Raises:\n ConfigurationError: If validation system fails\n \"\"\"\n try:\n # Use new validation system\n result = self.validation_registry.validate_config(config)\n\n # Convert validation errors to string messages for backward compatibility\n error_messages = result.get_error_messages()\n\n # Add warnings if any\n if result.warnings:\n for warning in result.warnings:\n logger.warning(f\"Configuration warning: {warning}\")\n\n return result.is_valid(), error_messages\n\n except Exception as e:\n logger.error(f\"Error during configuration validation: {e}\")\n raise ConfigurationError(\n f\"Validation system error: {e}\", error_code=\"VALIDATION_SYSTEM_ERROR\"\n ) from e\n\n def validate_argument_combination(\n self, config: Dict[str, Any]\n ) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate that argument combinations are compatible using the new compatibility validator.\n\n Args:\n config: Configuration dictionary to check for compatibility\n\n Returns:\n Tuple of (is_valid, list_of_warnings_or_errors)\n \"\"\"\n try:\n issues = self.compatibility_validator.validate_compatibility(config)\n\n warnings = []\n errors = []\n\n for issue in issues:\n message = issue[\"message\"]\n if issue[\"severity\"] == \"error\":\n errors.append(message)\n else:\n warnings.append(message)\n\n # Log warnings\n for warning in warnings:\n logger.warning(f\"Configuration compatibility warning: {warning}\")\n\n # Return all issues as warnings for backward compatibility\n # (errors are treated as warnings in the legacy interface)\n all_issues = errors + warnings\n\n return len(errors) == 0, all_issues\n\n except Exception as e:\n logger.error(f\"Error during compatibility validation: {e}\")\n return False, [f\"Compatibility validation error: {e}\"]\n\n def build_cli_args(self, config: Dict[str, Any]) -> List[str]:\n \"\"\"\n Build command-line arguments from a configuration dictionary.\n\n Only includes arguments that are explicitly set in the config.\n Handles special cases like LoRA modules.\n \"\"\"\n args = []\n\n # Special handling for model (positional argument)\n # Check if this is a GGUF/Ollama configuration\n if (\n isinstance(config.get(\"model\"), dict)\n and \"quantization\" in config[\"model\"]\n and config[\"model\"][\"quantization\"] == \"gguf\"\n ):\n # Extract GGUF model config\n gguf_config = config[\"model\"]\n model_path = gguf_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", model_path])\n\n # Set quantization to gguf\n config[\"quantization\"] = \"gguf\"\n\n # Add served-model-name if provided (for Ollama models)\n if \"served_model_name\" in gguf_config:\n config[\"served_model_name\"] = gguf_config[\"served_model_name\"]\n logger.info(\n f\"Configuring GGUF model: {model_path} as {gguf_config['served_model_name']}\"\n )\n else:\n logger.info(f\"Configuring GGUF model: {model_path}\")\n\n # Check if this is a LoRA configuration\n elif (\n isinstance(config.get(\"model\"), dict) and \"lora_modules\" in config[\"model\"]\n ):\n # Extract base model and LoRA config\n lora_config = config[\"model\"]\n base_model = lora_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", base_model])\n\n # Enable LoRA support when modules are present\n args.append(\"--enable-lora\")\n\n # Track maximum rank for all LoRA modules\n max_rank = 16 # Default minimum\n\n # Add LoRA modules\n for lora in lora_config.get(\"lora_modules\", []):\n lora_path = lora.get(\"path\", \"\")\n if lora_path:\n # vLLM expects --lora-modules with name=path format\n lora_name = lora.get(\"name\", \"adapter\")\n args.extend([\"--lora-modules\", f\"{lora_name}={lora_path}\"])\n\n # Track maximum rank\n lora_rank = lora.get(\"rank\", 16)\n max_rank = max(max_rank, lora_rank)\n\n # Add max-lora-rank parameter\n args.extend([\"--max-lora-rank\", str(max_rank)])\n\n elif \"model\" in config:\n args.extend([\"serve\", config[\"model\"]])\n\n # Handle lora_modules if present as a string (from CLI)\n if \"lora_modules\" in config and config[\"lora_modules\"]:\n # Enable LoRA support\n if \"--enable-lora\" not in args:\n args.append(\"--enable-lora\")\n\n # Parse and add LoRA modules\n lora_modules_str = config[\"lora_modules\"]\n if isinstance(lora_modules_str, str):\n # Split by space and add each module\n for module in lora_modules_str.split():\n args.extend([\"--lora-modules\", module])\n\n # Add max-lora-rank if not already added\n # Use a safe default of 64 which should cover most LoRA adapters\n if \"--max-lora-rank\" not in args:\n # Check if max_lora_rank is explicitly set in config\n if \"max_lora_rank\" not in config:\n args.extend([\"--max-lora-rank\", \"64\"])\n\n for arg_name, value in config.items():\n # Skip special keys and None values\n if (\n arg_name in [\"model\", \"name\", \"description\", \"icon\", \"lora_modules\"]\n or value is None\n ):\n continue\n\n arg_info = self.schema_manager.get_argument_info(arg_name)\n if not arg_info:\n logger.warning(f\"Unknown argument in config: {arg_name}\")\n continue\n\n cli_flag = arg_info.get(\"cli_flag\")\n if not cli_flag:\n continue\n\n arg_type = arg_info.get(\"type\")\n\n if arg_type == \"boolean\":\n if value: # Only add flag if True\n args.append(cli_flag)\n elif arg_type in [\"integer\", \"float\", \"string\", \"choice\"]:\n args.extend([cli_flag, str(value)])\n else:\n logger.warning(f\"Unknown argument type for {arg_name}: {arg_type}\")\n\n return args\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n return self.profile_manager.export_profile(profile_name, filepath)\n\n def import_profile(self, filepath: Path, new_name: Optional[str] = None) -> bool:\n \"\"\"Import a profile from a JSON file with comprehensive validation.\"\"\"\n return self.profile_manager.import_profile(\n filepath, new_name, self.validate_config\n )\n\n def get_last_config(self) -> Optional[Dict[str, Any]]:\n \"\"\"Get the last used server configuration.\"\"\"\n return self.config.get(\"last_config\")\n\n def save_last_config(self, config: Dict[str, Any]) -> None:\n \"\"\"Save the last used server configuration.\"\"\"\n self.config[\"last_config\"] = config\n self._save_config()\n\n def get_recent_models(self, limit: int = 5) -> List[str]:\n \"\"\"Get recently used models.\"\"\"\n return self.config.get(\"recent_models\", [])[:limit]\n\n def add_recent_model(self, model: str) -> None:\n \"\"\"Add a model to recent models list.\"\"\"\n recent = self.config.get(\"recent_models\", [])\n if model in recent:\n recent.remove(model)\n recent.insert(0, model)\n self.config[\"recent_models\"] = recent[:10] # Keep only last 10\n self._save_config()\n\n def clear_cache(self) -> None:\n \"\"\"Clear cached data.\"\"\"\n cache_file = self.config_dir / \"cache.json\"\n if cache_file.exists():\n cache_file.unlink()\n self.config.pop(\"last_config\", None)\n self.config.pop(\"recent_models\", None)\n self._save_config()\n logger.info(\"Cache cleared\")\n\n def get_server_defaults(self) -> Dict[str, Any]:\n \"\"\"Get default server settings.\"\"\"\n return self.config.get(\n \"server_defaults\",\n {\n \"default_port\": 8000,\n \"auto_restart\": False,\n \"log_level\": \"info\",\n \"cleanup_on_exit\": True, # Default to cleaning up servers on exit\n },\n )\n\n def save_server_defaults(self, defaults: Dict[str, Any]) -> None:\n \"\"\"Save default server settings.\"\"\"\n self.config[\"server_defaults\"] = defaults\n self._save_config()\n\n def get_ui_preferences(self) -> Dict[str, Any]:\n \"\"\"Get UI preferences including progress bar style and log display settings.\"\"\"\n return self.config.get(\n \"ui_preferences\",\n {\n \"progress_bar_style\": \"blocks\", # Default style\n \"show_gpu_in_monitor\": True,\n \"log_lines_startup\": 50, # Number of log lines to show during startup\n \"log_lines_monitor\": 50, # Number of log lines to show in server monitor\n \"startup_refresh_rate\": 4.0, # Hz for startup log refresh\n \"monitor_refresh_rate\": 1.0, # Hz for monitor log refresh\n },\n )\n\n def save_ui_preferences(self, preferences: Dict[str, Any]) -> None:\n \"\"\"Save UI preferences.\"\"\"\n self.config[\"ui_preferences\"] = preferences\n self._save_config()\n\n # Shortcut management methods\n def get_all_shortcuts(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all shortcuts.\"\"\"\n return self.shortcut_manager.get_all_shortcuts()\n\n def get_shortcut(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific shortcut by name.\"\"\"\n return self.shortcut_manager.get_shortcut(name)\n\n def save_shortcut(self, name: str, shortcut_data: Dict[str, Any]) -> bool:\n \"\"\"Save or update a shortcut.\"\"\"\n return self.shortcut_manager.save_shortcut(name, shortcut_data)\n\n def delete_shortcut(self, name: str) -> bool:\n \"\"\"Delete a shortcut.\"\"\"\n return self.shortcut_manager.delete_shortcut(name)\n\n def list_shortcuts(self) -> List[Dict[str, Any]]:\n \"\"\"List all shortcuts with summary information.\"\"\"\n return self.shortcut_manager.list_shortcuts()\n\n def get_recent_shortcuts(self, limit: int = 5) -> List[Dict[str, Any]]:\n \"\"\"Get recently used shortcuts.\"\"\"\n return self.shortcut_manager.get_recent_shortcuts(limit)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 15704}, "tests/proxy/test_manager.py::114": {"resolved_imports": ["src/vllm_cli/proxy/manager.py", "src/vllm_cli/proxy/models.py"], "used_names": ["MagicMock"], "enclosing_function": "test_stop_proxy", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_server_manager.py::37": {"resolved_imports": ["src/vllm_cli/server/__init__.py", "src/vllm_cli/server/process.py", "src/vllm_cli/server/manager.py"], "used_names": ["VLLMServer", "process"], "enclosing_function": "test_init", "extracted_code": "# Source: src/vllm_cli/server/__init__.py\n\nThis package provides comprehensive vLLM server management including\nprocess lifecycle, monitoring, discovery, and utilities.\n\nMain Components:\n- VLLMServer: Core server management class\n- Process management: Server registry and lifecycle\n- Discovery: External server detection\n- Monitoring: Health checks and metrics\n- Utils: Port management and cleanup utilities\n\"\"\"\n\n\n\n# Process management functions\nfrom .process import (\n add_server,\n cleanup_servers_on_exit,\n find_server_by_model,\n find_server_by_port,\n get_active_servers,\n remove_server,\n stop_all_servers,\n)\n\n\n\n# Source: src/vllm_cli/server/manager.py\nclass VLLMServer:\n \"\"\"\n Manages a vLLM server instance with comprehensive lifecycle control.\n\n This class handles the complete lifecycle of a vLLM server including\n configuration, process management, logging, monitoring, and cleanup.\n It supports both programmatically started servers and external server\n detection and management.\n\n Attributes:\n config: Server configuration dictionary\n model: Model name being served\n port: Port number the server is listening on\n process: Subprocess or external process reference\n log_file: File handle for server logs\n log_queue: Thread-safe queue for log lines\n log_thread: Background thread for log monitoring\n start_time: Timestamp when server was started\n log_path: Path to the server's log file\n \"\"\"\n\n def __init__(self, config: Dict[str, Any]) -> None:\n \"\"\"\n Initialize a vLLM server instance.\n\n Sets up the server configuration, logging infrastructure, and\n prepares the instance for server lifecycle management.\n\n Args:\n config: Server configuration dictionary containing model name,\n port, and other vLLM-specific parameters\n \"\"\"\n self.config: Dict[str, Any] = config\n\n # Extract model name - handle both string and dict (LoRA config) formats\n model_config = config.get(\"model\", \"unknown\")\n if isinstance(model_config, dict):\n # LoRA configuration - extract base model name\n self.model: str = model_config.get(\"model\", \"unknown\")\n else:\n # Regular string model name\n self.model: str = model_config\n\n self.port: int = config.get(\"port\", 8000)\n self.process: Optional[Union[subprocess.Popen, Any]] = None\n self.log_file: Optional[TextIO] = None\n self.log_queue: Queue[str] = Queue()\n self.log_thread: Optional[Thread] = None\n self.start_time: Optional[datetime] = None\n self.log_path: Path\n self._recent_logs: List[str] = []\n\n # Setup logging\n log_dir = Path.home() / \".vllm-cli\" / \"logs\"\n log_dir.mkdir(parents=True, exist_ok=True)\n\n timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n self.log_path = log_dir / f\"vllm_{self.model.replace('/', '_')}_{timestamp}.log\"\n\n def start(self) -> bool:\n \"\"\"\n Start the vLLM server.\n\n Returns:\n True if server started successfully, False otherwise\n \"\"\"\n if self.is_running():\n logger.warning(f\"Server already running for {self.model}\")\n return False\n\n try:\n # Build command - run directly without conda wrapper\n full_cmd = self._build_command()\n\n logger.info(f\"Starting vLLM server with command: {' '.join(full_cmd)}\")\n\n # Open log file for writing\n self.log_file = open(self.log_path, \"w\", buffering=1)\n\n # Start with parent environment\n env = os.environ.copy()\n # Note: No longer forcing PYTHONUNBUFFERED=1, let user control it\n\n # Layer 1: Apply universal environment variables from settings\n config_manager = ConfigManager()\n universal_env = config_manager.config.get(\"universal_environment\", {})\n if universal_env:\n logger.info(\n f\"Applying {len(universal_env)} universal environment variable(s)\"\n )\n for key, value in universal_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting universal {key}={value}\")\n else:\n logger.debug(f\"Setting universal {key}=\")\n\n # Layer 2: Apply profile environment variables (override universal)\n profile_env = self.config.get(\"profile_environment\", {})\n if profile_env:\n logger.info(\n f\"Applying {len(profile_env)} profile environment variable(s)\"\n )\n for key, value in profile_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting profile {key}={value}\")\n else:\n logger.debug(f\"Setting profile {key}=\")\n\n # Handle GPU device selection via CUDA_VISIBLE_DEVICES\n # This overrides any CUDA_VISIBLE_DEVICES from the profile\n if self.config.get(\"device\"):\n device_str = str(self.config[\"device\"])\n env[\"CUDA_VISIBLE_DEVICES\"] = device_str\n logger.info(f\"Setting CUDA_VISIBLE_DEVICES={device_str}\")\n\n # If using specific GPUs, adjust tensor parallel size if needed\n device_list = [d.strip() for d in device_str.split(\",\")]\n num_devices = len(device_list)\n\n # Check if tensor_parallel_size is set and compatible\n if self.config.get(\"tensor_parallel_size\"):\n tp_size = self.config[\"tensor_parallel_size\"]\n if tp_size > num_devices:\n logger.warning(\n f\"tensor_parallel_size ({tp_size}) > number of selected devices ({num_devices}). \"\n f\"Adjusting tensor_parallel_size to {num_devices}\"\n )\n self.config[\"tensor_parallel_size\"] = num_devices\n elif num_devices % tp_size != 0:\n logger.warning(\n f\"Number of GPUs ({num_devices}) is not evenly divisible by \"\n f\"tensor_parallel_size ({tp_size}). This may lead to inefficient GPU utilization. \"\n f\"Consider using tensor_parallel_size of: \"\n f\"{', '.join(str(i) for i in range(1, num_devices + 1) if num_devices % i == 0)}\"\n )\n\n # Add HuggingFace token if configured\n config_manager = ConfigManager()\n hf_token = config_manager.config.get(\"hf_token\")\n if hf_token:\n env[\"HF_TOKEN\"] = hf_token\n env[\"HUGGING_FACE_HUB_TOKEN\"] = hf_token # Some tools use this variant\n logger.info(\"HuggingFace token configured for server\")\n\n # Enable development mode for sleep endpoints if sleep mode is enabled\n if self.config.get(\"enable_sleep_mode\"):\n env[\"VLLM_SERVER_DEV_MODE\"] = \"1\"\n logger.info(\"Sleep mode enabled with development endpoints\")\n\n # Start the process with proper pipe configuration\n # Use start_new_session=True to create a new process group\n # This prevents the child process from receiving Ctrl+C signals\n self.process = subprocess.Popen(\n full_cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n text=True,\n bufsize=0, # Unbuffered\n universal_newlines=True,\n env=env,\n start_new_session=True, # Create new process group to isolate from parent signals\n )\n\n # Start log monitoring thread\n self._start_log_monitor()\n\n # Set start time and add to registry\n self.start_time = datetime.now()\n from .process import add_server\n\n add_server(self)\n\n # Return immediately - let the UI monitor the startup\n logger.info(\n f\"vLLM server process launched for {self.model} on port {self.port}\"\n )\n return True\n\n except Exception as e:\n logger.error(f\"Error starting vLLM server: {e}\")\n return False\n\n def _build_command(self) -> List[str]:\n \"\"\"\n Build the vLLM command from configuration using the schema.\n\n Returns:\n List of command arguments\n \"\"\"\n # Use the new ConfigManager to build CLI args\n config_manager = ConfigManager()\n\n # Start with the vllm command\n cmd = [\"vllm\"]\n\n # Add the arguments built from schema\n cli_args = config_manager.build_cli_args(self.config)\n cmd.extend(cli_args)\n\n # Handle extra_args if present (backward compatibility)\n if self.config.get(\"extra_args\"):\n self._add_extra_args_to_command(cmd)\n\n logger.debug(f\"Built command: {' '.join(cmd)}\")\n return cmd\n\n def _add_extra_args_to_command(self, cmd: List[str]) -> None:\n \"\"\"\n Add extra arguments to the vLLM command.\n\n Args:\n cmd: Command list to extend with extra arguments\n \"\"\"\n try:\n extra_args = shlex.split(self.config[\"extra_args\"])\n if extra_args:\n logger.info(f\"Adding extra arguments: {extra_args}\")\n cmd.extend(extra_args)\n except ValueError as e:\n logger.warning(f\"Failed to parse extra_args: {e}\")\n\n def _start_log_monitor(self) -> None:\n \"\"\"\n Start a thread to monitor log output from the vLLM server process.\n\n Creates a daemon thread that continuously reads stdout/stderr from\n the server process, writes to log files, and queues log lines for\n real-time display in the UI.\n \"\"\"\n self.log_thread = Thread(target=self._log_monitor_worker, daemon=True)\n self.log_thread.start()\n\n def _log_monitor_worker(self) -> None:\n \"\"\"\n Worker function for log monitoring thread.\n\n Continuously reads log output from the server process and handles\n file writing and queue management for UI display.\n \"\"\"\n try:\n self.log_queue.put(\"Starting vLLM server process...\")\n\n while self._should_continue_monitoring():\n if self._process_log_line():\n continue\n else:\n # No line read, check if process still running\n if self.process and self.process.poll() is not None:\n break\n time.sleep(0.01) # Small sleep to prevent busy waiting\n\n except Exception as e:\n logger.error(f\"Error in log monitor: {e}\")\n self.log_queue.put(f\"Log monitoring error: {e}\")\n\n def _should_continue_monitoring(self) -> bool:\n \"\"\"\n Check if log monitoring should continue.\n\n Returns:\n True if monitoring should continue, False otherwise\n \"\"\"\n return (\n self.is_running()\n and self.process\n and hasattr(self.process, \"stdout\")\n and self.process.stdout\n )\n\n def _process_log_line(self) -> bool:\n \"\"\"\n Process a single log line from the server output.\n\n Reads one line from the process stdout, writes it to the log file,\n and adds it to the queue for UI display after filtering and formatting.\n\n Returns:\n True if a line was processed, False if no line was available\n \"\"\"\n if not (self.process and self.process.stdout):\n return False\n\n line = self.process.stdout.readline()\n if not line:\n return False\n\n # Write to log file\n self._write_to_log_file(line)\n\n # Process for UI display\n line_stripped = line.strip()\n if line_stripped and self._should_display_log_line(line_stripped):\n # Truncate overly long lines\n if len(line_stripped) > 200:\n line_stripped = line_stripped[:197] + \"...\"\n\n self.log_queue.put(line_stripped)\n logger.debug(f\"Log captured: {line_stripped[:50]}...\")\n\n return True\n\n def _write_to_log_file(self, line: str) -> None:\n \"\"\"\n Write a log line to the log file.\n\n Args:\n line: Log line to write\n \"\"\"\n if self.log_file and not self.log_file.closed:\n self.log_file.write(line)\n self.log_file.flush()\n\n def _should_display_log_line(self, line: str) -> bool:\n \"\"\"\n Determine if a log line should be displayed in the UI.\n\n Filters out certain system messages that are not useful for users.\n\n Args:\n line: Stripped log line to check\n\n Returns:\n True if the line should be displayed, False otherwise\n \"\"\"\n # Filter out conda activation and system messages\n filtered_messages = [\n \"Activated CUDA\",\n \"Using nvcc from:\",\n \"Cuda compilation tools\",\n ]\n return not any(skip in line for skip in filtered_messages)\n\n def stop(self) -> bool:\n \"\"\"\n Stop the vLLM server.\n\n Returns:\n True if server stopped successfully, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n try:\n # Check if this is an external server\n if hasattr(self.process, \"terminate\"):\n # Normal subprocess\n # Since we created a new session, we need to terminate the entire process group\n try:\n # Get the process group ID (pgid)\n # Since we used start_new_session=True, the pgid is the same as the pid\n pgid = self.process.pid\n\n # Send SIGTERM to the entire process group for graceful shutdown\n logger.info(f\"Sending SIGTERM to process group {pgid}\")\n os.killpg(pgid, signal.SIGTERM)\n\n # Wait for process to terminate\n try:\n self.process.wait(timeout=10)\n logger.info(f\"Process group {pgid} terminated gracefully\")\n except subprocess.TimeoutExpired:\n # Force kill if not terminated\n logger.warning(\n f\"Process group {pgid} did not terminate, sending SIGKILL\"\n )\n os.killpg(pgid, signal.SIGKILL)\n self.process.wait()\n logger.info(f\"Process group {pgid} force killed\")\n\n except ProcessLookupError:\n # Process already dead\n logger.info(\"Process already terminated\")\n except PermissionError as e:\n # Fall back to terminating just the process\n logger.warning(\n f\"Permission denied for process group kill: {e}, falling back to process termination\"\n )\n self.process.terminate()\n try:\n self.process.wait(timeout=10)\n except subprocess.TimeoutExpired:\n self.process.kill()\n self.process.wait()\n elif hasattr(self.process, \"pid\"):\n # External server - kill entire process group or individual process\n try:\n pgid = self.process.pid\n killed = False\n\n # First attempt: try to kill process group\n try:\n os.killpg(pgid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process group {pgid}\")\n killed = True\n except (OSError, ProcessLookupError) as e:\n # Process group kill failed, try individual process\n logger.debug(\n f\"Process group kill failed: {e}, trying individual process\"\n )\n try:\n # Ensure pid is an integer (handle Mock objects)\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process {self.process.pid}\")\n killed = True\n except ProcessLookupError:\n # Process already dead\n logger.info(\n f\"Process {self.process.pid} already terminated\"\n )\n except OSError as e:\n logger.warning(\n f\"Failed to send SIGTERM to {self.process.pid}: {e}\"\n )\n\n if killed:\n # Wait for graceful shutdown\n time.sleep(2)\n\n # Check if still running and force kill if needed\n if self.is_running():\n try:\n os.killpg(pgid, signal.SIGKILL)\n logger.info(f\"Force killed process group {pgid}\")\n except (OSError, ProcessLookupError):\n # Process group kill failed, try individual\n try:\n # Ensure pid is an integer (handle Mock objects in tests)\n if hasattr(self.process, \"pid\"):\n try:\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGKILL)\n logger.info(f\"Force killed process {pid}\")\n except (TypeError, ValueError):\n # PID is not a valid integer (might be Mock)\n pass\n except ProcessLookupError:\n pass # Already dead\n except OSError as e:\n logger.error(\n f\"Failed to force kill {self.process.pid}: {e}\"\n )\n\n except Exception as e:\n logger.error(f\"Unexpected error stopping external server: {e}\")\n\n # Close log file if we have one\n if hasattr(self, \"log_file\") and self.log_file:\n self.log_file.close()\n\n # Remove from registry\n from .process import remove_server\n\n remove_server(self)\n\n logger.info(f\"vLLM server stopped for {self.model}\")\n return True\n\n except Exception as e:\n logger.error(f\"Error stopping vLLM server: {e}\")\n return False\n\n def is_running(self) -> bool:\n \"\"\"\n Check if the server is running.\n\n Returns:\n True if server is running, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n # Check if this is an external server (detected, not started by us)\n if hasattr(self.process, \"poll\"):\n # Normal subprocess\n return self.process.poll() is None\n elif hasattr(self.process, \"pid\"):\n # External server - check if PID still exists\n try:\n import psutil\n\n return psutil.pid_exists(self.process.pid)\n except ImportError:\n # Fallback to os method\n try:\n os.kill(self.process.pid, 0)\n return True\n except (OSError, ProcessLookupError):\n return False\n\n return False\n\n def get_status(self) -> Dict[str, Any]:\n \"\"\"\n Get server status information.\n\n Returns:\n Dictionary with status information\n \"\"\"\n status = {\n \"model\": self.model,\n \"port\": self.port,\n \"running\": self.is_running(),\n \"pid\": self.process.pid if self.process else None,\n \"start_time\": self.start_time.isoformat() if self.start_time else None,\n \"log_path\": str(self.log_path) if self.log_path else None,\n }\n\n if self.is_running() and self.start_time:\n uptime = datetime.now() - self.start_time\n status[\"uptime_seconds\"] = uptime.total_seconds()\n status[\"uptime_str\"] = str(uptime).split(\".\")[0]\n\n return status\n\n def wait_for_startup(self) -> bool:\n \"\"\"\n Wait for the server to complete startup.\n\n Monitors the server logs for startup completion indicators and verifies\n via HTTP endpoint. Will wait indefinitely until either startup completes\n or the process terminates.\n\n Returns:\n True if server started successfully, False if process terminated\n \"\"\"\n import time\n\n logger.info(f\"Waiting for {self.model} server to complete startup...\")\n\n # Track if we've seen startup indicators in logs\n log_indicates_ready = False\n\n while True:\n # Check if server is still running\n if not self.is_running():\n logger.error(\n f\"Server process for {self.model} terminated during startup\"\n )\n return False\n\n # Get recent logs to check for startup completion\n recent_logs = self.get_recent_logs(50)\n\n if recent_logs and not log_indicates_ready:\n # Check for startup completion indicators\n for log in recent_logs:\n log_lower = log.lower()\n # Look for the explicit \"Application startup complete\" message\n if \"application startup complete\" in log_lower:\n logger.debug(f\"Server {self.model} startup detected in logs\")\n log_indicates_ready = True\n break\n\n # Also check for other ready indicators as fallback\n if any(\n indicator in log_lower\n for indicator in [\n \"uvicorn running on\",\n \"started server process\",\n \"server is ready\",\n \"api server started\",\n ]\n ):\n logger.debug(\n f\"Server {self.model} startup detected via ready indicator\"\n )\n log_indicates_ready = True\n break\n\n # If logs indicate ready, verify via HTTP\n if log_indicates_ready:\n # Try to verify server is actually ready via HTTP\n port = self.config.get(\"port\")\n if port:\n try:\n import httpx\n\n with httpx.Client() as client:\n # Try /v1/models endpoint first (most reliable)\n response = client.get(\n f\"http://localhost:{port}/v1/models\", timeout=5.0\n )\n if response.status_code == 200:\n logger.info(\n f\"Server {self.model} startup complete \"\n \"(verified via HTTP)\"\n )\n return True\n except httpx.ConnectError:\n # Server not ready yet, continue waiting\n logger.debug(\n f\"Server {self.model} not accepting connections yet\"\n )\n except Exception as e:\n # Log but continue, might be network issue\n logger.debug(f\"HTTP verification failed: {e}\")\n else:\n # No port configured, trust the logs\n logger.info(\n f\"Server {self.model} startup complete (no port for verification)\"\n )\n return True\n\n # Small sleep to avoid busy waiting\n time.sleep(0.5)\n\n def get_recent_logs(self, n: int = 20) -> List[str]:\n \"\"\"\n Get recent log lines from the server output.\n\n Retrieves the most recent log lines from either the in-memory queue\n or the log file on disk. This method ensures logs are available even\n after the monitoring thread has processed them.\n\n Args:\n n: Number of recent lines to return (default: 20)\n\n Returns:\n List of recent log lines, with the most recent last\n \"\"\"\n # Update recent logs from queue\n self._update_recent_logs_from_queue()\n\n # Return from memory if available\n if self._recent_logs:\n return self._recent_logs[-n:]\n\n # Fallback to reading from file\n return self._read_logs_from_file(n)\n\n def _update_recent_logs_from_queue(self) -> None:\n \"\"\"\n Update the recent logs cache from the log queue.\n\n Drains all available log lines from the queue and adds them\n to the recent logs cache, maintaining a maximum of 100 lines.\n \"\"\"\n temp_logs = []\n\n # Get all available logs from queue (don't block)\n while not self.log_queue.empty():\n try:\n log_line = self.log_queue.get_nowait()\n temp_logs.append(log_line)\n except Empty:\n break\n\n if temp_logs:\n self._recent_logs.extend(temp_logs)\n # Keep only the last 100 logs in memory to prevent unbounded growth\n self._recent_logs = self._recent_logs[-100:]\n\n def _read_logs_from_file(self, n: int) -> List[str]:\n \"\"\"\n Read recent log lines from the log file.\n\n Args:\n n: Number of lines to read\n\n Returns:\n List of log lines from file\n \"\"\"\n if not (self.log_path and self.log_path.exists()):\n return []\n\n try:\n with open(self.log_path, \"r\") as f:\n file_logs = f.readlines()\n if file_logs:\n # Get last n lines, strip them\n logs = [line.strip() for line in file_logs[-n:]]\n # Update recent logs cache\n self._recent_logs = logs[-100:]\n return logs\n except Exception as e:\n logger.debug(f\"Error reading log file: {e}\")\n\n return []\n\n def restart(self) -> bool:\n \"\"\"\n Restart the server with the same configuration.\n\n Returns:\n True if restart successful, False otherwise\n \"\"\"\n logger.info(f\"Restarting vLLM server for {self.model}\")\n\n # Stop if running\n if self.is_running():\n self.stop()\n time.sleep(2) # Wait a bit before restarting\n\n # Start again\n return self.start()\n\n def health_check(self) -> bool:\n \"\"\"\n Perform a health check on the server.\n\n Returns:\n True if server is healthy, False otherwise\n \"\"\"\n if not self.is_running():\n return False\n\n try:\n import requests\n\n # Try to connect to the server\n response = requests.get(f\"http://localhost:{self.port}/health\", timeout=5)\n\n return response.status_code == 200\n\n except Exception:\n # If requests fails, just check process\n return self.is_running()", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 28614}, "tests/test_ollama_integration_fixed.py::273": {"resolved_imports": ["src/vllm_cli/models/cache.py", "src/vllm_cli/models/manager.py"], "used_names": ["ModelManager", "patch"], "enclosing_function": "test_list_models_includes_ollama", "extracted_code": "# Source: src/vllm_cli/models/manager.py\nclass ModelManager:\n \"\"\"\n Manages model discovery, caching, and metadata operations.\n\n Provides a high-level interface for model operations including\n listing, searching, and retrieving model information with\n integrated caching for performance.\n \"\"\"\n\n def __init__(self):\n self.cache = ModelCache()\n\n def list_available_models(self, refresh: bool = False) -> List[Dict[str, Any]]:\n \"\"\"\n List all available downloaded models with caching.\n\n Model scanning can be expensive, so results are cached for a short time\n to improve performance when multiple UI components need model data.\n\n Args:\n refresh: Force refresh the model cache, ignoring TTL\n\n Returns:\n List of model dictionaries with keys:\n - name: Full model name (publisher/model)\n - size: Model size in bytes\n - path: Path to model directory\n - type: Model type (model, custom_model)\n - publisher: Model publisher/organization\n - display_name: Human-readable model name\n - metadata: Additional model metadata\n \"\"\"\n # If refresh is forced, clear cache first to ensure fresh data\n if refresh:\n self.cache.clear_cache()\n logger.debug(\"Cache cleared for forced refresh\")\n else:\n # Check cache only if not refreshing\n cached_models = self.cache.get_cached_models()\n if cached_models is not None:\n return cached_models\n\n # Fetch fresh model data\n models = scan_for_models()\n\n # Process and normalize model data\n processed_models = []\n for item in models:\n # Accept all model types from hf-model-tool\n model_types = [\"model\", \"custom_model\", \"ollama_model\", \"gguf_model\"]\n if item.get(\"type\") in model_types:\n # For Ollama/GGUF models, use the item directly (already formatted)\n if item.get(\"type\") in [\"ollama_model\", \"gguf_model\"]:\n processed_models.append(item)\n else:\n model_dict = build_model_dict(item)\n processed_models.append(model_dict)\n\n # Sort models by name\n processed_models.sort(key=lambda x: x[\"name\"])\n\n # Update cache\n self.cache.cache_models(processed_models)\n\n logger.info(f\"Found {len(processed_models)} models\")\n return processed_models\n\n def get_model_details(self, model_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get detailed information about a specific model.\n\n Args:\n model_name: Name of the model to get details for\n\n Returns:\n Dictionary with model details or None if not found\n \"\"\"\n # First, try to find from cached models\n models = self.list_available_models()\n model_info = None\n\n for model in models:\n if model[\"name\"] == model_name or model.get(\"display_name\") == model_name:\n model_info = model\n break\n\n if not model_info:\n logger.warning(f\"Model {model_name} not found\")\n return None\n\n # Build detailed information\n details = {\n \"name\": model_info[\"name\"],\n \"full_name\": model_info[\"name\"],\n \"path\": model_info.get(\"path\", \"\"),\n \"size\": model_info.get(\"size\", 0),\n \"type\": model_info.get(\"type\", \"model\"),\n \"publisher\": model_info.get(\"publisher\", \"unknown\"),\n \"display_name\": model_info.get(\"display_name\", model_name),\n }\n\n # Extract metadata if available\n metadata = model_info.get(\"metadata\", {})\n if metadata:\n details[\"architecture\"] = (\n metadata.get(\"architectures\", [\"unknown\"])[0]\n if metadata.get(\"architectures\")\n else \"unknown\"\n )\n details[\"model_type\"] = metadata.get(\"model_type\", \"unknown\")\n details[\"torch_dtype\"] = metadata.get(\"torch_dtype\", \"unknown\")\n details[\"vocab_size\"] = metadata.get(\"vocab_size\", \"unknown\")\n\n # Add to main details\n details[\"metadata\"] = metadata\n\n # Try to read config.json for more details if path exists\n if details[\"path\"]:\n from .metadata import extract_model_config\n\n config_data = extract_model_config(details[\"path\"])\n if config_data:\n details.update(config_data)\n\n return details\n\n def search_models(self, query: str) -> List[Dict[str, Any]]:\n \"\"\"\n Search for models matching a query.\n\n Args:\n query: Search query string\n\n Returns:\n List of matching models\n \"\"\"\n models = self.list_available_models()\n query_lower = query.lower()\n\n # Filter models matching the query\n matches = []\n for model in models:\n if (\n query_lower in model[\"name\"].lower()\n or query_lower in model.get(\"display_name\", \"\").lower()\n or query_lower in model.get(\"publisher\", \"\").lower()\n ):\n matches.append(model)\n\n return matches\n\n def get_model_count(self) -> int:\n \"\"\"\n Get the total number of available models.\n\n Returns:\n Number of available models\n \"\"\"\n return len(self.list_available_models())\n\n def get_models_by_publisher(self, publisher: str) -> List[Dict[str, Any]]:\n \"\"\"\n Get all models from a specific publisher.\n\n Args:\n publisher: Publisher/organization name\n\n Returns:\n List of models from the publisher\n \"\"\"\n models = self.list_available_models()\n return [\n model\n for model in models\n if model.get(\"publisher\", \"\").lower() == publisher.lower()\n ]\n\n def get_models_by_type(self, model_type: str) -> List[Dict[str, Any]]:\n \"\"\"\n Get all models of a specific type.\n\n Args:\n model_type: Type of model (e.g., 'model', 'custom_model')\n\n Returns:\n List of models of the specified type\n \"\"\"\n models = self.list_available_models()\n return [model for model in models if model.get(\"type\") == model_type]\n\n def refresh_cache(self) -> None:\n \"\"\"Force refresh of the model cache.\"\"\"\n # First, force registry refresh to pick up any changes\n try:\n import os\n from pathlib import Path\n\n from hf_model_tool import get_registry\n\n # Clear all possible cache files\n cache_locations = [\n Path.home() / \".config/hf-model-tool/registry_cache.json\",\n Path.home() / \".cache/hf-model-tool/registry.json\",\n Path.home() / \".hf-model-tool/cache.json\",\n ]\n\n for cache_file in cache_locations:\n if cache_file.exists():\n try:\n os.remove(cache_file)\n logger.debug(f\"Removed cache file: {cache_file}\")\n except Exception as e:\n logger.debug(f\"Could not remove {cache_file}: {e}\")\n\n # Get registry and clear its in-memory cache\n registry = get_registry()\n\n # Clear all in-memory collections\n registry.models.clear()\n registry.custom_models.clear()\n registry.ollama_models.clear()\n registry.gguf_models.clear()\n registry.lora_adapters.clear()\n registry.datasets.clear()\n\n # Reset scan time to force rescan\n registry._last_scan_time = 0\n\n # Force complete rescan without incremental updates\n registry.scan_all(force=True, incremental=False)\n logger.info(\"Forced complete registry refresh\")\n except Exception as e:\n logger.debug(f\"Registry refresh error: {e}\")\n\n # Clear the cache to ensure we don't get stale data\n self.cache.clear_cache()\n logger.debug(\"Cache cleared\")\n\n # Now fetch fresh models - this will populate the cache with new data\n models = self.list_available_models(refresh=True)\n logger.info(f\"Model cache refreshed with {len(models)} models\")\n\n def get_cache_stats(self) -> Dict[str, Any]:\n \"\"\"\n Get cache statistics.\n\n Returns:\n Dictionary with cache statistics\n \"\"\"\n return self.cache.get_cache_stats()", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 8654}, "tests/test_custom_directory_integration.py::157": {"resolved_imports": ["src/vllm_cli/models/manager.py", "src/vllm_cli/models/manifest.py", "src/vllm_cli/models/discovery.py"], "used_names": ["_scan_directory_for_models"], "enclosing_function": "test_discover_custom_models", "extracted_code": "# Source: src/vllm_cli/models/discovery.py\ndef _scan_directory_for_models(base_path: Path) -> List[Dict[str, Any]]:\n \"\"\"\n Scan a directory for model files.\n\n Args:\n base_path: Base directory to scan\n\n Returns:\n List of model dictionaries found in the directory\n \"\"\"\n models = []\n\n # Look for model directories\n for model_dir in base_path.glob(\"*\"):\n if not model_dir.is_dir():\n continue\n\n # Check if it looks like a model directory\n if _is_model_directory(model_dir):\n model_info = _extract_basic_model_info(model_dir)\n if model_info:\n models.append(model_info)\n\n # Apply manifest data if available\n models = apply_manifest_to_models(models, base_path)\n\n return models", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 784}, "tests/test_ollama_integration_fixed.py::114": {"resolved_imports": ["src/vllm_cli/models/cache.py", "src/vllm_cli/models/manager.py"], "used_names": ["ModelCache"], "enclosing_function": "test_cache_stats_after_refresh", "extracted_code": "# Source: src/vllm_cli/models/cache.py\nclass ModelCache:\n \"\"\"\n Cache for model discovery results.\n\n Provides time-based caching of model listings to avoid expensive\n directory scanning operations when model data is accessed frequently.\n \"\"\"\n\n def __init__(self, ttl_seconds: float = 30.0):\n \"\"\"\n Initialize model cache.\n\n Args:\n ttl_seconds: Time-to-live for cached data in seconds\n \"\"\"\n self.ttl_seconds = ttl_seconds\n self._cache: Optional[Tuple[float, List[Dict[str, Any]]]] = None\n self._stats = {\"hits\": 0, \"misses\": 0, \"updates\": 0}\n\n def get_cached_models(self) -> Optional[List[Dict[str, Any]]]:\n \"\"\"\n Get cached model list if still valid.\n\n Returns:\n List of cached models if cache is valid, None if expired or empty\n \"\"\"\n if self._cache is None:\n self._stats[\"misses\"] += 1\n return None\n\n cache_time, cached_data = self._cache\n\n # Check if cache is still valid\n if time.time() - cache_time < self.ttl_seconds:\n self._stats[\"hits\"] += 1\n logger.debug(f\"Cache hit: returning {len(cached_data)} cached models\")\n return cached_data.copy() # Return copy to prevent modification\n else:\n # Cache expired\n self._stats[\"misses\"] += 1\n logger.debug(\"Cache expired\")\n self._cache = None\n return None\n\n def cache_models(self, models: List[Dict[str, Any]]) -> None:\n \"\"\"\n Cache a list of models.\n\n Args:\n models: List of model dictionaries to cache\n \"\"\"\n self._cache = (time.time(), models.copy())\n self._stats[\"updates\"] += 1\n logger.debug(f\"Cached {len(models)} models\")\n\n def clear_cache(self) -> None:\n \"\"\"Clear the model cache.\"\"\"\n self._cache = None\n # Increment misses to reflect that the next access will be a miss\n self._stats[\"misses\"] += 1\n logger.debug(\"Model cache cleared\")\n\n def is_cached(self) -> bool:\n \"\"\"\n Check if there is valid cached data.\n\n Returns:\n True if cache contains valid data, False otherwise\n \"\"\"\n if self._cache is None:\n return False\n\n cache_time, _ = self._cache\n return time.time() - cache_time < self.ttl_seconds\n\n def get_cache_age(self) -> Optional[float]:\n \"\"\"\n Get the age of cached data in seconds.\n\n Returns:\n Age in seconds if cache exists, None if no cache\n \"\"\"\n if self._cache is None:\n return None\n\n cache_time, _ = self._cache\n return time.time() - cache_time\n\n def get_cache_stats(self) -> Dict[str, Any]:\n \"\"\"\n Get cache statistics.\n\n Returns:\n Dictionary with cache performance statistics\n \"\"\"\n total_requests = self._stats[\"hits\"] + self._stats[\"misses\"]\n hit_rate = (\n (self._stats[\"hits\"] / total_requests * 100) if total_requests > 0 else 0\n )\n\n stats = {\n \"hits\": self._stats[\"hits\"],\n \"misses\": self._stats[\"misses\"],\n \"updates\": self._stats[\"updates\"],\n \"total_requests\": total_requests,\n \"hit_rate_percent\": round(hit_rate, 2),\n \"is_cached\": self.is_cached(),\n \"cache_age_seconds\": self.get_cache_age(),\n \"ttl_seconds\": self.ttl_seconds,\n }\n\n if self._cache:\n _, cached_data = self._cache\n stats[\"cached_models_count\"] = len(cached_data)\n else:\n stats[\"cached_models_count\"] = 0\n\n return stats\n\n def get_stats(self) -> Dict[str, Any]:\n \"\"\"\n Alias for get_cache_stats() for backward compatibility.\n\n Returns:\n Dictionary with cache performance statistics\n \"\"\"\n return self.get_cache_stats()\n\n def reset_stats(self) -> None:\n \"\"\"Reset cache statistics.\"\"\"\n self._stats = {\"hits\": 0, \"misses\": 0, \"updates\": 0}\n logger.debug(\"Cache statistics reset\")\n\n def set_ttl(self, ttl_seconds: float) -> None:\n \"\"\"\n Set new TTL for cache.\n\n Args:\n ttl_seconds: New time-to-live in seconds\n \"\"\"\n old_ttl = self.ttl_seconds\n self.ttl_seconds = ttl_seconds\n logger.debug(f\"Cache TTL changed from {old_ttl}s to {ttl_seconds}s\")\n\n def get_cached_model_count(self) -> int:\n \"\"\"\n Get the number of models currently cached.\n\n Returns:\n Number of cached models, 0 if no cache\n \"\"\"\n if self._cache is None:\n return 0\n\n _, cached_data = self._cache\n return len(cached_data)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 4761}, "tests/test_config_manager.py::58": {"resolved_imports": ["src/vllm_cli/config/manager.py"], "used_names": ["ConfigManager", "patch", "yaml"], "enclosing_function": "test_load_existing_config", "extracted_code": "# Source: src/vllm_cli/config/manager.py\nclass ConfigManager:\n \"\"\"\n Enhanced configuration manager with comprehensive validation support.\n\n This class manages configuration files, profiles, and validation using\n the new validation framework. It provides a clean API for configuration\n operations while ensuring data integrity through comprehensive validation.\n\n Attributes:\n config_dir: Directory for configuration files\n validation_registry: Registry of validation rules\n compatibility_validator: Validator for parameter combinations\n \"\"\"\n\n def __init__(self):\n # Paths for configuration files\n self.config_dir = Path.home() / \".config\" / \"vllm-cli\"\n self.config_file = self.config_dir / \"config.yaml\"\n\n # Ensure config directory exists\n self.config_dir.mkdir(parents=True, exist_ok=True)\n\n # Initialize sub-managers\n self.schema_manager = SchemaManager()\n self.profile_manager = ProfileManager(self.config_dir)\n self.persistence_manager = PersistenceManager()\n self.shortcut_manager = ShortcutManager(self.config_dir)\n\n # Initialize validation system\n self.validation_registry = create_vllm_validation_registry()\n self.compatibility_validator = create_compatibility_validator(\n self.validation_registry\n )\n\n # Load main configuration\n self.config = self._load_config()\n\n def _load_config(self) -> Dict[str, Any]:\n \"\"\"Load main configuration file (legacy YAML support).\"\"\"\n return self.persistence_manager.load_yaml_file(self.config_file)\n\n def _save_config(self) -> None:\n \"\"\"Save main configuration file.\"\"\"\n self.persistence_manager.save_yaml_file(self.config_file, self.config)\n\n def get_argument_info(self, arg_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get detailed information about a specific argument.\"\"\"\n return self.schema_manager.get_argument_info(arg_name)\n\n def get_arguments_by_category(self, category: str) -> List[Dict[str, Any]]:\n \"\"\"Get all arguments belonging to a specific category.\"\"\"\n return self.schema_manager.get_arguments_by_category(category)\n\n def get_category_info(self, category: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get information about a specific category.\"\"\"\n return self.schema_manager.get_category_info(category)\n\n def get_ordered_categories(self) -> List[Tuple[str, Dict[str, Any]]]:\n \"\"\"Get categories ordered by their display order.\"\"\"\n return self.schema_manager.get_ordered_categories()\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n return self.profile_manager.get_all_profiles()\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name with dynamic defaults applied.\"\"\"\n profile = self.profile_manager.get_profile(name)\n if profile and \"config\" in profile:\n # Apply dynamic defaults to the profile configuration\n profile[\"config\"] = self.profile_manager.apply_dynamic_defaults(\n profile[\"config\"]\n )\n return profile\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"Save or update a user profile with validation.\"\"\"\n # Validate profile configuration if present\n if \"config\" in profile:\n is_valid, errors = self.validate_config(profile[\"config\"])\n if not is_valid:\n from ..errors import ProfileError\n\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n return self.profile_manager.save_user_profile(name, profile)\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n return self.profile_manager.delete_user_profile(name)\n\n @property\n def default_profiles(self) -> Dict[str, Any]:\n \"\"\"Get default profiles.\"\"\"\n return self.profile_manager.default_profiles\n\n @property\n def user_profiles(self) -> Dict[str, Any]:\n \"\"\"Get user profiles.\"\"\"\n return self.profile_manager.user_profiles\n\n def validate_config(self, config: Dict[str, Any]) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate a configuration using the new validation framework.\n\n This method uses the comprehensive validation system to check\n configuration values, types, ranges, and dependencies.\n\n Args:\n config: Configuration dictionary to validate\n\n Returns:\n Tuple of (is_valid, list_of_error_messages)\n\n Raises:\n ConfigurationError: If validation system fails\n \"\"\"\n try:\n # Use new validation system\n result = self.validation_registry.validate_config(config)\n\n # Convert validation errors to string messages for backward compatibility\n error_messages = result.get_error_messages()\n\n # Add warnings if any\n if result.warnings:\n for warning in result.warnings:\n logger.warning(f\"Configuration warning: {warning}\")\n\n return result.is_valid(), error_messages\n\n except Exception as e:\n logger.error(f\"Error during configuration validation: {e}\")\n raise ConfigurationError(\n f\"Validation system error: {e}\", error_code=\"VALIDATION_SYSTEM_ERROR\"\n ) from e\n\n def validate_argument_combination(\n self, config: Dict[str, Any]\n ) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate that argument combinations are compatible using the new compatibility validator.\n\n Args:\n config: Configuration dictionary to check for compatibility\n\n Returns:\n Tuple of (is_valid, list_of_warnings_or_errors)\n \"\"\"\n try:\n issues = self.compatibility_validator.validate_compatibility(config)\n\n warnings = []\n errors = []\n\n for issue in issues:\n message = issue[\"message\"]\n if issue[\"severity\"] == \"error\":\n errors.append(message)\n else:\n warnings.append(message)\n\n # Log warnings\n for warning in warnings:\n logger.warning(f\"Configuration compatibility warning: {warning}\")\n\n # Return all issues as warnings for backward compatibility\n # (errors are treated as warnings in the legacy interface)\n all_issues = errors + warnings\n\n return len(errors) == 0, all_issues\n\n except Exception as e:\n logger.error(f\"Error during compatibility validation: {e}\")\n return False, [f\"Compatibility validation error: {e}\"]\n\n def build_cli_args(self, config: Dict[str, Any]) -> List[str]:\n \"\"\"\n Build command-line arguments from a configuration dictionary.\n\n Only includes arguments that are explicitly set in the config.\n Handles special cases like LoRA modules.\n \"\"\"\n args = []\n\n # Special handling for model (positional argument)\n # Check if this is a GGUF/Ollama configuration\n if (\n isinstance(config.get(\"model\"), dict)\n and \"quantization\" in config[\"model\"]\n and config[\"model\"][\"quantization\"] == \"gguf\"\n ):\n # Extract GGUF model config\n gguf_config = config[\"model\"]\n model_path = gguf_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", model_path])\n\n # Set quantization to gguf\n config[\"quantization\"] = \"gguf\"\n\n # Add served-model-name if provided (for Ollama models)\n if \"served_model_name\" in gguf_config:\n config[\"served_model_name\"] = gguf_config[\"served_model_name\"]\n logger.info(\n f\"Configuring GGUF model: {model_path} as {gguf_config['served_model_name']}\"\n )\n else:\n logger.info(f\"Configuring GGUF model: {model_path}\")\n\n # Check if this is a LoRA configuration\n elif (\n isinstance(config.get(\"model\"), dict) and \"lora_modules\" in config[\"model\"]\n ):\n # Extract base model and LoRA config\n lora_config = config[\"model\"]\n base_model = lora_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", base_model])\n\n # Enable LoRA support when modules are present\n args.append(\"--enable-lora\")\n\n # Track maximum rank for all LoRA modules\n max_rank = 16 # Default minimum\n\n # Add LoRA modules\n for lora in lora_config.get(\"lora_modules\", []):\n lora_path = lora.get(\"path\", \"\")\n if lora_path:\n # vLLM expects --lora-modules with name=path format\n lora_name = lora.get(\"name\", \"adapter\")\n args.extend([\"--lora-modules\", f\"{lora_name}={lora_path}\"])\n\n # Track maximum rank\n lora_rank = lora.get(\"rank\", 16)\n max_rank = max(max_rank, lora_rank)\n\n # Add max-lora-rank parameter\n args.extend([\"--max-lora-rank\", str(max_rank)])\n\n elif \"model\" in config:\n args.extend([\"serve\", config[\"model\"]])\n\n # Handle lora_modules if present as a string (from CLI)\n if \"lora_modules\" in config and config[\"lora_modules\"]:\n # Enable LoRA support\n if \"--enable-lora\" not in args:\n args.append(\"--enable-lora\")\n\n # Parse and add LoRA modules\n lora_modules_str = config[\"lora_modules\"]\n if isinstance(lora_modules_str, str):\n # Split by space and add each module\n for module in lora_modules_str.split():\n args.extend([\"--lora-modules\", module])\n\n # Add max-lora-rank if not already added\n # Use a safe default of 64 which should cover most LoRA adapters\n if \"--max-lora-rank\" not in args:\n # Check if max_lora_rank is explicitly set in config\n if \"max_lora_rank\" not in config:\n args.extend([\"--max-lora-rank\", \"64\"])\n\n for arg_name, value in config.items():\n # Skip special keys and None values\n if (\n arg_name in [\"model\", \"name\", \"description\", \"icon\", \"lora_modules\"]\n or value is None\n ):\n continue\n\n arg_info = self.schema_manager.get_argument_info(arg_name)\n if not arg_info:\n logger.warning(f\"Unknown argument in config: {arg_name}\")\n continue\n\n cli_flag = arg_info.get(\"cli_flag\")\n if not cli_flag:\n continue\n\n arg_type = arg_info.get(\"type\")\n\n if arg_type == \"boolean\":\n if value: # Only add flag if True\n args.append(cli_flag)\n elif arg_type in [\"integer\", \"float\", \"string\", \"choice\"]:\n args.extend([cli_flag, str(value)])\n else:\n logger.warning(f\"Unknown argument type for {arg_name}: {arg_type}\")\n\n return args\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n return self.profile_manager.export_profile(profile_name, filepath)\n\n def import_profile(self, filepath: Path, new_name: Optional[str] = None) -> bool:\n \"\"\"Import a profile from a JSON file with comprehensive validation.\"\"\"\n return self.profile_manager.import_profile(\n filepath, new_name, self.validate_config\n )\n\n def get_last_config(self) -> Optional[Dict[str, Any]]:\n \"\"\"Get the last used server configuration.\"\"\"\n return self.config.get(\"last_config\")\n\n def save_last_config(self, config: Dict[str, Any]) -> None:\n \"\"\"Save the last used server configuration.\"\"\"\n self.config[\"last_config\"] = config\n self._save_config()\n\n def get_recent_models(self, limit: int = 5) -> List[str]:\n \"\"\"Get recently used models.\"\"\"\n return self.config.get(\"recent_models\", [])[:limit]\n\n def add_recent_model(self, model: str) -> None:\n \"\"\"Add a model to recent models list.\"\"\"\n recent = self.config.get(\"recent_models\", [])\n if model in recent:\n recent.remove(model)\n recent.insert(0, model)\n self.config[\"recent_models\"] = recent[:10] # Keep only last 10\n self._save_config()\n\n def clear_cache(self) -> None:\n \"\"\"Clear cached data.\"\"\"\n cache_file = self.config_dir / \"cache.json\"\n if cache_file.exists():\n cache_file.unlink()\n self.config.pop(\"last_config\", None)\n self.config.pop(\"recent_models\", None)\n self._save_config()\n logger.info(\"Cache cleared\")\n\n def get_server_defaults(self) -> Dict[str, Any]:\n \"\"\"Get default server settings.\"\"\"\n return self.config.get(\n \"server_defaults\",\n {\n \"default_port\": 8000,\n \"auto_restart\": False,\n \"log_level\": \"info\",\n \"cleanup_on_exit\": True, # Default to cleaning up servers on exit\n },\n )\n\n def save_server_defaults(self, defaults: Dict[str, Any]) -> None:\n \"\"\"Save default server settings.\"\"\"\n self.config[\"server_defaults\"] = defaults\n self._save_config()\n\n def get_ui_preferences(self) -> Dict[str, Any]:\n \"\"\"Get UI preferences including progress bar style and log display settings.\"\"\"\n return self.config.get(\n \"ui_preferences\",\n {\n \"progress_bar_style\": \"blocks\", # Default style\n \"show_gpu_in_monitor\": True,\n \"log_lines_startup\": 50, # Number of log lines to show during startup\n \"log_lines_monitor\": 50, # Number of log lines to show in server monitor\n \"startup_refresh_rate\": 4.0, # Hz for startup log refresh\n \"monitor_refresh_rate\": 1.0, # Hz for monitor log refresh\n },\n )\n\n def save_ui_preferences(self, preferences: Dict[str, Any]) -> None:\n \"\"\"Save UI preferences.\"\"\"\n self.config[\"ui_preferences\"] = preferences\n self._save_config()\n\n # Shortcut management methods\n def get_all_shortcuts(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all shortcuts.\"\"\"\n return self.shortcut_manager.get_all_shortcuts()\n\n def get_shortcut(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific shortcut by name.\"\"\"\n return self.shortcut_manager.get_shortcut(name)\n\n def save_shortcut(self, name: str, shortcut_data: Dict[str, Any]) -> bool:\n \"\"\"Save or update a shortcut.\"\"\"\n return self.shortcut_manager.save_shortcut(name, shortcut_data)\n\n def delete_shortcut(self, name: str) -> bool:\n \"\"\"Delete a shortcut.\"\"\"\n return self.shortcut_manager.delete_shortcut(name)\n\n def list_shortcuts(self) -> List[Dict[str, Any]]:\n \"\"\"List all shortcuts with summary information.\"\"\"\n return self.shortcut_manager.list_shortcuts()\n\n def get_recent_shortcuts(self, limit: int = 5) -> List[Dict[str, Any]]:\n \"\"\"Get recently used shortcuts.\"\"\"\n return self.shortcut_manager.get_recent_shortcuts(limit)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 15704}, "tests/test_custom_directory_integration.py::391": {"resolved_imports": ["src/vllm_cli/models/manager.py", "src/vllm_cli/models/manifest.py"], "used_names": ["Path", "apply_manifest_to_models", "json", "tempfile"], "enclosing_function": "test_custom_model_with_manifest_metadata", "extracted_code": "# Source: src/vllm_cli/models/manifest.py\ndef apply_manifest_to_models(\n models: List[Dict[str, Any]], directory: Path\n) -> List[Dict[str, Any]]:\n \"\"\"\n Apply manifest data to discovered models if manifest exists.\n\n Args:\n models: List of discovered models\n directory: Directory to check for manifest\n\n Returns:\n Updated models list with manifest data applied\n \"\"\"\n manifest = load_manifest(directory)\n if not manifest:\n return models\n\n manifest_models = manifest.get(\"models\", [])\n manifest_by_path = {}\n\n # Build lookup by path\n for entry in manifest_models:\n if entry.get(\"enabled\", True):\n # Resolve path\n model_path = directory / entry[\"path\"]\n manifest_by_path[str(model_path)] = entry\n\n # Apply manifest data to models\n updated_models = []\n for model in models:\n model_path = model.get(\"path\", \"\")\n\n if model_path in manifest_by_path:\n manifest_entry = manifest_by_path[model_path]\n # Override with manifest data\n model[\"name\"] = manifest_entry.get(\"name\", model[\"name\"])\n model[\"display_name\"] = manifest_entry.get(\"name\", model[\"display_name\"])\n model[\"publisher\"] = manifest_entry.get(\n \"publisher\", model.get(\"publisher\", \"unknown\")\n )\n model[\"notes\"] = manifest_entry.get(\"notes\", \"\")\n model[\"from_manifest\"] = True\n\n updated_models.append(model)\n\n return updated_models", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 1521}, "tests/test_environment_variables.py::168": {"resolved_imports": ["src/vllm_cli/config/manager.py", "src/vllm_cli/server/manager.py"], "used_names": ["Mock", "VLLMServer", "os", "patch"], "enclosing_function": "test_subprocess_env_isolation", "extracted_code": "# Source: src/vllm_cli/server/manager.py\nclass VLLMServer:\n \"\"\"\n Manages a vLLM server instance with comprehensive lifecycle control.\n\n This class handles the complete lifecycle of a vLLM server including\n configuration, process management, logging, monitoring, and cleanup.\n It supports both programmatically started servers and external server\n detection and management.\n\n Attributes:\n config: Server configuration dictionary\n model: Model name being served\n port: Port number the server is listening on\n process: Subprocess or external process reference\n log_file: File handle for server logs\n log_queue: Thread-safe queue for log lines\n log_thread: Background thread for log monitoring\n start_time: Timestamp when server was started\n log_path: Path to the server's log file\n \"\"\"\n\n def __init__(self, config: Dict[str, Any]) -> None:\n \"\"\"\n Initialize a vLLM server instance.\n\n Sets up the server configuration, logging infrastructure, and\n prepares the instance for server lifecycle management.\n\n Args:\n config: Server configuration dictionary containing model name,\n port, and other vLLM-specific parameters\n \"\"\"\n self.config: Dict[str, Any] = config\n\n # Extract model name - handle both string and dict (LoRA config) formats\n model_config = config.get(\"model\", \"unknown\")\n if isinstance(model_config, dict):\n # LoRA configuration - extract base model name\n self.model: str = model_config.get(\"model\", \"unknown\")\n else:\n # Regular string model name\n self.model: str = model_config\n\n self.port: int = config.get(\"port\", 8000)\n self.process: Optional[Union[subprocess.Popen, Any]] = None\n self.log_file: Optional[TextIO] = None\n self.log_queue: Queue[str] = Queue()\n self.log_thread: Optional[Thread] = None\n self.start_time: Optional[datetime] = None\n self.log_path: Path\n self._recent_logs: List[str] = []\n\n # Setup logging\n log_dir = Path.home() / \".vllm-cli\" / \"logs\"\n log_dir.mkdir(parents=True, exist_ok=True)\n\n timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n self.log_path = log_dir / f\"vllm_{self.model.replace('/', '_')}_{timestamp}.log\"\n\n def start(self) -> bool:\n \"\"\"\n Start the vLLM server.\n\n Returns:\n True if server started successfully, False otherwise\n \"\"\"\n if self.is_running():\n logger.warning(f\"Server already running for {self.model}\")\n return False\n\n try:\n # Build command - run directly without conda wrapper\n full_cmd = self._build_command()\n\n logger.info(f\"Starting vLLM server with command: {' '.join(full_cmd)}\")\n\n # Open log file for writing\n self.log_file = open(self.log_path, \"w\", buffering=1)\n\n # Start with parent environment\n env = os.environ.copy()\n # Note: No longer forcing PYTHONUNBUFFERED=1, let user control it\n\n # Layer 1: Apply universal environment variables from settings\n config_manager = ConfigManager()\n universal_env = config_manager.config.get(\"universal_environment\", {})\n if universal_env:\n logger.info(\n f\"Applying {len(universal_env)} universal environment variable(s)\"\n )\n for key, value in universal_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting universal {key}={value}\")\n else:\n logger.debug(f\"Setting universal {key}=\")\n\n # Layer 2: Apply profile environment variables (override universal)\n profile_env = self.config.get(\"profile_environment\", {})\n if profile_env:\n logger.info(\n f\"Applying {len(profile_env)} profile environment variable(s)\"\n )\n for key, value in profile_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting profile {key}={value}\")\n else:\n logger.debug(f\"Setting profile {key}=\")\n\n # Handle GPU device selection via CUDA_VISIBLE_DEVICES\n # This overrides any CUDA_VISIBLE_DEVICES from the profile\n if self.config.get(\"device\"):\n device_str = str(self.config[\"device\"])\n env[\"CUDA_VISIBLE_DEVICES\"] = device_str\n logger.info(f\"Setting CUDA_VISIBLE_DEVICES={device_str}\")\n\n # If using specific GPUs, adjust tensor parallel size if needed\n device_list = [d.strip() for d in device_str.split(\",\")]\n num_devices = len(device_list)\n\n # Check if tensor_parallel_size is set and compatible\n if self.config.get(\"tensor_parallel_size\"):\n tp_size = self.config[\"tensor_parallel_size\"]\n if tp_size > num_devices:\n logger.warning(\n f\"tensor_parallel_size ({tp_size}) > number of selected devices ({num_devices}). \"\n f\"Adjusting tensor_parallel_size to {num_devices}\"\n )\n self.config[\"tensor_parallel_size\"] = num_devices\n elif num_devices % tp_size != 0:\n logger.warning(\n f\"Number of GPUs ({num_devices}) is not evenly divisible by \"\n f\"tensor_parallel_size ({tp_size}). This may lead to inefficient GPU utilization. \"\n f\"Consider using tensor_parallel_size of: \"\n f\"{', '.join(str(i) for i in range(1, num_devices + 1) if num_devices % i == 0)}\"\n )\n\n # Add HuggingFace token if configured\n config_manager = ConfigManager()\n hf_token = config_manager.config.get(\"hf_token\")\n if hf_token:\n env[\"HF_TOKEN\"] = hf_token\n env[\"HUGGING_FACE_HUB_TOKEN\"] = hf_token # Some tools use this variant\n logger.info(\"HuggingFace token configured for server\")\n\n # Enable development mode for sleep endpoints if sleep mode is enabled\n if self.config.get(\"enable_sleep_mode\"):\n env[\"VLLM_SERVER_DEV_MODE\"] = \"1\"\n logger.info(\"Sleep mode enabled with development endpoints\")\n\n # Start the process with proper pipe configuration\n # Use start_new_session=True to create a new process group\n # This prevents the child process from receiving Ctrl+C signals\n self.process = subprocess.Popen(\n full_cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n text=True,\n bufsize=0, # Unbuffered\n universal_newlines=True,\n env=env,\n start_new_session=True, # Create new process group to isolate from parent signals\n )\n\n # Start log monitoring thread\n self._start_log_monitor()\n\n # Set start time and add to registry\n self.start_time = datetime.now()\n from .process import add_server\n\n add_server(self)\n\n # Return immediately - let the UI monitor the startup\n logger.info(\n f\"vLLM server process launched for {self.model} on port {self.port}\"\n )\n return True\n\n except Exception as e:\n logger.error(f\"Error starting vLLM server: {e}\")\n return False\n\n def _build_command(self) -> List[str]:\n \"\"\"\n Build the vLLM command from configuration using the schema.\n\n Returns:\n List of command arguments\n \"\"\"\n # Use the new ConfigManager to build CLI args\n config_manager = ConfigManager()\n\n # Start with the vllm command\n cmd = [\"vllm\"]\n\n # Add the arguments built from schema\n cli_args = config_manager.build_cli_args(self.config)\n cmd.extend(cli_args)\n\n # Handle extra_args if present (backward compatibility)\n if self.config.get(\"extra_args\"):\n self._add_extra_args_to_command(cmd)\n\n logger.debug(f\"Built command: {' '.join(cmd)}\")\n return cmd\n\n def _add_extra_args_to_command(self, cmd: List[str]) -> None:\n \"\"\"\n Add extra arguments to the vLLM command.\n\n Args:\n cmd: Command list to extend with extra arguments\n \"\"\"\n try:\n extra_args = shlex.split(self.config[\"extra_args\"])\n if extra_args:\n logger.info(f\"Adding extra arguments: {extra_args}\")\n cmd.extend(extra_args)\n except ValueError as e:\n logger.warning(f\"Failed to parse extra_args: {e}\")\n\n def _start_log_monitor(self) -> None:\n \"\"\"\n Start a thread to monitor log output from the vLLM server process.\n\n Creates a daemon thread that continuously reads stdout/stderr from\n the server process, writes to log files, and queues log lines for\n real-time display in the UI.\n \"\"\"\n self.log_thread = Thread(target=self._log_monitor_worker, daemon=True)\n self.log_thread.start()\n\n def _log_monitor_worker(self) -> None:\n \"\"\"\n Worker function for log monitoring thread.\n\n Continuously reads log output from the server process and handles\n file writing and queue management for UI display.\n \"\"\"\n try:\n self.log_queue.put(\"Starting vLLM server process...\")\n\n while self._should_continue_monitoring():\n if self._process_log_line():\n continue\n else:\n # No line read, check if process still running\n if self.process and self.process.poll() is not None:\n break\n time.sleep(0.01) # Small sleep to prevent busy waiting\n\n except Exception as e:\n logger.error(f\"Error in log monitor: {e}\")\n self.log_queue.put(f\"Log monitoring error: {e}\")\n\n def _should_continue_monitoring(self) -> bool:\n \"\"\"\n Check if log monitoring should continue.\n\n Returns:\n True if monitoring should continue, False otherwise\n \"\"\"\n return (\n self.is_running()\n and self.process\n and hasattr(self.process, \"stdout\")\n and self.process.stdout\n )\n\n def _process_log_line(self) -> bool:\n \"\"\"\n Process a single log line from the server output.\n\n Reads one line from the process stdout, writes it to the log file,\n and adds it to the queue for UI display after filtering and formatting.\n\n Returns:\n True if a line was processed, False if no line was available\n \"\"\"\n if not (self.process and self.process.stdout):\n return False\n\n line = self.process.stdout.readline()\n if not line:\n return False\n\n # Write to log file\n self._write_to_log_file(line)\n\n # Process for UI display\n line_stripped = line.strip()\n if line_stripped and self._should_display_log_line(line_stripped):\n # Truncate overly long lines\n if len(line_stripped) > 200:\n line_stripped = line_stripped[:197] + \"...\"\n\n self.log_queue.put(line_stripped)\n logger.debug(f\"Log captured: {line_stripped[:50]}...\")\n\n return True\n\n def _write_to_log_file(self, line: str) -> None:\n \"\"\"\n Write a log line to the log file.\n\n Args:\n line: Log line to write\n \"\"\"\n if self.log_file and not self.log_file.closed:\n self.log_file.write(line)\n self.log_file.flush()\n\n def _should_display_log_line(self, line: str) -> bool:\n \"\"\"\n Determine if a log line should be displayed in the UI.\n\n Filters out certain system messages that are not useful for users.\n\n Args:\n line: Stripped log line to check\n\n Returns:\n True if the line should be displayed, False otherwise\n \"\"\"\n # Filter out conda activation and system messages\n filtered_messages = [\n \"Activated CUDA\",\n \"Using nvcc from:\",\n \"Cuda compilation tools\",\n ]\n return not any(skip in line for skip in filtered_messages)\n\n def stop(self) -> bool:\n \"\"\"\n Stop the vLLM server.\n\n Returns:\n True if server stopped successfully, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n try:\n # Check if this is an external server\n if hasattr(self.process, \"terminate\"):\n # Normal subprocess\n # Since we created a new session, we need to terminate the entire process group\n try:\n # Get the process group ID (pgid)\n # Since we used start_new_session=True, the pgid is the same as the pid\n pgid = self.process.pid\n\n # Send SIGTERM to the entire process group for graceful shutdown\n logger.info(f\"Sending SIGTERM to process group {pgid}\")\n os.killpg(pgid, signal.SIGTERM)\n\n # Wait for process to terminate\n try:\n self.process.wait(timeout=10)\n logger.info(f\"Process group {pgid} terminated gracefully\")\n except subprocess.TimeoutExpired:\n # Force kill if not terminated\n logger.warning(\n f\"Process group {pgid} did not terminate, sending SIGKILL\"\n )\n os.killpg(pgid, signal.SIGKILL)\n self.process.wait()\n logger.info(f\"Process group {pgid} force killed\")\n\n except ProcessLookupError:\n # Process already dead\n logger.info(\"Process already terminated\")\n except PermissionError as e:\n # Fall back to terminating just the process\n logger.warning(\n f\"Permission denied for process group kill: {e}, falling back to process termination\"\n )\n self.process.terminate()\n try:\n self.process.wait(timeout=10)\n except subprocess.TimeoutExpired:\n self.process.kill()\n self.process.wait()\n elif hasattr(self.process, \"pid\"):\n # External server - kill entire process group or individual process\n try:\n pgid = self.process.pid\n killed = False\n\n # First attempt: try to kill process group\n try:\n os.killpg(pgid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process group {pgid}\")\n killed = True\n except (OSError, ProcessLookupError) as e:\n # Process group kill failed, try individual process\n logger.debug(\n f\"Process group kill failed: {e}, trying individual process\"\n )\n try:\n # Ensure pid is an integer (handle Mock objects)\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process {self.process.pid}\")\n killed = True\n except ProcessLookupError:\n # Process already dead\n logger.info(\n f\"Process {self.process.pid} already terminated\"\n )\n except OSError as e:\n logger.warning(\n f\"Failed to send SIGTERM to {self.process.pid}: {e}\"\n )\n\n if killed:\n # Wait for graceful shutdown\n time.sleep(2)\n\n # Check if still running and force kill if needed\n if self.is_running():\n try:\n os.killpg(pgid, signal.SIGKILL)\n logger.info(f\"Force killed process group {pgid}\")\n except (OSError, ProcessLookupError):\n # Process group kill failed, try individual\n try:\n # Ensure pid is an integer (handle Mock objects in tests)\n if hasattr(self.process, \"pid\"):\n try:\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGKILL)\n logger.info(f\"Force killed process {pid}\")\n except (TypeError, ValueError):\n # PID is not a valid integer (might be Mock)\n pass\n except ProcessLookupError:\n pass # Already dead\n except OSError as e:\n logger.error(\n f\"Failed to force kill {self.process.pid}: {e}\"\n )\n\n except Exception as e:\n logger.error(f\"Unexpected error stopping external server: {e}\")\n\n # Close log file if we have one\n if hasattr(self, \"log_file\") and self.log_file:\n self.log_file.close()\n\n # Remove from registry\n from .process import remove_server\n\n remove_server(self)\n\n logger.info(f\"vLLM server stopped for {self.model}\")\n return True\n\n except Exception as e:\n logger.error(f\"Error stopping vLLM server: {e}\")\n return False\n\n def is_running(self) -> bool:\n \"\"\"\n Check if the server is running.\n\n Returns:\n True if server is running, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n # Check if this is an external server (detected, not started by us)\n if hasattr(self.process, \"poll\"):\n # Normal subprocess\n return self.process.poll() is None\n elif hasattr(self.process, \"pid\"):\n # External server - check if PID still exists\n try:\n import psutil\n\n return psutil.pid_exists(self.process.pid)\n except ImportError:\n # Fallback to os method\n try:\n os.kill(self.process.pid, 0)\n return True\n except (OSError, ProcessLookupError):\n return False\n\n return False\n\n def get_status(self) -> Dict[str, Any]:\n \"\"\"\n Get server status information.\n\n Returns:\n Dictionary with status information\n \"\"\"\n status = {\n \"model\": self.model,\n \"port\": self.port,\n \"running\": self.is_running(),\n \"pid\": self.process.pid if self.process else None,\n \"start_time\": self.start_time.isoformat() if self.start_time else None,\n \"log_path\": str(self.log_path) if self.log_path else None,\n }\n\n if self.is_running() and self.start_time:\n uptime = datetime.now() - self.start_time\n status[\"uptime_seconds\"] = uptime.total_seconds()\n status[\"uptime_str\"] = str(uptime).split(\".\")[0]\n\n return status\n\n def wait_for_startup(self) -> bool:\n \"\"\"\n Wait for the server to complete startup.\n\n Monitors the server logs for startup completion indicators and verifies\n via HTTP endpoint. Will wait indefinitely until either startup completes\n or the process terminates.\n\n Returns:\n True if server started successfully, False if process terminated\n \"\"\"\n import time\n\n logger.info(f\"Waiting for {self.model} server to complete startup...\")\n\n # Track if we've seen startup indicators in logs\n log_indicates_ready = False\n\n while True:\n # Check if server is still running\n if not self.is_running():\n logger.error(\n f\"Server process for {self.model} terminated during startup\"\n )\n return False\n\n # Get recent logs to check for startup completion\n recent_logs = self.get_recent_logs(50)\n\n if recent_logs and not log_indicates_ready:\n # Check for startup completion indicators\n for log in recent_logs:\n log_lower = log.lower()\n # Look for the explicit \"Application startup complete\" message\n if \"application startup complete\" in log_lower:\n logger.debug(f\"Server {self.model} startup detected in logs\")\n log_indicates_ready = True\n break\n\n # Also check for other ready indicators as fallback\n if any(\n indicator in log_lower\n for indicator in [\n \"uvicorn running on\",\n \"started server process\",\n \"server is ready\",\n \"api server started\",\n ]\n ):\n logger.debug(\n f\"Server {self.model} startup detected via ready indicator\"\n )\n log_indicates_ready = True\n break\n\n # If logs indicate ready, verify via HTTP\n if log_indicates_ready:\n # Try to verify server is actually ready via HTTP\n port = self.config.get(\"port\")\n if port:\n try:\n import httpx\n\n with httpx.Client() as client:\n # Try /v1/models endpoint first (most reliable)\n response = client.get(\n f\"http://localhost:{port}/v1/models\", timeout=5.0\n )\n if response.status_code == 200:\n logger.info(\n f\"Server {self.model} startup complete \"\n \"(verified via HTTP)\"\n )\n return True\n except httpx.ConnectError:\n # Server not ready yet, continue waiting\n logger.debug(\n f\"Server {self.model} not accepting connections yet\"\n )\n except Exception as e:\n # Log but continue, might be network issue\n logger.debug(f\"HTTP verification failed: {e}\")\n else:\n # No port configured, trust the logs\n logger.info(\n f\"Server {self.model} startup complete (no port for verification)\"\n )\n return True\n\n # Small sleep to avoid busy waiting\n time.sleep(0.5)\n\n def get_recent_logs(self, n: int = 20) -> List[str]:\n \"\"\"\n Get recent log lines from the server output.\n\n Retrieves the most recent log lines from either the in-memory queue\n or the log file on disk. This method ensures logs are available even\n after the monitoring thread has processed them.\n\n Args:\n n: Number of recent lines to return (default: 20)\n\n Returns:\n List of recent log lines, with the most recent last\n \"\"\"\n # Update recent logs from queue\n self._update_recent_logs_from_queue()\n\n # Return from memory if available\n if self._recent_logs:\n return self._recent_logs[-n:]\n\n # Fallback to reading from file\n return self._read_logs_from_file(n)\n\n def _update_recent_logs_from_queue(self) -> None:\n \"\"\"\n Update the recent logs cache from the log queue.\n\n Drains all available log lines from the queue and adds them\n to the recent logs cache, maintaining a maximum of 100 lines.\n \"\"\"\n temp_logs = []\n\n # Get all available logs from queue (don't block)\n while not self.log_queue.empty():\n try:\n log_line = self.log_queue.get_nowait()\n temp_logs.append(log_line)\n except Empty:\n break\n\n if temp_logs:\n self._recent_logs.extend(temp_logs)\n # Keep only the last 100 logs in memory to prevent unbounded growth\n self._recent_logs = self._recent_logs[-100:]\n\n def _read_logs_from_file(self, n: int) -> List[str]:\n \"\"\"\n Read recent log lines from the log file.\n\n Args:\n n: Number of lines to read\n\n Returns:\n List of log lines from file\n \"\"\"\n if not (self.log_path and self.log_path.exists()):\n return []\n\n try:\n with open(self.log_path, \"r\") as f:\n file_logs = f.readlines()\n if file_logs:\n # Get last n lines, strip them\n logs = [line.strip() for line in file_logs[-n:]]\n # Update recent logs cache\n self._recent_logs = logs[-100:]\n return logs\n except Exception as e:\n logger.debug(f\"Error reading log file: {e}\")\n\n return []\n\n def restart(self) -> bool:\n \"\"\"\n Restart the server with the same configuration.\n\n Returns:\n True if restart successful, False otherwise\n \"\"\"\n logger.info(f\"Restarting vLLM server for {self.model}\")\n\n # Stop if running\n if self.is_running():\n self.stop()\n time.sleep(2) # Wait a bit before restarting\n\n # Start again\n return self.start()\n\n def health_check(self) -> bool:\n \"\"\"\n Perform a health check on the server.\n\n Returns:\n True if server is healthy, False otherwise\n \"\"\"\n if not self.is_running():\n return False\n\n try:\n import requests\n\n # Try to connect to the server\n response = requests.get(f\"http://localhost:{self.port}/health\", timeout=5)\n\n return response.status_code == 200\n\n except Exception:\n # If requests fails, just check process\n return self.is_running()", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 27979}, "tests/test_environment_variables.py::442": {"resolved_imports": ["src/vllm_cli/config/manager.py", "src/vllm_cli/server/manager.py"], "used_names": ["Mock", "VLLMServer", "patch"], "enclosing_function": "test_complete_override_chain", "extracted_code": "# Source: src/vllm_cli/server/manager.py\nclass VLLMServer:\n \"\"\"\n Manages a vLLM server instance with comprehensive lifecycle control.\n\n This class handles the complete lifecycle of a vLLM server including\n configuration, process management, logging, monitoring, and cleanup.\n It supports both programmatically started servers and external server\n detection and management.\n\n Attributes:\n config: Server configuration dictionary\n model: Model name being served\n port: Port number the server is listening on\n process: Subprocess or external process reference\n log_file: File handle for server logs\n log_queue: Thread-safe queue for log lines\n log_thread: Background thread for log monitoring\n start_time: Timestamp when server was started\n log_path: Path to the server's log file\n \"\"\"\n\n def __init__(self, config: Dict[str, Any]) -> None:\n \"\"\"\n Initialize a vLLM server instance.\n\n Sets up the server configuration, logging infrastructure, and\n prepares the instance for server lifecycle management.\n\n Args:\n config: Server configuration dictionary containing model name,\n port, and other vLLM-specific parameters\n \"\"\"\n self.config: Dict[str, Any] = config\n\n # Extract model name - handle both string and dict (LoRA config) formats\n model_config = config.get(\"model\", \"unknown\")\n if isinstance(model_config, dict):\n # LoRA configuration - extract base model name\n self.model: str = model_config.get(\"model\", \"unknown\")\n else:\n # Regular string model name\n self.model: str = model_config\n\n self.port: int = config.get(\"port\", 8000)\n self.process: Optional[Union[subprocess.Popen, Any]] = None\n self.log_file: Optional[TextIO] = None\n self.log_queue: Queue[str] = Queue()\n self.log_thread: Optional[Thread] = None\n self.start_time: Optional[datetime] = None\n self.log_path: Path\n self._recent_logs: List[str] = []\n\n # Setup logging\n log_dir = Path.home() / \".vllm-cli\" / \"logs\"\n log_dir.mkdir(parents=True, exist_ok=True)\n\n timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n self.log_path = log_dir / f\"vllm_{self.model.replace('/', '_')}_{timestamp}.log\"\n\n def start(self) -> bool:\n \"\"\"\n Start the vLLM server.\n\n Returns:\n True if server started successfully, False otherwise\n \"\"\"\n if self.is_running():\n logger.warning(f\"Server already running for {self.model}\")\n return False\n\n try:\n # Build command - run directly without conda wrapper\n full_cmd = self._build_command()\n\n logger.info(f\"Starting vLLM server with command: {' '.join(full_cmd)}\")\n\n # Open log file for writing\n self.log_file = open(self.log_path, \"w\", buffering=1)\n\n # Start with parent environment\n env = os.environ.copy()\n # Note: No longer forcing PYTHONUNBUFFERED=1, let user control it\n\n # Layer 1: Apply universal environment variables from settings\n config_manager = ConfigManager()\n universal_env = config_manager.config.get(\"universal_environment\", {})\n if universal_env:\n logger.info(\n f\"Applying {len(universal_env)} universal environment variable(s)\"\n )\n for key, value in universal_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting universal {key}={value}\")\n else:\n logger.debug(f\"Setting universal {key}=\")\n\n # Layer 2: Apply profile environment variables (override universal)\n profile_env = self.config.get(\"profile_environment\", {})\n if profile_env:\n logger.info(\n f\"Applying {len(profile_env)} profile environment variable(s)\"\n )\n for key, value in profile_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting profile {key}={value}\")\n else:\n logger.debug(f\"Setting profile {key}=\")\n\n # Handle GPU device selection via CUDA_VISIBLE_DEVICES\n # This overrides any CUDA_VISIBLE_DEVICES from the profile\n if self.config.get(\"device\"):\n device_str = str(self.config[\"device\"])\n env[\"CUDA_VISIBLE_DEVICES\"] = device_str\n logger.info(f\"Setting CUDA_VISIBLE_DEVICES={device_str}\")\n\n # If using specific GPUs, adjust tensor parallel size if needed\n device_list = [d.strip() for d in device_str.split(\",\")]\n num_devices = len(device_list)\n\n # Check if tensor_parallel_size is set and compatible\n if self.config.get(\"tensor_parallel_size\"):\n tp_size = self.config[\"tensor_parallel_size\"]\n if tp_size > num_devices:\n logger.warning(\n f\"tensor_parallel_size ({tp_size}) > number of selected devices ({num_devices}). \"\n f\"Adjusting tensor_parallel_size to {num_devices}\"\n )\n self.config[\"tensor_parallel_size\"] = num_devices\n elif num_devices % tp_size != 0:\n logger.warning(\n f\"Number of GPUs ({num_devices}) is not evenly divisible by \"\n f\"tensor_parallel_size ({tp_size}). This may lead to inefficient GPU utilization. \"\n f\"Consider using tensor_parallel_size of: \"\n f\"{', '.join(str(i) for i in range(1, num_devices + 1) if num_devices % i == 0)}\"\n )\n\n # Add HuggingFace token if configured\n config_manager = ConfigManager()\n hf_token = config_manager.config.get(\"hf_token\")\n if hf_token:\n env[\"HF_TOKEN\"] = hf_token\n env[\"HUGGING_FACE_HUB_TOKEN\"] = hf_token # Some tools use this variant\n logger.info(\"HuggingFace token configured for server\")\n\n # Enable development mode for sleep endpoints if sleep mode is enabled\n if self.config.get(\"enable_sleep_mode\"):\n env[\"VLLM_SERVER_DEV_MODE\"] = \"1\"\n logger.info(\"Sleep mode enabled with development endpoints\")\n\n # Start the process with proper pipe configuration\n # Use start_new_session=True to create a new process group\n # This prevents the child process from receiving Ctrl+C signals\n self.process = subprocess.Popen(\n full_cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n text=True,\n bufsize=0, # Unbuffered\n universal_newlines=True,\n env=env,\n start_new_session=True, # Create new process group to isolate from parent signals\n )\n\n # Start log monitoring thread\n self._start_log_monitor()\n\n # Set start time and add to registry\n self.start_time = datetime.now()\n from .process import add_server\n\n add_server(self)\n\n # Return immediately - let the UI monitor the startup\n logger.info(\n f\"vLLM server process launched for {self.model} on port {self.port}\"\n )\n return True\n\n except Exception as e:\n logger.error(f\"Error starting vLLM server: {e}\")\n return False\n\n def _build_command(self) -> List[str]:\n \"\"\"\n Build the vLLM command from configuration using the schema.\n\n Returns:\n List of command arguments\n \"\"\"\n # Use the new ConfigManager to build CLI args\n config_manager = ConfigManager()\n\n # Start with the vllm command\n cmd = [\"vllm\"]\n\n # Add the arguments built from schema\n cli_args = config_manager.build_cli_args(self.config)\n cmd.extend(cli_args)\n\n # Handle extra_args if present (backward compatibility)\n if self.config.get(\"extra_args\"):\n self._add_extra_args_to_command(cmd)\n\n logger.debug(f\"Built command: {' '.join(cmd)}\")\n return cmd\n\n def _add_extra_args_to_command(self, cmd: List[str]) -> None:\n \"\"\"\n Add extra arguments to the vLLM command.\n\n Args:\n cmd: Command list to extend with extra arguments\n \"\"\"\n try:\n extra_args = shlex.split(self.config[\"extra_args\"])\n if extra_args:\n logger.info(f\"Adding extra arguments: {extra_args}\")\n cmd.extend(extra_args)\n except ValueError as e:\n logger.warning(f\"Failed to parse extra_args: {e}\")\n\n def _start_log_monitor(self) -> None:\n \"\"\"\n Start a thread to monitor log output from the vLLM server process.\n\n Creates a daemon thread that continuously reads stdout/stderr from\n the server process, writes to log files, and queues log lines for\n real-time display in the UI.\n \"\"\"\n self.log_thread = Thread(target=self._log_monitor_worker, daemon=True)\n self.log_thread.start()\n\n def _log_monitor_worker(self) -> None:\n \"\"\"\n Worker function for log monitoring thread.\n\n Continuously reads log output from the server process and handles\n file writing and queue management for UI display.\n \"\"\"\n try:\n self.log_queue.put(\"Starting vLLM server process...\")\n\n while self._should_continue_monitoring():\n if self._process_log_line():\n continue\n else:\n # No line read, check if process still running\n if self.process and self.process.poll() is not None:\n break\n time.sleep(0.01) # Small sleep to prevent busy waiting\n\n except Exception as e:\n logger.error(f\"Error in log monitor: {e}\")\n self.log_queue.put(f\"Log monitoring error: {e}\")\n\n def _should_continue_monitoring(self) -> bool:\n \"\"\"\n Check if log monitoring should continue.\n\n Returns:\n True if monitoring should continue, False otherwise\n \"\"\"\n return (\n self.is_running()\n and self.process\n and hasattr(self.process, \"stdout\")\n and self.process.stdout\n )\n\n def _process_log_line(self) -> bool:\n \"\"\"\n Process a single log line from the server output.\n\n Reads one line from the process stdout, writes it to the log file,\n and adds it to the queue for UI display after filtering and formatting.\n\n Returns:\n True if a line was processed, False if no line was available\n \"\"\"\n if not (self.process and self.process.stdout):\n return False\n\n line = self.process.stdout.readline()\n if not line:\n return False\n\n # Write to log file\n self._write_to_log_file(line)\n\n # Process for UI display\n line_stripped = line.strip()\n if line_stripped and self._should_display_log_line(line_stripped):\n # Truncate overly long lines\n if len(line_stripped) > 200:\n line_stripped = line_stripped[:197] + \"...\"\n\n self.log_queue.put(line_stripped)\n logger.debug(f\"Log captured: {line_stripped[:50]}...\")\n\n return True\n\n def _write_to_log_file(self, line: str) -> None:\n \"\"\"\n Write a log line to the log file.\n\n Args:\n line: Log line to write\n \"\"\"\n if self.log_file and not self.log_file.closed:\n self.log_file.write(line)\n self.log_file.flush()\n\n def _should_display_log_line(self, line: str) -> bool:\n \"\"\"\n Determine if a log line should be displayed in the UI.\n\n Filters out certain system messages that are not useful for users.\n\n Args:\n line: Stripped log line to check\n\n Returns:\n True if the line should be displayed, False otherwise\n \"\"\"\n # Filter out conda activation and system messages\n filtered_messages = [\n \"Activated CUDA\",\n \"Using nvcc from:\",\n \"Cuda compilation tools\",\n ]\n return not any(skip in line for skip in filtered_messages)\n\n def stop(self) -> bool:\n \"\"\"\n Stop the vLLM server.\n\n Returns:\n True if server stopped successfully, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n try:\n # Check if this is an external server\n if hasattr(self.process, \"terminate\"):\n # Normal subprocess\n # Since we created a new session, we need to terminate the entire process group\n try:\n # Get the process group ID (pgid)\n # Since we used start_new_session=True, the pgid is the same as the pid\n pgid = self.process.pid\n\n # Send SIGTERM to the entire process group for graceful shutdown\n logger.info(f\"Sending SIGTERM to process group {pgid}\")\n os.killpg(pgid, signal.SIGTERM)\n\n # Wait for process to terminate\n try:\n self.process.wait(timeout=10)\n logger.info(f\"Process group {pgid} terminated gracefully\")\n except subprocess.TimeoutExpired:\n # Force kill if not terminated\n logger.warning(\n f\"Process group {pgid} did not terminate, sending SIGKILL\"\n )\n os.killpg(pgid, signal.SIGKILL)\n self.process.wait()\n logger.info(f\"Process group {pgid} force killed\")\n\n except ProcessLookupError:\n # Process already dead\n logger.info(\"Process already terminated\")\n except PermissionError as e:\n # Fall back to terminating just the process\n logger.warning(\n f\"Permission denied for process group kill: {e}, falling back to process termination\"\n )\n self.process.terminate()\n try:\n self.process.wait(timeout=10)\n except subprocess.TimeoutExpired:\n self.process.kill()\n self.process.wait()\n elif hasattr(self.process, \"pid\"):\n # External server - kill entire process group or individual process\n try:\n pgid = self.process.pid\n killed = False\n\n # First attempt: try to kill process group\n try:\n os.killpg(pgid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process group {pgid}\")\n killed = True\n except (OSError, ProcessLookupError) as e:\n # Process group kill failed, try individual process\n logger.debug(\n f\"Process group kill failed: {e}, trying individual process\"\n )\n try:\n # Ensure pid is an integer (handle Mock objects)\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process {self.process.pid}\")\n killed = True\n except ProcessLookupError:\n # Process already dead\n logger.info(\n f\"Process {self.process.pid} already terminated\"\n )\n except OSError as e:\n logger.warning(\n f\"Failed to send SIGTERM to {self.process.pid}: {e}\"\n )\n\n if killed:\n # Wait for graceful shutdown\n time.sleep(2)\n\n # Check if still running and force kill if needed\n if self.is_running():\n try:\n os.killpg(pgid, signal.SIGKILL)\n logger.info(f\"Force killed process group {pgid}\")\n except (OSError, ProcessLookupError):\n # Process group kill failed, try individual\n try:\n # Ensure pid is an integer (handle Mock objects in tests)\n if hasattr(self.process, \"pid\"):\n try:\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGKILL)\n logger.info(f\"Force killed process {pid}\")\n except (TypeError, ValueError):\n # PID is not a valid integer (might be Mock)\n pass\n except ProcessLookupError:\n pass # Already dead\n except OSError as e:\n logger.error(\n f\"Failed to force kill {self.process.pid}: {e}\"\n )\n\n except Exception as e:\n logger.error(f\"Unexpected error stopping external server: {e}\")\n\n # Close log file if we have one\n if hasattr(self, \"log_file\") and self.log_file:\n self.log_file.close()\n\n # Remove from registry\n from .process import remove_server\n\n remove_server(self)\n\n logger.info(f\"vLLM server stopped for {self.model}\")\n return True\n\n except Exception as e:\n logger.error(f\"Error stopping vLLM server: {e}\")\n return False\n\n def is_running(self) -> bool:\n \"\"\"\n Check if the server is running.\n\n Returns:\n True if server is running, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n # Check if this is an external server (detected, not started by us)\n if hasattr(self.process, \"poll\"):\n # Normal subprocess\n return self.process.poll() is None\n elif hasattr(self.process, \"pid\"):\n # External server - check if PID still exists\n try:\n import psutil\n\n return psutil.pid_exists(self.process.pid)\n except ImportError:\n # Fallback to os method\n try:\n os.kill(self.process.pid, 0)\n return True\n except (OSError, ProcessLookupError):\n return False\n\n return False\n\n def get_status(self) -> Dict[str, Any]:\n \"\"\"\n Get server status information.\n\n Returns:\n Dictionary with status information\n \"\"\"\n status = {\n \"model\": self.model,\n \"port\": self.port,\n \"running\": self.is_running(),\n \"pid\": self.process.pid if self.process else None,\n \"start_time\": self.start_time.isoformat() if self.start_time else None,\n \"log_path\": str(self.log_path) if self.log_path else None,\n }\n\n if self.is_running() and self.start_time:\n uptime = datetime.now() - self.start_time\n status[\"uptime_seconds\"] = uptime.total_seconds()\n status[\"uptime_str\"] = str(uptime).split(\".\")[0]\n\n return status\n\n def wait_for_startup(self) -> bool:\n \"\"\"\n Wait for the server to complete startup.\n\n Monitors the server logs for startup completion indicators and verifies\n via HTTP endpoint. Will wait indefinitely until either startup completes\n or the process terminates.\n\n Returns:\n True if server started successfully, False if process terminated\n \"\"\"\n import time\n\n logger.info(f\"Waiting for {self.model} server to complete startup...\")\n\n # Track if we've seen startup indicators in logs\n log_indicates_ready = False\n\n while True:\n # Check if server is still running\n if not self.is_running():\n logger.error(\n f\"Server process for {self.model} terminated during startup\"\n )\n return False\n\n # Get recent logs to check for startup completion\n recent_logs = self.get_recent_logs(50)\n\n if recent_logs and not log_indicates_ready:\n # Check for startup completion indicators\n for log in recent_logs:\n log_lower = log.lower()\n # Look for the explicit \"Application startup complete\" message\n if \"application startup complete\" in log_lower:\n logger.debug(f\"Server {self.model} startup detected in logs\")\n log_indicates_ready = True\n break\n\n # Also check for other ready indicators as fallback\n if any(\n indicator in log_lower\n for indicator in [\n \"uvicorn running on\",\n \"started server process\",\n \"server is ready\",\n \"api server started\",\n ]\n ):\n logger.debug(\n f\"Server {self.model} startup detected via ready indicator\"\n )\n log_indicates_ready = True\n break\n\n # If logs indicate ready, verify via HTTP\n if log_indicates_ready:\n # Try to verify server is actually ready via HTTP\n port = self.config.get(\"port\")\n if port:\n try:\n import httpx\n\n with httpx.Client() as client:\n # Try /v1/models endpoint first (most reliable)\n response = client.get(\n f\"http://localhost:{port}/v1/models\", timeout=5.0\n )\n if response.status_code == 200:\n logger.info(\n f\"Server {self.model} startup complete \"\n \"(verified via HTTP)\"\n )\n return True\n except httpx.ConnectError:\n # Server not ready yet, continue waiting\n logger.debug(\n f\"Server {self.model} not accepting connections yet\"\n )\n except Exception as e:\n # Log but continue, might be network issue\n logger.debug(f\"HTTP verification failed: {e}\")\n else:\n # No port configured, trust the logs\n logger.info(\n f\"Server {self.model} startup complete (no port for verification)\"\n )\n return True\n\n # Small sleep to avoid busy waiting\n time.sleep(0.5)\n\n def get_recent_logs(self, n: int = 20) -> List[str]:\n \"\"\"\n Get recent log lines from the server output.\n\n Retrieves the most recent log lines from either the in-memory queue\n or the log file on disk. This method ensures logs are available even\n after the monitoring thread has processed them.\n\n Args:\n n: Number of recent lines to return (default: 20)\n\n Returns:\n List of recent log lines, with the most recent last\n \"\"\"\n # Update recent logs from queue\n self._update_recent_logs_from_queue()\n\n # Return from memory if available\n if self._recent_logs:\n return self._recent_logs[-n:]\n\n # Fallback to reading from file\n return self._read_logs_from_file(n)\n\n def _update_recent_logs_from_queue(self) -> None:\n \"\"\"\n Update the recent logs cache from the log queue.\n\n Drains all available log lines from the queue and adds them\n to the recent logs cache, maintaining a maximum of 100 lines.\n \"\"\"\n temp_logs = []\n\n # Get all available logs from queue (don't block)\n while not self.log_queue.empty():\n try:\n log_line = self.log_queue.get_nowait()\n temp_logs.append(log_line)\n except Empty:\n break\n\n if temp_logs:\n self._recent_logs.extend(temp_logs)\n # Keep only the last 100 logs in memory to prevent unbounded growth\n self._recent_logs = self._recent_logs[-100:]\n\n def _read_logs_from_file(self, n: int) -> List[str]:\n \"\"\"\n Read recent log lines from the log file.\n\n Args:\n n: Number of lines to read\n\n Returns:\n List of log lines from file\n \"\"\"\n if not (self.log_path and self.log_path.exists()):\n return []\n\n try:\n with open(self.log_path, \"r\") as f:\n file_logs = f.readlines()\n if file_logs:\n # Get last n lines, strip them\n logs = [line.strip() for line in file_logs[-n:]]\n # Update recent logs cache\n self._recent_logs = logs[-100:]\n return logs\n except Exception as e:\n logger.debug(f\"Error reading log file: {e}\")\n\n return []\n\n def restart(self) -> bool:\n \"\"\"\n Restart the server with the same configuration.\n\n Returns:\n True if restart successful, False otherwise\n \"\"\"\n logger.info(f\"Restarting vLLM server for {self.model}\")\n\n # Stop if running\n if self.is_running():\n self.stop()\n time.sleep(2) # Wait a bit before restarting\n\n # Start again\n return self.start()\n\n def health_check(self) -> bool:\n \"\"\"\n Perform a health check on the server.\n\n Returns:\n True if server is healthy, False otherwise\n \"\"\"\n if not self.is_running():\n return False\n\n try:\n import requests\n\n # Try to connect to the server\n response = requests.get(f\"http://localhost:{self.port}/health\", timeout=5)\n\n return response.status_code == 200\n\n except Exception:\n # If requests fails, just check process\n return self.is_running()", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 27979}, "tests/proxy/test_e2e.py::592": {"resolved_imports": ["src/vllm_cli/proxy/manager.py", "src/vllm_cli/proxy/models.py", "src/vllm_cli/proxy/server.py"], "used_names": ["ProxyConfig", "ProxyServer", "asyncio", "datetime", "pytest"], "enclosing_function": "test_e2e_stale_entry_cleanup_with_refresh", "extracted_code": "# Source: src/vllm_cli/proxy/models.py\nclass ProxyConfig(BaseModel):\n \"\"\"Configuration for the proxy server.\"\"\"\n\n host: str = Field(\"0.0.0.0\", description=\"Proxy server host\") # nosec B104\n port: int = Field(8000, description=\"Proxy server port\")\n models: List[ModelConfig] = Field(\n default_factory=list, description=\"List of models to serve\"\n )\n enable_cors: bool = Field(True, description=\"Enable CORS headers\")\n enable_metrics: bool = Field(True, description=\"Enable metrics endpoint\")\n log_requests: bool = Field(False, description=\"Log all requests\")\n\n\n# Source: src/vllm_cli/proxy/server.py\nclass ProxyServer:\n \"\"\"\n FastAPI proxy server that routes OpenAI API requests to appropriate vLLM instances.\n \"\"\"\n\n def __init__(self, config: ProxyConfig):\n \"\"\"Initialize the proxy server with configuration.\"\"\"\n self.config = config\n self.app = FastAPI(title=\"vLLM Multi-Model Proxy\", version=\"0.1.0\")\n self.router = RequestRouter()\n self.registry = ModelRegistry() # Dynamic runtime registry\n self.start_time = datetime.now()\n self.total_requests = 0\n self.model_requests: Dict[str, int] = {}\n\n # HTTP client for forwarding requests\n self.client = httpx.AsyncClient(timeout=httpx.Timeout(timeout=300.0))\n\n # Setup middleware and routes\n self._setup_middleware()\n self._setup_routes()\n\n def _setup_middleware(self):\n \"\"\"Configure middleware for the FastAPI app.\"\"\"\n if self.config.enable_cors:\n self.app.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n )\n\n # Request logging middleware\n if self.config.log_requests:\n\n @self.app.middleware(\"http\")\n async def log_requests(request: Request, call_next):\n start_time = time.time()\n response = await call_next(request)\n duration = time.time() - start_time\n logger.info(\n f\"{request.method} {request.url.path} - \"\n f\"{response.status_code} - {duration:.3f}s\"\n )\n return response\n\n def _setup_routes(self):\n \"\"\"Setup API routes for the proxy server.\"\"\"\n\n @self.app.get(\"/\")\n async def root():\n \"\"\"Root endpoint.\"\"\"\n return {\n \"message\": \"vLLM Multi-Model Proxy Server\",\n \"version\": \"0.1.0\",\n \"models_count\": len(self.router.get_active_models()),\n }\n\n @self.app.get(\"/health\")\n async def health():\n \"\"\"Health check endpoint.\"\"\"\n return {\"status\": \"healthy\", \"timestamp\": datetime.now().isoformat()}\n\n @self.app.get(\"/v1/models\")\n async def list_models():\n \"\"\"List available models (OpenAI API compatible).\"\"\"\n models = self.router.get_active_models()\n return {\n \"object\": \"list\",\n \"data\": [\n {\n \"id\": model_name,\n \"object\": \"model\",\n \"created\": int(time.time()),\n \"owned_by\": \"vllm-cli-proxy\",\n }\n for model_name in models\n ],\n }\n\n @self.app.post(\"/v1/chat/completions\")\n async def chat_completions(request: Request):\n \"\"\"Handle chat completions requests.\"\"\"\n return await self._forward_request(request, \"/v1/chat/completions\")\n\n @self.app.post(\"/v1/completions\")\n async def completions(request: Request):\n \"\"\"Handle completions requests.\"\"\"\n return await self._forward_request(request, \"/v1/completions\")\n\n @self.app.post(\"/v1/embeddings\")\n async def embeddings(request: Request):\n \"\"\"Handle embeddings requests.\"\"\"\n return await self._forward_request(request, \"/v1/embeddings\")\n\n @self.app.post(\"/v1/responses\")\n async def responses(request: Request):\n \"\"\"Handle responses requests (OpenAI Responses API).\"\"\"\n return await self._forward_request(request, \"/v1/responses\")\n\n @self.app.get(\"/proxy/status\")\n async def proxy_status():\n \"\"\"Get proxy server status.\"\"\"\n models_status = []\n\n # Get models from registry\n for port, model_entry in self.registry.get_all_models().items():\n models_status.append(\n ModelStatus(\n name=model_entry.display_name,\n model_path=\"\", # Not tracked in registry\n port=port,\n gpu_ids=model_entry.gpu_ids,\n status=(\n \"running\"\n if model_entry.state.value == \"running\"\n else \"stopped\"\n ),\n registration_status=model_entry.status.value,\n request_count=0, # Not tracked in simplified registry\n )\n )\n\n return ProxyStatus(\n proxy_running=True,\n proxy_port=self.config.port,\n proxy_host=self.config.host,\n models=models_status,\n total_requests=self.total_requests,\n start_time=self.start_time.isoformat(),\n )\n\n @self.app.post(\"/proxy/pre_register\")\n async def pre_register(request: Dict[str, Any]):\n \"\"\"Pre-register a model with pending status.\"\"\"\n try:\n port = request[\"port\"]\n gpu_ids = request.get(\"gpu_ids\", [])\n config_name = request.get(\"config_name\")\n request.get(\"estimated_util\")\n\n logger.info(\n f\"Pre-registering model '{config_name}' on port {port} \"\n f\"with GPUs {gpu_ids}\"\n )\n\n # Pre-register in the runtime registry\n success = self.registry.pre_register(port, gpu_ids, config_name)\n\n if success:\n logger.info(f\"Pre-registered model on port {port}\")\n return {\n \"status\": \"success\",\n \"message\": f\"Pre-registered model on port {port}\",\n }\n else:\n message = f\"Failed to pre-register model on port {port}\"\n logger.error(message)\n raise HTTPException(status_code=400, detail=message)\n\n except Exception as e:\n logger.error(f\"Pre-registration error: {e}\")\n raise HTTPException(status_code=400, detail=str(e))\n\n @self.app.post(\"/proxy/register\")\n async def register_model(request: Dict[str, Any]):\n \"\"\"Register a new model in the runtime registry (backward compatibility).\"\"\"\n try:\n port = request[\"port\"]\n gpu_ids = request.get(\"gpu_ids\", [])\n actual_name = request.get(\"actual_name\", f\"model_{port}\")\n\n # Register in the runtime registry\n success = self.registry.verify_and_activate(port, actual_name)\n\n if success:\n # Add to router for request routing\n backend_url = f\"http://localhost:{port}\"\n self.router.add_backend(\n actual_name, backend_url, {\"port\": port, \"gpu_ids\": gpu_ids}\n )\n\n return {\n \"status\": \"success\",\n \"message\": f\"Registered model '{actual_name}' on port {port}\",\n \"actual_name\": actual_name,\n }\n else:\n message = f\"Failed to register model on port {port}\"\n raise HTTPException(status_code=400, detail=message)\n\n except Exception as e:\n raise HTTPException(status_code=400, detail=str(e))\n\n @self.app.delete(\"/proxy/models/{port}\")\n async def unregister_model(port: int):\n \"\"\"Unregister a model from the runtime registry.\"\"\"\n try:\n # Get model info before unregistering\n model_entry = self.registry.get_model(port)\n if not model_entry:\n raise HTTPException(\n status_code=404, detail=f\"Model on port {port} not found\"\n )\n\n # Unregister from registry\n success = self.registry.remove_model(port)\n message = (\n f\"Model on port {port} unregistered\"\n if success\n else f\"Model on port {port} not found\"\n )\n\n if success:\n # Remove from router\n if model_entry.actual_name:\n try:\n self.router.remove_backend(model_entry.actual_name)\n except Exception:\n pass # Router entry might not exist\n\n return {\"status\": \"success\", \"message\": message}\n else:\n raise HTTPException(status_code=400, detail=message)\n\n except HTTPException:\n raise\n except Exception as e:\n raise HTTPException(status_code=400, detail=str(e))\n\n @self.app.post(\"/proxy/state\")\n async def update_model_state(request: Dict[str, Any]):\n \"\"\"Update the state of a model (running/sleeping/stopped).\"\"\"\n try:\n port = request[\"port\"]\n state = request[\"state\"]\n sleep_level = request.get(\"sleep_level\", 0)\n\n # Update model state\n model_entry = self.registry.get_model(port)\n if model_entry:\n from .registry import ModelState\n\n if state == \"sleeping\":\n model_entry.state = ModelState.SLEEPING\n model_entry.sleep_level = sleep_level\n elif state == \"running\":\n model_entry.state = ModelState.RUNNING\n model_entry.sleep_level = 0\n elif state == \"stopped\":\n model_entry.state = ModelState.STOPPED\n message = f\"Updated state to {state}\"\n return {\"status\": \"success\", \"message\": message}\n else:\n raise HTTPException(\n status_code=404, detail=f\"Model on port {port} not found\"\n )\n\n except Exception as e:\n raise HTTPException(status_code=400, detail=str(e))\n\n @self.app.get(\"/proxy/registry\")\n async def get_registry():\n \"\"\"Get the complete registry status including GPU allocation.\"\"\"\n return self.registry.get_status_summary()\n\n @self.app.post(\"/proxy/refresh_models\")\n async def refresh_models():\n \"\"\"\n Refresh model registry - verify ALL models and update their status.\n \"\"\"\n import httpx\n\n from .registry import ModelState, RegistrationStatus\n\n # Cleanup any stale entries\n removed_count = self.registry.cleanup_stale_entries()\n if removed_count > 0:\n logger.info(f\"Removed {removed_count} stale entries\")\n\n # Get all models and check their status\n all_models = self.registry.get_all_models()\n newly_registered = []\n already_available = []\n newly_failed = []\n pending_count = 0\n\n for port, model_entry in all_models.items():\n # Check ALL models\n try:\n # Call the model's /v1/models endpoint\n async with httpx.AsyncClient() as client:\n response = await client.get(\n f\"http://localhost:{port}/v1/models\", timeout=5.0\n )\n\n if response.status_code == 200:\n # Model is responding\n # Always check if model is sleeping\n # (not just when marked as sleeping)\n is_sleeping = False\n try:\n sleep_response = await client.get(\n f\"http://localhost:{port}/is_sleeping\", timeout=2.0\n )\n if sleep_response.status_code == 200:\n sleep_data = sleep_response.json()\n is_sleeping = sleep_data.get(\"is_sleeping\", False)\n\n # Update model state based on actual sleep status\n if (\n is_sleeping\n and model_entry.state != ModelState.SLEEPING\n ):\n model_entry.state = ModelState.SLEEPING\n logger.info(f\"Model on port {port} is sleeping\")\n elif (\n not is_sleeping\n and model_entry.state == ModelState.SLEEPING\n ):\n model_entry.state = ModelState.RUNNING\n logger.info(\n f\"Model on port {port} has been woken up\"\n )\n elif not is_sleeping:\n model_entry.state = ModelState.RUNNING\n except Exception:\n # If /is_sleeping endpoint doesn't exist or fails,\n # check current state. If it was sleeping, keep it as\n # sleeping; otherwise assume running\n if model_entry.state != ModelState.SLEEPING:\n model_entry.state = ModelState.RUNNING\n\n # Extract actual model name from response\n models_data = response.json()\n actual_name = None\n if models_data.get(\"data\"):\n actual_name = models_data[\"data\"][0].get(\"id\")\n\n # Check previous status\n was_pending = (\n model_entry.status == RegistrationStatus.PENDING\n )\n was_error = model_entry.status == RegistrationStatus.ERROR\n\n # Verify and activate the model\n if self.registry.verify_and_activate(port, actual_name):\n if was_pending or was_error:\n newly_registered.append(\n actual_name or f\"port_{port}\"\n )\n else:\n already_available.append(\n actual_name or f\"port_{port}\"\n )\n\n # Ensure it's in the router\n if (\n actual_name\n and actual_name not in self.router.backends\n ):\n backend_url = f\"http://localhost:{port}\"\n self.router.add_backend(\n actual_name,\n backend_url,\n {\n \"port\": port,\n \"gpu_ids\": model_entry.gpu_ids,\n },\n )\n logger.debug(\n f\"Model on port {port} verified as available\"\n )\n else:\n # Model not responding properly\n if model_entry.status == RegistrationStatus.AVAILABLE:\n # Was available, now failing\n model_entry.mark_error(f\"HTTP {response.status_code}\")\n newly_failed.append(model_entry.display_name)\n # Remove from router if present\n if model_entry.actual_name in self.router.backends:\n self.router.remove_backend(model_entry.actual_name)\n else:\n pending_count += 1\n\n except Exception as e:\n # Model not accessible\n if model_entry.status == RegistrationStatus.AVAILABLE:\n # Was available, now failing\n model_entry.mark_error(\n str(e)[:100]\n ) # Limit error message length\n newly_failed.append(model_entry.display_name)\n # Remove from router if present\n if (\n model_entry.actual_name\n and model_entry.actual_name in self.router.backends\n ):\n self.router.remove_backend(model_entry.actual_name)\n logger.warning(\n f\"Model on port {port} no longer accessible: {e}\"\n )\n elif model_entry.status == RegistrationStatus.PENDING:\n pending_count += 1\n logger.debug(f\"Model on port {port} still not ready: {e}\")\n\n summary = {\n \"registered\": len(newly_registered),\n \"already_available\": len(already_available),\n \"failed\": len(newly_failed),\n \"pending\": pending_count,\n \"removed\": removed_count,\n \"total\": len(all_models),\n }\n\n return {\n \"status\": \"success\",\n \"summary\": summary,\n \"details\": {\n \"newly_registered\": newly_registered,\n \"already_available\": already_available,\n \"newly_failed\": newly_failed,\n },\n }\n\n if self.config.enable_metrics:\n\n @self.app.get(\"/metrics\")\n async def metrics():\n \"\"\"Prometheus-compatible metrics endpoint.\"\"\"\n metrics_text = []\n metrics_text.append(\n \"# HELP proxy_requests_total Total requests to proxy\"\n )\n metrics_text.append(\"# TYPE proxy_requests_total counter\")\n metrics_text.append(f\"proxy_requests_total {self.total_requests}\")\n\n metrics_text.append(\"# HELP model_requests_total Requests per model\")\n metrics_text.append(\"# TYPE model_requests_total counter\")\n for model, count in self.model_requests.items():\n metrics_text.append(\n f'model_requests_total{{model=\"{model}\"}} {count}'\n )\n\n uptime = (datetime.now() - self.start_time).total_seconds()\n metrics_text.append(\n \"# HELP proxy_uptime_seconds Proxy uptime in seconds\"\n )\n metrics_text.append(\"# TYPE proxy_uptime_seconds gauge\")\n metrics_text.append(f\"proxy_uptime_seconds {uptime}\")\n\n return \"\\n\".join(metrics_text)\n\n async def _forward_request(self, request: Request, endpoint: str):\n \"\"\"\n Forward a request to the appropriate vLLM backend.\n\n Args:\n request: Incoming FastAPI request\n endpoint: Target endpoint path\n\n Returns:\n Response from the backend server\n \"\"\"\n try:\n # Parse request body\n body = await request.body()\n json_body = json.loads(body) if body else {}\n\n # Extract model from request\n model_name = json_body.get(\"model\")\n if not model_name:\n raise HTTPException(\n status_code=400, detail=\"Missing 'model' field in request\"\n )\n\n # Get backend URL for this model\n backend_url = self.router.route_request(model_name)\n if not backend_url:\n raise HTTPException(\n status_code=404, detail=f\"Model '{model_name}' not found\"\n )\n\n # Update request counters\n self.total_requests += 1\n self.model_requests[model_name] = self.model_requests.get(model_name, 0) + 1\n\n # Check if streaming is requested\n stream = json_body.get(\"stream\", False)\n\n # Forward the request\n target_url = f\"{backend_url}{endpoint}\"\n headers = dict(request.headers)\n headers.pop(\"host\", None) # Remove host header\n\n if stream:\n # Handle streaming response\n return StreamingResponse(\n self._stream_response(target_url, headers, body),\n media_type=\"text/event-stream\",\n )\n else:\n # Handle regular response\n response = await self.client.post(\n target_url, headers=headers, content=body\n )\n\n if response.status_code != 200:\n raise HTTPException(\n status_code=response.status_code, detail=response.text\n )\n\n return JSONResponse(\n content=response.json(), status_code=response.status_code\n )\n\n except HTTPException:\n raise\n except Exception as e:\n logger.error(f\"Error forwarding request: {e}\")\n raise HTTPException(status_code=500, detail=str(e))\n\n async def _stream_response(\n self, url: str, headers: Dict, body: bytes\n ) -> AsyncGenerator[bytes, None]:\n \"\"\"\n Stream response from backend server.\n\n Args:\n url: Target URL\n headers: Request headers\n body: Request body\n\n Yields:\n Chunks of response data\n \"\"\"\n try:\n async with self.client.stream(\n \"POST\", url, headers=headers, content=body\n ) as response:\n async for chunk in response.aiter_bytes():\n yield chunk\n except Exception as e:\n logger.error(f\"Error streaming response: {e}\")\n yield f'data: {{\"error\": \"{str(e)}\"}}\\n\\n'.encode()\n\n async def _check_backend_health(self, port: int) -> str:\n \"\"\"\n Check health of a backend server.\n\n Args:\n port: Backend server port\n\n Returns:\n Status string: \"running\", \"error\", or \"unknown\"\n \"\"\"\n try:\n response = await self.client.get(\n f\"http://localhost:{port}/health\", timeout=5.0\n )\n return \"running\" if response.status_code == 200 else \"error\"\n except Exception:\n return \"unknown\"\n\n def run(self):\n \"\"\"Run the proxy server.\"\"\"\n import uvicorn\n\n logger.info(f\"Starting proxy server on {self.config.host}:{self.config.port}\")\n\n uvicorn.run(\n self.app, host=self.config.host, port=self.config.port, log_level=\"info\"\n )\n\n async def shutdown(self):\n \"\"\"Cleanup resources on shutdown.\"\"\"\n await self.client.aclose()", "n_imports_parsed": 14, "n_files_resolved": 3, "n_chars_extracted": 24537}, "tests/test_ollama_support.py::138": {"resolved_imports": ["src/vllm_cli/models/discovery.py", "src/vllm_cli/models/manager.py", "src/vllm_cli/ui/model_manager.py"], "used_names": ["patch", "pytest", "select_model"], "enclosing_function": "test_select_ollama_model_format", "extracted_code": "# Source: src/vllm_cli/ui/model_manager.py\ndef select_model() -> Optional[Any]:\n \"\"\"\n Select a model from available models with provider categorization.\n Can return either a string (model name) or a dict (model with LoRA config).\n \"\"\"\n console.print(\"\\n[bold cyan]Model Selection[/bold cyan]\")\n\n try:\n # First, ask if user wants to use local or remote model\n model_source_choices = [\n \"Select from local models\",\n \"Serve model with LoRA adapters\",\n \"Use a model from HuggingFace Hub (auto-download)\",\n ]\n\n source_choice = unified_prompt(\n \"model_source\",\n \"How would you like to select a model?\",\n model_source_choices,\n allow_back=True,\n )\n\n if not source_choice or source_choice == \"BACK\":\n return None\n\n if source_choice == \"Use a model from HuggingFace Hub (auto-download)\":\n return enter_remote_model()\n\n if source_choice == \"Serve model with LoRA adapters\":\n return select_model_with_lora()\n\n # Continue with local model selection\n console.print(\"\\n[bold cyan]Fetching available models...[/bold cyan]\")\n models = list_available_models()\n\n if not models:\n console.print(\"[yellow]No local models found.[/yellow]\")\n console.print(\"\\nYou can either:\")\n console.print(\" 1. Download models using HuggingFace tools\")\n console.print(\" 2. Go back and select 'Use a model from HuggingFace Hub'\")\n input(\"\\nPress Enter to continue...\")\n return None\n\n # Group models by provider\n providers_dict = {}\n for model in models:\n # Special handling for Ollama models\n if model.get(\"type\") == \"ollama_model\":\n provider = \"ollama\"\n else:\n provider = model.get(\"publisher\", \"unknown\")\n if provider == \"unknown\" or not provider:\n # Try to extract provider from model name\n if \"/\" in model[\"name\"]:\n provider = model[\"name\"].split(\"/\")[0]\n else:\n provider = \"local\"\n\n if provider not in providers_dict:\n providers_dict[provider] = []\n providers_dict[provider].append(model)\n\n # Separate local provider from others\n local_provider = None\n other_providers = []\n\n for provider in providers_dict.keys():\n if provider == \"local\":\n local_provider = provider\n else:\n other_providers.append(provider)\n\n # Sort other providers alphabetically\n other_providers.sort()\n\n # Build provider choices with separation\n provider_choices = []\n\n # Add other providers first\n for provider in other_providers:\n count = len(providers_dict[provider])\n provider_choices.append(\n f\"{provider} ({count} model{'s' if count > 1 else ''})\"\n )\n\n # Add separator and local provider at the bottom if it exists\n if local_provider:\n # Add separator if there are other providers\n if other_providers:\n provider_choices.append(\"─\" * 30)\n count = len(providers_dict[local_provider])\n provider_choices.append(\n f\"{local_provider} ({count} model{'s' if count > 1 else ''})\"\n )\n\n # Count total providers (excluding separator)\n total_providers = len(providers_dict)\n\n selected_provider = unified_prompt(\n \"provider\",\n f\"Select Provider ({total_providers} available)\",\n provider_choices,\n allow_back=True,\n )\n\n if not selected_provider or selected_provider == \"BACK\":\n return None\n\n # Check if separator was selected (shouldn't happen, but handle it)\n if selected_provider.startswith(\"─\"):\n # Retry selection\n return select_model()\n\n # Extract provider name\n provider_name = selected_provider.split(\" (\")[0]\n\n # Now show models for selected provider\n provider_models = providers_dict[provider_name]\n\n # Create model choices for selected provider\n model_choices = []\n for model in provider_models:\n size_str = format_size(model.get(\"size\", 0))\n # Show only the model name without provider if it's already in the name\n display_name = model[\"name\"]\n if display_name.startswith(f\"{provider_name}/\"):\n display_name = display_name[len(provider_name) + 1 :] # noqa: E203\n model_choices.append(f\"{display_name} ({size_str})\")\n\n # Show model selection for the provider\n selected = unified_prompt(\n \"model\",\n f\"Select {provider_name} Model ({len(provider_models)} available)\",\n model_choices,\n allow_back=True,\n )\n\n if not selected or selected == \"BACK\":\n # Go back to provider selection\n return select_model()\n\n # Extract model name and reconstruct full name if needed\n model_display_name = selected.split(\" (\")[0]\n\n # Find the full model and return appropriate identifier\n for model in provider_models:\n check_name = model[\"name\"]\n if check_name.startswith(f\"{provider_name}/\"):\n check_name = check_name[len(provider_name) + 1 :] # noqa: E203\n if check_name == model_display_name or model[\"name\"] == model_display_name:\n # Special handling for Ollama models\n if model.get(\"type\") == \"ollama_model\":\n console.print(\"\\n[yellow]⚠ Warning: Ollama GGUF Model[/yellow]\")\n console.print(\n \"GGUF support in vLLM is experimental and varies by model architecture.\"\n )\n console.print(\n \"\\n[cyan]Important:[/cyan] Not all GGUF models are supported.\"\n )\n console.print(\"\\nFor compatibility information, see:\")\n console.print(\n \" • vLLM-CLI Guide: [cyan]https://github.com/Chen-zexi/vllm-cli/blob/main/docs/ollama-integration.md[/cyan]\"\n )\n console.print(\n \" • vLLM Docs: [cyan]https://docs.vllm.ai/en/latest/models/supported_models.html[/cyan]\"\n )\n\n console.print(\n \"\\n[cyan]Continue with this model? (Y/n):[/cyan] \", end=\"\"\n )\n confirm = input().strip().lower()\n if confirm not in [\"\", \"y\", \"yes\"]:\n return select_model() # Go back to selection\n\n # Return the GGUF file path with all metadata including name\n return {\n \"model\": model[\"path\"],\n \"path\": model[\"path\"], # Include path\n \"served_model_name\": model[\n \"name\"\n ], # Use correct field name for vLLM\n \"type\": \"ollama_model\", # Preserve type\n \"quantization\": \"gguf\",\n \"experimental\": True,\n }\n\n # For custom models, always use path regardless of publisher\n # Custom models are identified by their type\n if model.get(\"type\") == \"custom_model\" and model.get(\"path\"):\n return model[\"path\"]\n\n # For non-HF pattern models (local), also use path\n model_name = model[\"name\"]\n if model.get(\"path\") and (\n \"/\" not in model_name # No HF org/model pattern\n or model_name.startswith(\"/\") # Absolute path\n or model.get(\"publisher\")\n in [\"local\", \"unknown\", None] # Local publisher\n ):\n return model[\"path\"]\n return model[\"name\"]\n\n # Fallback\n return model_display_name\n\n except Exception as e:\n logger.error(f\"Error selecting model: {e}\")\n console.print(f\"[red]Error selecting model: {e}[/red]\")\n return None", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 8433}, "tests/test_profiles.py::33": {"resolved_imports": ["src/vllm_cli/config/profiles.py"], "used_names": ["Path", "ProfileManager", "patch"], "enclosing_function": "test_load_default_profiles", "extracted_code": "# Source: src/vllm_cli/config/profiles.py\nclass ProfileManager:\n \"\"\"\n Manages user profiles for vLLM configurations.\n\n Handles creation, retrieval, updating, and deletion of user profiles\n with validation and persistence.\n \"\"\"\n\n def __init__(self, config_dir: Path):\n self.config_dir = config_dir\n self.user_profiles_file = config_dir / \"user_profiles.json\"\n\n # Paths for schema files (packaged with application)\n schema_dir = Path(__file__).parent.parent / \"schemas\"\n self.default_profiles_file = schema_dir / \"default_profiles.json\"\n\n # Load profiles\n self.default_profiles = self._load_default_profiles()\n self.user_profiles = self._load_user_profiles()\n\n def _load_json_file(self, filepath: Path) -> Dict[str, Any]:\n \"\"\"Load a JSON file safely.\"\"\"\n if filepath.exists():\n try:\n with open(filepath, \"r\") as f:\n return json.load(f)\n except Exception as e:\n logger.error(f\"Error loading {filepath}: {e}\")\n return {}\n\n def _save_json_file(self, filepath: Path, data: Dict[str, Any]) -> bool:\n \"\"\"Save data to a JSON file.\"\"\"\n try:\n with open(filepath, \"w\") as f:\n json.dump(data, f, indent=2)\n return True\n except Exception as e:\n logger.error(f\"Error saving {filepath}: {e}\")\n return False\n\n def _load_default_profiles(self) -> Dict[str, Any]:\n \"\"\"Load default built-in profiles.\"\"\"\n profiles = self._load_json_file(self.default_profiles_file)\n return profiles.get(\"profiles\", {})\n\n def _load_user_profiles(self) -> Dict[str, Any]:\n \"\"\"Load user-created custom profiles.\"\"\"\n return self._load_json_file(self.user_profiles_file)\n\n def _save_user_profiles(self) -> bool:\n \"\"\"Save user profiles to file.\"\"\"\n return self._save_json_file(self.user_profiles_file, self.user_profiles)\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n all_profiles = deepcopy(self.default_profiles)\n all_profiles.update(self.user_profiles)\n return all_profiles\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name.\"\"\"\n # Check user profiles first, then default profiles\n if name in self.user_profiles:\n return deepcopy(self.user_profiles[name])\n elif name in self.default_profiles:\n return deepcopy(self.default_profiles[name])\n return None\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"\n Save or update a user profile with validation.\n\n Args:\n name: Profile name\n profile: Profile data to save\n\n Returns:\n True if saved successfully\n\n Raises:\n ProfileError: If profile validation fails or save fails\n \"\"\"\n try:\n # Validate profile structure\n if not isinstance(profile, dict):\n raise ProfileError(\n \"Profile must be a dictionary\",\n profile_name=name,\n error_code=\"INVALID_PROFILE_TYPE\",\n )\n\n # Process LoRA configuration if present\n if \"config\" in profile:\n config = profile[\"config\"]\n\n # Handle LoRA adapters in config\n if \"lora_adapters\" in config:\n # Validate LoRA adapter entries\n lora_adapters = config[\"lora_adapters\"]\n if isinstance(lora_adapters, list):\n # Ensure each adapter has required fields\n for adapter in lora_adapters:\n if not isinstance(adapter, dict):\n continue\n if \"path\" not in adapter and \"name\" in adapter:\n # Try to resolve adapter by name\n adapter[\"path\"] = self._resolve_lora_path(\n adapter[\"name\"]\n )\n\n # Convert to lora_modules format for vLLM\n if lora_adapters:\n config[\"enable_lora\"] = True\n lora_modules = []\n for adapter in lora_adapters:\n if isinstance(adapter, dict):\n name = adapter.get(\"name\", \"adapter\")\n path = adapter.get(\"path\", \"\")\n if path:\n lora_modules.append(f\"{name}={path}\")\n if lora_modules:\n config[\"lora_modules\"] = \" \".join(lora_modules)\n\n # Save the profile\n self.user_profiles[name] = deepcopy(profile)\n\n if not self._save_user_profiles():\n raise ProfileError(\n \"Failed to save profile to disk\",\n profile_name=name,\n error_code=\"PROFILE_SAVE_FAILED\",\n )\n\n logger.info(f\"Successfully saved user profile: {name}\")\n return True\n\n except ProfileError:\n raise\n except Exception as e:\n logger.error(f\"Unexpected error saving profile {name}: {e}\")\n raise ProfileError(\n f\"Unexpected error saving profile: {e}\",\n profile_name=name,\n error_code=\"PROFILE_SAVE_ERROR\",\n ) from e\n\n def _resolve_lora_path(self, adapter_name: str) -> str:\n \"\"\"\n Try to resolve a LoRA adapter path by name.\n\n Args:\n adapter_name: Name of the LoRA adapter\n\n Returns:\n Path to the adapter if found, empty string otherwise\n \"\"\"\n try:\n from ..models import scan_for_lora_adapters\n\n adapters = scan_for_lora_adapters()\n for adapter in adapters:\n if (\n adapter.get(\"name\") == adapter_name\n or adapter.get(\"display_name\") == adapter_name\n ):\n return adapter.get(\"path\", \"\")\n except Exception as e:\n logger.debug(f\"Could not resolve LoRA path for {adapter_name}: {e}\")\n return \"\"\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n if name in self.user_profiles:\n del self.user_profiles[name]\n return self._save_user_profiles()\n return False\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n profile = self.get_profile(profile_name)\n if not profile:\n logger.error(f\"Profile '{profile_name}' not found\")\n return False\n\n export_data = {\"version\": \"1.0\", \"profile\": profile}\n\n try:\n with open(filepath, \"w\") as f:\n json.dump(export_data, f, indent=2)\n logger.info(f\"Profile '{profile_name}' exported to {filepath}\")\n return True\n except Exception as e:\n logger.error(f\"Error exporting profile: {e}\")\n return False\n\n def import_profile(\n self,\n filepath: Path,\n new_name: Optional[str] = None,\n validate_config_func: Optional[Callable] = None,\n ) -> bool:\n \"\"\"\n Import a profile from a JSON file with comprehensive validation.\n\n Args:\n filepath: Path to the profile file\n new_name: Optional new name for the profile\n validate_config_func: Optional function to validate profile config\n\n Returns:\n True if imported successfully\n\n Raises:\n ProfileError: If import fails for any reason\n \"\"\"\n try:\n # Check file exists\n if not filepath.exists():\n raise ProfileError(\n f\"Profile file not found: {filepath}\",\n error_code=\"PROFILE_FILE_NOT_FOUND\",\n )\n\n # Load and parse file\n try:\n with open(filepath, \"r\") as f:\n data = json.load(f)\n except json.JSONDecodeError as e:\n raise ProfileError(\n f\"Invalid JSON in profile file: {e}\",\n error_code=\"PROFILE_INVALID_JSON\",\n ) from e\n\n # Validate file format\n if not isinstance(data, dict) or \"profile\" not in data:\n raise ProfileError(\n \"Invalid profile file format - missing 'profile' key\",\n error_code=\"PROFILE_INVALID_FORMAT\",\n )\n\n profile = data[\"profile\"]\n name = new_name or profile.get(\"name\", filepath.stem)\n\n # Validate profile configuration if function provided\n if validate_config_func and \"config\" in profile:\n is_valid, errors = validate_config_func(profile[\"config\"])\n if not is_valid:\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n # Save the profile\n return self.save_user_profile(name, profile)\n\n except ProfileError:\n raise\n except Exception as e:\n logger.error(f\"Unexpected error importing profile from {filepath}: {e}\")\n raise ProfileError(\n f\"Failed to import profile: {e}\", error_code=\"PROFILE_IMPORT_ERROR\"\n ) from e\n\n def list_profile_names(self) -> Dict[str, List[str]]:\n \"\"\"\n List all profile names categorized by type.\n\n Returns:\n Dictionary with 'default' and 'user' lists of profile names\n \"\"\"\n return {\n \"default\": list(self.default_profiles.keys()),\n \"user\": list(self.user_profiles.keys()),\n }\n\n def profile_exists(self, name: str) -> bool:\n \"\"\"Check if a profile exists (in either default or user profiles).\"\"\"\n return name in self.default_profiles or name in self.user_profiles\n\n def is_user_profile(self, name: str) -> bool:\n \"\"\"Check if a profile is a user-created profile.\"\"\"\n return name in self.user_profiles\n\n def has_user_override(self, name: str) -> bool:\n \"\"\"\n Check if a built-in profile has been overridden by a user profile.\n\n Args:\n name: Profile name to check\n\n Returns:\n True if this is a built-in profile that has a user override\n \"\"\"\n return name in self.default_profiles and name in self.user_profiles\n\n def get_original_default_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get the original default profile without any user overrides.\n\n Args:\n name: Profile name\n\n Returns:\n Original default profile if it exists, None otherwise\n \"\"\"\n if name in self.default_profiles:\n return deepcopy(self.default_profiles[name])\n return None\n\n def reset_to_default(self, name: str) -> bool:\n \"\"\"\n Reset a customized built-in profile to its default settings.\n\n This removes the user override for a built-in profile.\n\n Args:\n name: Profile name to reset\n\n Returns:\n True if reset successfully, False otherwise\n \"\"\"\n # Only reset if this is a built-in profile with a user override\n if self.has_user_override(name):\n return self.delete_user_profile(name)\n return False\n\n def get_profile_count(self) -> Dict[str, int]:\n \"\"\"Get count of profiles by type.\"\"\"\n return {\n \"default\": len(self.default_profiles),\n \"user\": len(self.user_profiles),\n \"total\": len(self.default_profiles) + len(self.user_profiles),\n }\n\n def apply_dynamic_defaults(self, profile_config: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Apply dynamic defaults to a profile configuration.\n\n This function intelligently sets tensor_parallel_size for multi-GPU systems.\n For single GPU systems, it allows vLLM to use its default behavior.\n\n Note: vLLM defaults to using only 1 GPU unless tensor_parallel_size is explicitly set.\n\n Args:\n profile_config: The profile configuration to enhance\n\n Returns:\n Enhanced profile configuration with dynamic defaults applied\n \"\"\"\n config = deepcopy(profile_config)\n\n # Apply dynamic tensor_parallel_size if not specified\n # Note: vLLM defaults to single GPU, so we only set this for multi-GPU systems\n # where tensor parallelism would be beneficial\n if \"tensor_parallel_size\" not in config:\n gpu_count = self._get_gpu_count()\n if gpu_count > 1:\n config[\"tensor_parallel_size\"] = gpu_count\n logger.debug(\n f\"Set tensor_parallel_size to {gpu_count} for multi-GPU system\"\n )\n # For single GPU, let vLLM use its default (no tensor_parallel_size needed)\n\n return config\n\n def _get_gpu_count(self) -> int:\n \"\"\"\n Get the number of available GPUs for tensor parallelism.\n\n Returns:\n Number of GPUs available, defaults to 1 if detection fails\n \"\"\"\n try:\n gpus = get_gpu_info()\n gpu_count = len(gpus) if gpus else 1\n logger.debug(f\"Detected {gpu_count} GPU(s)\")\n return gpu_count\n except Exception as e:\n logger.warning(f\"Failed to detect GPU count, defaulting to 1: {e}\")\n return 1", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 14008}, "tests/proxy/test_integration.py::136": {"resolved_imports": ["src/vllm_cli/proxy/config.py", "src/vllm_cli/proxy/manager.py", "src/vllm_cli/proxy/models.py", "src/vllm_cli/proxy/server_process.py"], "used_names": ["MagicMock", "ProxyConfigManager", "ProxyManager", "patch"], "enclosing_function": "test_proxy_manager_full_lifecycle", "extracted_code": "# Source: src/vllm_cli/proxy/config.py\nclass ProxyConfigManager:\n \"\"\"\n Manages proxy server configuration including persistence and validation.\n \"\"\"\n\n def __init__(self):\n \"\"\"Initialize the proxy configuration manager.\"\"\"\n self.config_dir = Path.home() / \".config\" / \"vllm-cli\"\n # Default configuration file path - used as fallback when no path specified\n # Also maintains backward compatibility with existing configurations\n self.proxy_config_file = self.config_dir / \"proxy_config.yaml\"\n self.proxy_configs_dir = self.config_dir / \"proxy_configs\"\n self.config_dir.mkdir(parents=True, exist_ok=True)\n self.proxy_configs_dir.mkdir(parents=True, exist_ok=True)\n\n def load_config(self, config_path: Optional[Path] = None) -> ProxyConfig:\n \"\"\"\n Load proxy configuration from file.\n\n Args:\n config_path: Path to configuration file (uses default if not provided)\n\n Returns:\n ProxyConfig instance\n \"\"\"\n config_file = config_path or self.proxy_config_file\n\n if not config_file.exists():\n logger.info(f\"No config file found at {config_file}, using defaults\")\n return self.get_default_config()\n\n try:\n with open(config_file, \"r\") as f:\n if config_file.suffix in [\".yaml\", \".yml\"]:\n config_dict = yaml.safe_load(f)\n else:\n config_dict = json.load(f)\n\n return self._parse_config(config_dict)\n\n except Exception as e:\n logger.error(f\"Failed to load config from {config_file}: {e}\")\n return self.get_default_config()\n\n def save_config(self, config: ProxyConfig, config_path: Optional[Path] = None):\n \"\"\"\n Save proxy configuration to file.\n\n Args:\n config: ProxyConfig to save\n config_path: Path to save to (uses default if not provided)\n \"\"\"\n config_file = config_path or self.proxy_config_file\n\n try:\n config_dict = {\n \"proxy\": {\n \"host\": config.host,\n \"port\": config.port,\n \"enable_cors\": config.enable_cors,\n \"enable_metrics\": config.enable_metrics,\n \"log_requests\": config.log_requests,\n },\n \"models\": [\n {\n \"name\": model.name,\n \"model_path\": model.model_path,\n \"gpu_ids\": model.gpu_ids,\n \"port\": model.port,\n \"profile\": model.profile,\n \"config_overrides\": model.config_overrides,\n \"enabled\": model.enabled,\n \"loading_priority\": model.loading_priority,\n }\n for model in config.models\n ],\n }\n\n with open(config_file, \"w\") as f:\n if config_file.suffix in [\".yaml\", \".yml\"]:\n yaml.safe_dump(config_dict, f, default_flow_style=False)\n else:\n json.dump(config_dict, f, indent=2)\n\n logger.info(f\"Saved proxy configuration to {config_file}\")\n\n except Exception as e:\n logger.error(f\"Failed to save config to {config_file}: {e}\")\n\n def save_named_config(self, config: ProxyConfig, name: str):\n \"\"\"\n Save proxy configuration with a specific name.\n\n Args:\n config: ProxyConfig to save\n name: Name for the configuration\n \"\"\"\n # Sanitize name for filesystem\n safe_name = \"\".join(c if c.isalnum() or c in \"_-\" else \"_\" for c in name)\n config_file = self.proxy_configs_dir / f\"{safe_name}.yaml\"\n\n self.save_config(config, config_file)\n logger.info(f\"Saved proxy configuration as '{name}'\")\n\n def load_named_config(self, name: str) -> Optional[ProxyConfig]:\n \"\"\"\n Load a named proxy configuration.\n\n Args:\n name: Name of the configuration to load\n\n Returns:\n ProxyConfig if found, None otherwise\n \"\"\"\n safe_name = \"\".join(c if c.isalnum() or c in \"_-\" else \"_\" for c in name)\n config_file = self.proxy_configs_dir / f\"{safe_name}.yaml\"\n\n if not config_file.exists():\n logger.error(f\"Configuration '{name}' not found\")\n return None\n\n return self.load_config(config_file)\n\n def list_saved_configs(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"\n List all saved proxy configurations.\n\n Returns:\n Dictionary mapping config names to their summaries\n \"\"\"\n configs = {}\n\n # Check new named configs directory\n for config_file in self.proxy_configs_dir.glob(\"*.yaml\"):\n name = config_file.stem\n try:\n config = self.load_config(config_file)\n if config:\n configs[name] = {\n \"file\": str(config_file),\n \"models\": len(config.models),\n \"port\": config.port,\n \"model_names\": [m.name for m in config.models][\n :3\n ], # First 3 models\n }\n except Exception as e:\n logger.warning(f\"Failed to load config {name}: {e}\")\n\n # Also check legacy default location\n if self.proxy_config_file.exists():\n try:\n config = self.load_config(self.proxy_config_file)\n if config:\n configs[\"default\"] = {\n \"file\": str(self.proxy_config_file),\n \"models\": len(config.models),\n \"port\": config.port,\n \"model_names\": [m.name for m in config.models][:3],\n }\n except Exception:\n pass\n\n return configs\n\n def delete_named_config(self, name: str) -> bool:\n \"\"\"\n Delete a named proxy configuration.\n\n Args:\n name: Name of the configuration to delete\n\n Returns:\n True if deleted successfully\n \"\"\"\n safe_name = \"\".join(c if c.isalnum() or c in \"_-\" else \"_\" for c in name)\n config_file = self.proxy_configs_dir / f\"{safe_name}.yaml\"\n\n if config_file.exists():\n try:\n config_file.unlink()\n logger.info(f\"Deleted configuration '{name}'\")\n return True\n except Exception as e:\n logger.error(f\"Failed to delete configuration '{name}': {e}\")\n return False\n else:\n logger.warning(f\"Configuration '{name}' not found\")\n return False\n\n def get_default_config(self) -> ProxyConfig:\n \"\"\"\n Get default proxy configuration.\n\n Returns:\n Default ProxyConfig instance\n \"\"\"\n return ProxyConfig(\n host=\"0.0.0.0\", # nosec B104\n port=8000,\n models=[],\n enable_cors=True,\n enable_metrics=True,\n log_requests=False,\n )\n\n def _parse_config(self, config_dict: Dict[str, Any]) -> ProxyConfig:\n \"\"\"\n Parse configuration dictionary into ProxyConfig.\n\n Args:\n config_dict: Configuration dictionary\n\n Returns:\n ProxyConfig instance\n \"\"\"\n proxy_settings = config_dict.get(\"proxy\", {})\n models_list = config_dict.get(\"models\", [])\n\n models = []\n for model_dict in models_list:\n try:\n models.append(ModelConfig(**model_dict))\n except Exception as e:\n logger.warning(f\"Failed to parse model config: {e}\")\n\n return ProxyConfig(\n host=proxy_settings.get(\"host\", \"0.0.0.0\"), # nosec B104\n port=proxy_settings.get(\"port\", 8000),\n models=models,\n enable_cors=proxy_settings.get(\"enable_cors\", True),\n enable_metrics=proxy_settings.get(\"enable_metrics\", True),\n log_requests=proxy_settings.get(\"log_requests\", False),\n )\n\n def validate_config(self, config: ProxyConfig) -> List[str]:\n \"\"\"\n Validate proxy configuration.\n\n Args:\n config: ProxyConfig to validate\n\n Returns:\n List of validation errors (empty if valid)\n \"\"\"\n errors = []\n\n # Check proxy port\n if not 1 <= config.port <= 65535:\n errors.append(f\"Invalid proxy port: {config.port}\")\n\n # Check for port conflicts\n used_ports = {config.port}\n for model in config.models:\n if model.port in used_ports:\n errors.append(f\"Port {model.port} is used by multiple services\")\n used_ports.add(model.port)\n\n # Check model names are unique\n model_names = [m.name for m in config.models]\n if len(model_names) != len(set(model_names)):\n errors.append(\"Model names must be unique\")\n\n return errors\n\n def create_example_config(self) -> ProxyConfig:\n \"\"\"\n Create an example proxy configuration.\n\n Returns:\n Example ProxyConfig instance\n \"\"\"\n return ProxyConfig(\n host=\"0.0.0.0\", # nosec B104\n port=8000,\n models=[\n ModelConfig(\n name=\"llama-3-8b\",\n model_path=\"meta-llama/Meta-Llama-3-8B-Instruct\",\n gpu_ids=[0],\n port=8001,\n profile=\"standard\",\n enabled=True,\n ),\n ModelConfig(\n name=\"mistral-7b\",\n model_path=\"mistralai/Mistral-7B-Instruct-v0.2\",\n gpu_ids=[1],\n port=8002,\n profile=\"performance\",\n enabled=True,\n ),\n ModelConfig(\n name=\"gemma-2b\",\n model_path=\"google/gemma-2b\",\n gpu_ids=[2],\n port=8003,\n profile=\"memory-optimized\",\n enabled=False, # Disabled by default\n ),\n ],\n enable_cors=True,\n enable_metrics=True,\n log_requests=False,\n )\n\n def export_config(self, config: ProxyConfig, export_path: Path):\n \"\"\"\n Export configuration to a file.\n\n Args:\n config: ProxyConfig to export\n export_path: Path to export to\n \"\"\"\n self.save_config(config, export_path)\n logger.info(f\"Exported configuration to {export_path}\")\n\n def import_config(self, import_path: Path) -> ProxyConfig:\n \"\"\"\n Import configuration from a file.\n\n Args:\n import_path: Path to import from\n\n Returns:\n Imported ProxyConfig instance\n \"\"\"\n config = self.load_config(import_path)\n logger.info(f\"Imported configuration from {import_path}\")\n return config\n\n\n# Source: src/vllm_cli/proxy/manager.py\nclass ProxyManager:\n \"\"\"\n Manages the lifecycle of multiple vLLM servers and the proxy server.\n \"\"\"\n\n def __init__(self, config: Optional[ProxyConfig] = None):\n \"\"\"\n Initialize the proxy manager.\n\n Args:\n config: Proxy configuration (uses defaults if not provided)\n \"\"\"\n self.proxy_config = config or ProxyConfig()\n self.proxy_process: Optional[ProxyServerProcess] = None\n self.vllm_servers: Dict[str, VLLMServer] = {}\n self.config_manager = ConfigManager()\n\n def _proxy_api_request(\n self,\n method: str,\n endpoint: str,\n json_data: Optional[Dict] = None,\n timeout: float = 5.0,\n ) -> Optional[Any]:\n \"\"\"\n Helper method for making HTTP requests to the proxy API.\n\n Args:\n method: HTTP method (POST, DELETE, GET)\n endpoint: API endpoint path\n json_data: Optional JSON data for request body\n timeout: Request timeout in seconds\n\n Returns:\n Response object if successful, None if failed\n \"\"\"\n try:\n import httpx\n\n url = f\"http://localhost:{self.proxy_config.port}{endpoint}\"\n with httpx.Client() as client:\n if method == \"POST\":\n response = client.post(url, json=json_data, timeout=timeout)\n elif method == \"DELETE\":\n response = client.delete(url, timeout=timeout)\n elif method == \"GET\":\n response = client.get(url, timeout=timeout)\n else:\n logger.error(f\"Unsupported HTTP method: {method}\")\n return None\n\n if response.status_code == 200:\n return response\n else:\n logger.warning(\n f\"API request failed: {method} {endpoint} - \"\n f\"{response.status_code}: {response.text}\"\n )\n return None\n\n except Exception as e:\n logger.warning(f\"API request error: {method} {endpoint} - {e}\")\n return None\n\n def start_proxy(self) -> bool:\n \"\"\"\n Start the proxy server.\n\n Returns:\n True if proxy started successfully\n \"\"\"\n try:\n # Create proxy server process instance\n self.proxy_process = ProxyServerProcess(self.proxy_config)\n\n # Start proxy as a subprocess\n if not self.proxy_process.start():\n logger.error(\"Failed to start proxy server process\")\n return False\n\n # Give it a moment to fully initialize\n time.sleep(2)\n\n # Register all running models with the proxy\n # Note: We'll need to update this to work with subprocess\n # For now, models will register when they start\n\n logger.info(\n f\"Proxy server started on \"\n f\"{self.proxy_config.host}:{self.proxy_config.port}\"\n )\n return True\n\n except Exception as e:\n logger.error(f\"Failed to start proxy server: {e}\")\n return False\n\n def stop_proxy(self):\n \"\"\"Stop the proxy server and all vLLM instances.\"\"\"\n logger.info(\"Stopping proxy server and all model servers...\")\n\n # Stop all vLLM servers\n for model_name in list(self.vllm_servers.keys()):\n self.stop_model(model_name)\n\n # Stop proxy server process\n if self.proxy_process:\n self.proxy_process.stop()\n self.proxy_process = None\n logger.info(\"Proxy server stopped\")\n\n def start_model(self, model_config: ModelConfig) -> bool:\n \"\"\"\n Start a vLLM server for a specific model.\n\n Args:\n model_config: Configuration for the model\n\n Returns:\n True if server started successfully\n \"\"\"\n try:\n # Check if model is already running\n if model_config.name in self.vllm_servers:\n logger.warning(f\"Model '{model_config.name}' is already running\")\n return False\n\n # Build vLLM server configuration\n vllm_config = self._build_vllm_config(model_config)\n\n # Pre-register with proxy if it's running\n if self.proxy_process and self.proxy_process.is_running():\n pre_register_data = {\n \"port\": model_config.port,\n \"gpu_ids\": model_config.gpu_ids,\n \"config_name\": model_config.name,\n }\n\n response = self._proxy_api_request(\n \"POST\", \"/proxy/pre_register\", pre_register_data\n )\n if response:\n logger.info(\n f\"Pre-registered model '{model_config.name}' with proxy\"\n )\n else:\n logger.warning(\n f\"Failed to pre-register model '{model_config.name}' with proxy\"\n )\n\n # Create and start vLLM server\n server = VLLMServer(vllm_config)\n if not server.start():\n logger.error(f\"Failed to start vLLM server for '{model_config.name}'\")\n return False\n\n # Store server reference\n self.vllm_servers[model_config.name] = server\n\n logger.info(\n f\"Started vLLM server process for '{model_config.name}' \"\n f\"on port {model_config.port} using GPUs {model_config.gpu_ids}\"\n )\n\n # Note: Registration with proxy will happen after startup completes\n # Registration happens during wait_and_register_model()\n\n return True\n\n except Exception as e:\n logger.error(f\"Failed to start model '{model_config.name}': {e}\")\n return False\n\n def wait_and_register_model(self, model_config: ModelConfig) -> bool:\n \"\"\"\n Wait for a model to complete startup and trigger proxy refresh.\n\n Args:\n model_config: Configuration for the model\n\n Returns:\n True if model started and registered successfully\n \"\"\"\n if model_config.name not in self.vllm_servers:\n logger.error(f\"Model '{model_config.name}' not found in servers\")\n return False\n\n server = self.vllm_servers[model_config.name]\n\n # Wait for server to complete startup\n if not server.wait_for_startup():\n logger.error(f\"Server '{model_config.name}' failed to complete startup\")\n # Clean up the failed server\n server.stop()\n del self.vllm_servers[model_config.name]\n return False\n\n # Trigger proxy refresh to verify and activate the model\n if self.proxy_process and self.proxy_process.is_running():\n # Call refresh to verify the pre-registered model\n response = self._proxy_api_request(\n \"POST\", \"/proxy/refresh_models\", timeout=10.0\n )\n if response:\n try:\n result = response.json()\n summary = result.get(\"summary\", {})\n if summary.get(\"registered\", 0) > 0:\n logger.info(\n f\"Model '{model_config.name}' successfully activated \"\n f\"on port {model_config.port}\"\n )\n return True\n else:\n logger.warning(\n f\"Model '{model_config.name}' started but \"\n f\"not activated in proxy\"\n )\n return True # Model is running, just not registered\n except Exception as e:\n logger.error(f\"Failed to parse refresh response: {e}\")\n return True # Model is running\n else:\n logger.warning(\n f\"Failed to refresh proxy after starting \"\n f\"model '{model_config.name}'\"\n )\n return True # Model is running even if refresh failed\n\n logger.info(f\"Model '{model_config.name}' is ready\")\n return True\n\n def refresh_model_registrations(self) -> Dict[str, Any]:\n \"\"\"\n Refresh model registrations with the proxy.\n\n Calls the proxy's refresh endpoint to verify all models in the registry.\n\n Returns:\n Dictionary with registration results\n \"\"\"\n if not self.proxy_process or not self.proxy_process.is_running():\n logger.warning(\"Proxy is not running, cannot refresh registrations\")\n return {\"status\": \"error\", \"message\": \"Proxy server is not running\"}\n\n # Call the refresh endpoint\n response = self._proxy_api_request(\n \"POST\", \"/proxy/refresh_models\", timeout=10.0\n )\n\n if response:\n try:\n result = response.json()\n summary = result.get(\"summary\", {})\n logger.info(\n f\"Model registration refresh completed: \"\n f\"{summary.get('registered', 0)} newly registered, \"\n f\"{summary.get('failed', 0)} newly failed, \"\n f\"{summary.get('already_available', 0)} already available, \"\n f\"{summary.get('removed', 0)} removed\"\n )\n return result\n except Exception as e:\n logger.error(f\"Failed to parse refresh response: {e}\")\n return {\"status\": \"error\", \"message\": f\"Failed to parse response: {e}\"}\n else:\n logger.error(\"Failed to refresh model registrations\")\n return {\n \"status\": \"error\",\n \"message\": \"Failed to connect to proxy refresh endpoint\",\n }\n\n def get_proxy_registry_status(self) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get full model registry status from proxy.\n\n Returns:\n Dictionary containing proxy status and all registered models,\n or None if proxy is not running\n \"\"\"\n if not self.proxy_process or not self.proxy_process.is_running():\n logger.warning(\"Proxy is not running, cannot get registry status\")\n return None\n\n response = self._proxy_api_request(\"GET\", \"/proxy/registry\")\n if response:\n try:\n return response.json()\n except Exception as e:\n logger.error(f\"Failed to parse proxy status response: {e}\")\n return None\n return None\n\n def sleep_model(self, model_name: str, level: int = 1) -> bool:\n \"\"\"\n Put a model to sleep, freeing GPU memory but keeping the port.\n Runs asynchronously and returns immediately.\n\n Args:\n model_name: Name of the model to sleep\n level: Sleep level (1=offload weights, 2=discard weights)\n\n Returns:\n True if sleep request was initiated successfully\n \"\"\"\n if model_name not in self.vllm_servers:\n logger.warning(f\"Model '{model_name}' is not running\")\n return False\n\n server = self.vllm_servers[model_name]\n port = server.port\n\n try:\n import threading\n\n import httpx\n\n def sleep_thread():\n try:\n # Use 10 minute timeout for very slow operations\n client = httpx.Client(timeout=600.0)\n logger.info(\n f\"Sending sleep request to model '{model_name}' \"\n f\"(level {level})...\"\n )\n response = client.post(\n f\"http://localhost:{port}/sleep?level={level}\"\n )\n client.close()\n\n if response.status_code == 200:\n logger.info(\n f\"Model '{model_name}' successfully put to sleep \"\n f\"(level {level})\"\n )\n\n # Update proxy registry state\n if self.proxy_process and self.proxy_process.is_running():\n state_data = {\n \"port\": port,\n \"state\": \"sleeping\",\n \"sleep_level\": level,\n }\n self._proxy_api_request(\"POST\", \"/proxy/state\", state_data)\n else:\n logger.error(\n f\"Failed to sleep model '{model_name}': \"\n f\"HTTP {response.status_code}\"\n )\n\n except Exception as e:\n logger.error(f\"Failed to sleep model '{model_name}': {e}\")\n\n # Start in background thread\n thread = threading.Thread(target=sleep_thread, daemon=True)\n thread.start()\n logger.info(f\"Sleep operation initiated for '{model_name}'\")\n return True\n\n except Exception as e:\n logger.error(f\"Failed to initiate sleep for '{model_name}': {e}\")\n return False\n\n def wake_model(self, model_name: str) -> bool:\n \"\"\"\n Wake up a sleeping model.\n Runs asynchronously and returns immediately.\n\n Args:\n model_name: Name of the model to wake\n\n Returns:\n True if wake request was initiated successfully\n \"\"\"\n if model_name not in self.vllm_servers:\n logger.warning(f\"Model '{model_name}' is not running\")\n return False\n\n server = self.vllm_servers[model_name]\n port = server.port\n\n try:\n import threading\n\n import httpx\n\n def wake_thread():\n try:\n # Use 10 minute timeout for very slow operations\n client = httpx.Client(timeout=600.0)\n logger.info(f\"Sending wake-up request to model '{model_name}'...\")\n response = client.post(f\"http://localhost:{port}/wake_up\")\n client.close()\n\n # Accept both 200 (OK) and 202 (Accepted) as success\n if response.status_code in [200, 202]:\n logger.info(f\"Model '{model_name}' successfully woken up\")\n\n # Update proxy registry state\n if self.proxy_process and self.proxy_process.is_running():\n state_data = {\n \"port\": port,\n \"state\": \"running\",\n \"sleep_level\": 0,\n }\n self._proxy_api_request(\"POST\", \"/proxy/state\", state_data)\n else:\n logger.error(\n f\"Failed to wake model '{model_name}': \"\n f\"HTTP {response.status_code}\"\n )\n\n except Exception as e:\n logger.error(f\"Failed to wake model '{model_name}': {e}\")\n\n # Start in background thread\n thread = threading.Thread(target=wake_thread, daemon=True)\n thread.start()\n logger.info(f\"Wake operation initiated for '{model_name}'\")\n return True\n\n except Exception as e:\n logger.error(f\"Failed to initiate wake for '{model_name}': {e}\")\n return False\n\n def is_sleeping(self, model_name: str) -> bool:\n \"\"\"\n Check if a model is sleeping.\n\n Args:\n model_name: Name of the model to check\n\n Returns:\n True if model is sleeping\n \"\"\"\n if model_name not in self.vllm_servers:\n return False\n\n server = self.vllm_servers[model_name]\n port = server.port\n\n try:\n import httpx\n\n client = httpx.Client(timeout=5.0)\n response = client.get(f\"http://localhost:{port}/is_sleeping\")\n client.close()\n\n if response.status_code == 200:\n data = response.json()\n return data.get(\"is_sleeping\", False)\n except Exception:\n pass\n\n return False\n\n def stop_model(self, model_name: str) -> bool:\n \"\"\"\n Stop a vLLM server for a specific model.\n\n Args:\n model_name: Name of the model to stop\n\n Returns:\n True if server stopped successfully\n \"\"\"\n if model_name not in self.vllm_servers:\n logger.warning(f\"Model '{model_name}' is not running\")\n return False\n\n try:\n # Get the port before stopping\n server = self.vllm_servers[model_name]\n port = server.port\n\n # Stop the vLLM server\n server.stop()\n\n # Remove from tracking\n del self.vllm_servers[model_name]\n\n # Unregister from proxy if it's running\n if self.proxy_process and self.proxy_process.is_running():\n # Use the new registry endpoint with port\n if self._proxy_api_request(\"DELETE\", f\"/proxy/models/{port}\"):\n logger.debug(f\"Unregistered model on port {port} from proxy\")\n\n logger.info(f\"Stopped vLLM server for '{model_name}'\")\n return True\n\n except Exception as e:\n logger.error(f\"Failed to stop model '{model_name}': {e}\")\n return False\n\n def unregister_model_from_proxy(self, port: int) -> bool:\n \"\"\"\n Unregister a model from the proxy registry by port.\n This is useful for cleaning up stopped models.\n\n Args:\n port: Port number of the model to unregister\n\n Returns:\n True if successfully unregistered or proxy not running\n \"\"\"\n if self.proxy_process and self.proxy_process.is_running():\n if self._proxy_api_request(\"DELETE\", f\"/proxy/models/{port}\"):\n logger.debug(f\"Unregistered model on port {port} from proxy\")\n return True\n return False\n return True # If proxy not running, consider it success\n\n def start_all_models_no_wait(self) -> int:\n \"\"\"\n Start all model processes without waiting for startup completion.\n\n This method starts all model servers concurrently and returns immediately,\n allowing the caller to monitor startup progress in real-time.\n\n Returns:\n Number of model processes successfully launched\n \"\"\"\n started_count = 0\n for model_config in self.proxy_config.models:\n if model_config.enabled:\n if self.start_model(model_config):\n started_count += 1\n # Small delay to avoid resource conflicts\n time.sleep(0.5)\n\n return started_count\n\n def start_models_with_priorities(self):\n \"\"\"\n Start models sequentially based on loading_priority.\n\n Models are grouped by priority (lower numbers first). Models within\n the same priority group start in parallel. This is a generator that\n yields each priority group after starting its models, allowing the\n UI layer to monitor startup progress with live feedback.\n\n This is useful for GPU-shared deployments where models with low\n gpu-memory-utilization should load first to claim KV cache space.\n\n Yields:\n Dictionary for each priority group:\n - priority: Priority number (or float('inf') for None)\n - priority_label: Human-readable priority label\n - models: List of ModelConfig instances in this group\n - started_models: List of ModelConfig instances that started successfully\n - failed_models: List of model names that failed to start\n - group_index: Current group number (1-indexed)\n - total_groups: Total number of priority groups\n - total_models: Total number of models across all groups\n \"\"\"\n from collections import defaultdict\n\n # Group models by loading_priority\n priority_groups = defaultdict(list)\n for model_config in self.proxy_config.models:\n if model_config.enabled:\n priority = model_config.loading_priority\n # Use a large number for None priority (load last)\n effective_priority = priority if priority is not None else float(\"inf\")\n priority_groups[effective_priority].append(model_config)\n\n # Sort priority groups (ascending order)\n sorted_priorities = sorted(priority_groups.keys())\n\n total_models = sum(len(models) for models in priority_groups.values())\n\n logger.info(\n f\"Starting {total_models} models in {len(sorted_priorities)} \"\n f\"priority group(s)\"\n )\n\n # Process each priority group sequentially\n for priority_idx, priority in enumerate(sorted_priorities, 1):\n models = priority_groups[priority]\n priority_label = (\n f\"Priority {int(priority)}\"\n if priority != float(\"inf\")\n else \"No Priority (Parallel)\"\n )\n\n logger.info(\n f\"Starting priority group {priority_idx}/{len(sorted_priorities)}: \"\n f\"{priority_label} ({len(models)} model(s))\"\n )\n\n # Start all models in this priority group (non-blocking)\n group_started = []\n group_failed = []\n\n for model_config in models:\n if self.start_model(model_config):\n group_started.append(model_config)\n logger.info(\n f\"Started {model_config.name} (port {model_config.port})\"\n )\n # Small delay to avoid resource conflicts\n time.sleep(0.5)\n else:\n group_failed.append(model_config.name)\n logger.error(f\"Failed to start {model_config.name}\")\n\n # Yield this group for UI monitoring (non-blocking)\n yield {\n \"priority\": priority,\n \"priority_label\": priority_label,\n \"models\": models,\n \"started_models\": group_started,\n \"failed_models\": group_failed,\n \"group_index\": priority_idx,\n \"total_groups\": len(sorted_priorities),\n \"total_models\": total_models,\n }\n\n # Control returns here after UI finishes monitoring this group\n\n def _build_vllm_config(self, model_config: ModelConfig) -> Dict[str, Any]:\n \"\"\"\n Build vLLM server configuration from model configuration.\n\n Args:\n model_config: Model configuration\n\n Returns:\n vLLM server configuration dictionary\n \"\"\"\n # Start with profile configuration if specified\n config = {}\n if model_config.profile:\n profile = self.config_manager.get_profile(model_config.profile)\n if profile:\n config = profile.get(\"config\", {}).copy()\n\n # Set model, port, and host\n config[\"model\"] = model_config.model_path\n config[\"port\"] = model_config.port\n config[\"host\"] = self.proxy_config.host # Use host from proxy configuration\n\n # Enable sleep mode for better resource management\n config[\"enable_sleep_mode\"] = True\n\n # Handle GPU assignment\n if model_config.gpu_ids:\n # Set CUDA_VISIBLE_DEVICES via device field\n config[\"device\"] = \",\".join(str(gpu) for gpu in model_config.gpu_ids)\n\n num_gpus = len(model_config.gpu_ids)\n\n # For single GPU assignment, override any parallel settings from profile\n if num_gpus == 1:\n # Remove parallel configuration that conflicts with single GPU\n conflicting_settings = [\n \"tensor_parallel_size\",\n \"pipeline_parallel_size\",\n \"distributed_executor_backend\",\n ]\n\n removed_settings = []\n for setting in conflicting_settings:\n if setting in config:\n removed_settings.append(f\"{setting}={config[setting]}\")\n del config[setting]\n\n # Disable expert parallelism for single GPU\n if config.get(\"enable_expert_parallel\"):\n removed_settings.append(\"enable_expert_parallel=True\")\n config[\"enable_expert_parallel\"] = False\n\n if removed_settings:\n logger.warning(\n f\"Model '{model_config.name}' assigned single GPU. \"\n f\"Overriding profile settings: {', '.join(removed_settings)}\"\n )\n\n elif num_gpus > 1:\n # For multi-GPU, set tensor_parallel_size if not already set\n if \"tensor_parallel_size\" not in config:\n config[\"tensor_parallel_size\"] = num_gpus\n elif config[\"tensor_parallel_size\"] > num_gpus:\n # Adjust if profile expects more GPUs than assigned\n logger.warning(\n f\"Model '{model_config.name}': Adjusting tensor_parallel_size \"\n f\"from {config['tensor_parallel_size']} to {num_gpus} \"\n f\"(assigned GPUs)\"\n )\n config[\"tensor_parallel_size\"] = num_gpus\n\n # Apply any config overrides\n config.update(model_config.config_overrides)\n\n return config\n\n def get_status(self) -> Dict[str, Any]:\n \"\"\"\n Get status of proxy and all model servers.\n\n Returns:\n Status dictionary\n \"\"\"\n status = {\n \"proxy_running\": self.proxy_process and self.proxy_process.is_running(),\n \"proxy_host\": self.proxy_config.host,\n \"proxy_port\": self.proxy_config.port,\n \"models\": [],\n }\n\n for model_name, server in self.vllm_servers.items():\n model_status = {\n \"name\": model_name,\n \"running\": server.is_running(),\n \"port\": server.port,\n \"uptime\": None,\n }\n\n if server.is_running() and server.start_time:\n uptime = time.time() - server.start_time.timestamp()\n model_status[\"uptime\"] = uptime\n\n status[\"models\"].append(model_status)\n\n return status\n\n def reload_model(self, model_name: str) -> bool:\n \"\"\"\n Reload a model (stop and start again).\n\n Args:\n model_name: Name of the model to reload\n\n Returns:\n True if reload successful\n \"\"\"\n # Find the model config\n model_config = None\n for config in self.proxy_config.models:\n if config.name == model_name:\n model_config = config\n break\n\n if not model_config:\n logger.error(f\"Model '{model_name}' not found in configuration\")\n return False\n\n # Stop if running\n if model_name in self.vllm_servers:\n self.stop_model(model_name)\n time.sleep(2) # Wait before restarting\n\n # Start the model\n if not self.start_model(model_config):\n return False\n\n # Wait for startup and register\n return self.wait_and_register_model(model_config)\n\n def allocate_gpus_automatically(self) -> List[ModelConfig]:\n \"\"\"\n Automatically allocate GPUs to models based on available resources.\n\n Returns:\n List of model configurations with GPU allocations\n \"\"\"\n from ..system import get_gpu_info\n\n # Get available GPUs\n gpu_info = get_gpu_info()\n if not gpu_info:\n logger.warning(\"No GPUs available for allocation\")\n return []\n\n num_gpus = len(gpu_info)\n models = self.proxy_config.models\n\n # Simple allocation strategy: distribute GPUs evenly\n allocated_configs = []\n\n if len(models) <= num_gpus:\n # Each model gets at least one GPU\n gpus_per_model = num_gpus // len(models)\n remaining_gpus = num_gpus % len(models)\n\n gpu_index = 0\n for i, model in enumerate(models):\n num_gpus_for_model = gpus_per_model\n if i < remaining_gpus:\n num_gpus_for_model += 1\n\n model.gpu_ids = list(range(gpu_index, gpu_index + num_gpus_for_model))\n gpu_index += num_gpus_for_model\n\n # Allocate port if not specified\n if not model.port:\n model.port = get_next_available_port(8001 + i)\n\n allocated_configs.append(model)\n else:\n # More models than GPUs - some models won't be allocated\n logger.warning(\n f\"More models ({len(models)}) than GPUs ({num_gpus}). \"\n f\"Only first {num_gpus} models will be allocated.\"\n )\n for i in range(num_gpus):\n models[i].gpu_ids = [i]\n if not models[i].port:\n models[i].port = get_next_available_port(8001 + i)\n allocated_configs.append(models[i])\n\n return allocated_configs\n\n def _get_model_config_by_name(self, model_name: str) -> Optional[ModelConfig]:\n \"\"\"\n Get model configuration by model name.\n\n Args:\n model_name: Name of the model\n\n Returns:\n ModelConfig if found, None otherwise\n \"\"\"\n for model_config in self.proxy_config.models:\n if model_config.name == model_name:\n return model_config\n return None\n\n @classmethod\n def from_config_file(cls, config_path: Path) -> \"ProxyManager\":\n \"\"\"\n Create ProxyManager from a configuration file.\n\n Args:\n config_path: Path to configuration file (YAML or JSON)\n\n Returns:\n ProxyManager instance\n \"\"\"\n import json\n\n import yaml\n\n with open(config_path, \"r\") as f:\n if config_path.suffix in [\".yaml\", \".yml\"]:\n config_dict = yaml.safe_load(f)\n else:\n config_dict = json.load(f)\n\n # Parse proxy configuration\n proxy_config = ProxyConfig(**config_dict.get(\"proxy\", {}))\n\n # Parse model configurations\n models = []\n for model_dict in config_dict.get(\"models\", []):\n models.append(ModelConfig(**model_dict))\n proxy_config.models = models\n\n return cls(proxy_config)", "n_imports_parsed": 9, "n_files_resolved": 4, "n_chars_extracted": 42411}, "tests/test_profiles.py::159": {"resolved_imports": ["src/vllm_cli/config/profiles.py"], "used_names": ["ProfileManager", "patch"], "enclosing_function": "test_get_all_profiles", "extracted_code": "# Source: src/vllm_cli/config/profiles.py\nclass ProfileManager:\n \"\"\"\n Manages user profiles for vLLM configurations.\n\n Handles creation, retrieval, updating, and deletion of user profiles\n with validation and persistence.\n \"\"\"\n\n def __init__(self, config_dir: Path):\n self.config_dir = config_dir\n self.user_profiles_file = config_dir / \"user_profiles.json\"\n\n # Paths for schema files (packaged with application)\n schema_dir = Path(__file__).parent.parent / \"schemas\"\n self.default_profiles_file = schema_dir / \"default_profiles.json\"\n\n # Load profiles\n self.default_profiles = self._load_default_profiles()\n self.user_profiles = self._load_user_profiles()\n\n def _load_json_file(self, filepath: Path) -> Dict[str, Any]:\n \"\"\"Load a JSON file safely.\"\"\"\n if filepath.exists():\n try:\n with open(filepath, \"r\") as f:\n return json.load(f)\n except Exception as e:\n logger.error(f\"Error loading {filepath}: {e}\")\n return {}\n\n def _save_json_file(self, filepath: Path, data: Dict[str, Any]) -> bool:\n \"\"\"Save data to a JSON file.\"\"\"\n try:\n with open(filepath, \"w\") as f:\n json.dump(data, f, indent=2)\n return True\n except Exception as e:\n logger.error(f\"Error saving {filepath}: {e}\")\n return False\n\n def _load_default_profiles(self) -> Dict[str, Any]:\n \"\"\"Load default built-in profiles.\"\"\"\n profiles = self._load_json_file(self.default_profiles_file)\n return profiles.get(\"profiles\", {})\n\n def _load_user_profiles(self) -> Dict[str, Any]:\n \"\"\"Load user-created custom profiles.\"\"\"\n return self._load_json_file(self.user_profiles_file)\n\n def _save_user_profiles(self) -> bool:\n \"\"\"Save user profiles to file.\"\"\"\n return self._save_json_file(self.user_profiles_file, self.user_profiles)\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n all_profiles = deepcopy(self.default_profiles)\n all_profiles.update(self.user_profiles)\n return all_profiles\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name.\"\"\"\n # Check user profiles first, then default profiles\n if name in self.user_profiles:\n return deepcopy(self.user_profiles[name])\n elif name in self.default_profiles:\n return deepcopy(self.default_profiles[name])\n return None\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"\n Save or update a user profile with validation.\n\n Args:\n name: Profile name\n profile: Profile data to save\n\n Returns:\n True if saved successfully\n\n Raises:\n ProfileError: If profile validation fails or save fails\n \"\"\"\n try:\n # Validate profile structure\n if not isinstance(profile, dict):\n raise ProfileError(\n \"Profile must be a dictionary\",\n profile_name=name,\n error_code=\"INVALID_PROFILE_TYPE\",\n )\n\n # Process LoRA configuration if present\n if \"config\" in profile:\n config = profile[\"config\"]\n\n # Handle LoRA adapters in config\n if \"lora_adapters\" in config:\n # Validate LoRA adapter entries\n lora_adapters = config[\"lora_adapters\"]\n if isinstance(lora_adapters, list):\n # Ensure each adapter has required fields\n for adapter in lora_adapters:\n if not isinstance(adapter, dict):\n continue\n if \"path\" not in adapter and \"name\" in adapter:\n # Try to resolve adapter by name\n adapter[\"path\"] = self._resolve_lora_path(\n adapter[\"name\"]\n )\n\n # Convert to lora_modules format for vLLM\n if lora_adapters:\n config[\"enable_lora\"] = True\n lora_modules = []\n for adapter in lora_adapters:\n if isinstance(adapter, dict):\n name = adapter.get(\"name\", \"adapter\")\n path = adapter.get(\"path\", \"\")\n if path:\n lora_modules.append(f\"{name}={path}\")\n if lora_modules:\n config[\"lora_modules\"] = \" \".join(lora_modules)\n\n # Save the profile\n self.user_profiles[name] = deepcopy(profile)\n\n if not self._save_user_profiles():\n raise ProfileError(\n \"Failed to save profile to disk\",\n profile_name=name,\n error_code=\"PROFILE_SAVE_FAILED\",\n )\n\n logger.info(f\"Successfully saved user profile: {name}\")\n return True\n\n except ProfileError:\n raise\n except Exception as e:\n logger.error(f\"Unexpected error saving profile {name}: {e}\")\n raise ProfileError(\n f\"Unexpected error saving profile: {e}\",\n profile_name=name,\n error_code=\"PROFILE_SAVE_ERROR\",\n ) from e\n\n def _resolve_lora_path(self, adapter_name: str) -> str:\n \"\"\"\n Try to resolve a LoRA adapter path by name.\n\n Args:\n adapter_name: Name of the LoRA adapter\n\n Returns:\n Path to the adapter if found, empty string otherwise\n \"\"\"\n try:\n from ..models import scan_for_lora_adapters\n\n adapters = scan_for_lora_adapters()\n for adapter in adapters:\n if (\n adapter.get(\"name\") == adapter_name\n or adapter.get(\"display_name\") == adapter_name\n ):\n return adapter.get(\"path\", \"\")\n except Exception as e:\n logger.debug(f\"Could not resolve LoRA path for {adapter_name}: {e}\")\n return \"\"\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n if name in self.user_profiles:\n del self.user_profiles[name]\n return self._save_user_profiles()\n return False\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n profile = self.get_profile(profile_name)\n if not profile:\n logger.error(f\"Profile '{profile_name}' not found\")\n return False\n\n export_data = {\"version\": \"1.0\", \"profile\": profile}\n\n try:\n with open(filepath, \"w\") as f:\n json.dump(export_data, f, indent=2)\n logger.info(f\"Profile '{profile_name}' exported to {filepath}\")\n return True\n except Exception as e:\n logger.error(f\"Error exporting profile: {e}\")\n return False\n\n def import_profile(\n self,\n filepath: Path,\n new_name: Optional[str] = None,\n validate_config_func: Optional[Callable] = None,\n ) -> bool:\n \"\"\"\n Import a profile from a JSON file with comprehensive validation.\n\n Args:\n filepath: Path to the profile file\n new_name: Optional new name for the profile\n validate_config_func: Optional function to validate profile config\n\n Returns:\n True if imported successfully\n\n Raises:\n ProfileError: If import fails for any reason\n \"\"\"\n try:\n # Check file exists\n if not filepath.exists():\n raise ProfileError(\n f\"Profile file not found: {filepath}\",\n error_code=\"PROFILE_FILE_NOT_FOUND\",\n )\n\n # Load and parse file\n try:\n with open(filepath, \"r\") as f:\n data = json.load(f)\n except json.JSONDecodeError as e:\n raise ProfileError(\n f\"Invalid JSON in profile file: {e}\",\n error_code=\"PROFILE_INVALID_JSON\",\n ) from e\n\n # Validate file format\n if not isinstance(data, dict) or \"profile\" not in data:\n raise ProfileError(\n \"Invalid profile file format - missing 'profile' key\",\n error_code=\"PROFILE_INVALID_FORMAT\",\n )\n\n profile = data[\"profile\"]\n name = new_name or profile.get(\"name\", filepath.stem)\n\n # Validate profile configuration if function provided\n if validate_config_func and \"config\" in profile:\n is_valid, errors = validate_config_func(profile[\"config\"])\n if not is_valid:\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n # Save the profile\n return self.save_user_profile(name, profile)\n\n except ProfileError:\n raise\n except Exception as e:\n logger.error(f\"Unexpected error importing profile from {filepath}: {e}\")\n raise ProfileError(\n f\"Failed to import profile: {e}\", error_code=\"PROFILE_IMPORT_ERROR\"\n ) from e\n\n def list_profile_names(self) -> Dict[str, List[str]]:\n \"\"\"\n List all profile names categorized by type.\n\n Returns:\n Dictionary with 'default' and 'user' lists of profile names\n \"\"\"\n return {\n \"default\": list(self.default_profiles.keys()),\n \"user\": list(self.user_profiles.keys()),\n }\n\n def profile_exists(self, name: str) -> bool:\n \"\"\"Check if a profile exists (in either default or user profiles).\"\"\"\n return name in self.default_profiles or name in self.user_profiles\n\n def is_user_profile(self, name: str) -> bool:\n \"\"\"Check if a profile is a user-created profile.\"\"\"\n return name in self.user_profiles\n\n def has_user_override(self, name: str) -> bool:\n \"\"\"\n Check if a built-in profile has been overridden by a user profile.\n\n Args:\n name: Profile name to check\n\n Returns:\n True if this is a built-in profile that has a user override\n \"\"\"\n return name in self.default_profiles and name in self.user_profiles\n\n def get_original_default_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get the original default profile without any user overrides.\n\n Args:\n name: Profile name\n\n Returns:\n Original default profile if it exists, None otherwise\n \"\"\"\n if name in self.default_profiles:\n return deepcopy(self.default_profiles[name])\n return None\n\n def reset_to_default(self, name: str) -> bool:\n \"\"\"\n Reset a customized built-in profile to its default settings.\n\n This removes the user override for a built-in profile.\n\n Args:\n name: Profile name to reset\n\n Returns:\n True if reset successfully, False otherwise\n \"\"\"\n # Only reset if this is a built-in profile with a user override\n if self.has_user_override(name):\n return self.delete_user_profile(name)\n return False\n\n def get_profile_count(self) -> Dict[str, int]:\n \"\"\"Get count of profiles by type.\"\"\"\n return {\n \"default\": len(self.default_profiles),\n \"user\": len(self.user_profiles),\n \"total\": len(self.default_profiles) + len(self.user_profiles),\n }\n\n def apply_dynamic_defaults(self, profile_config: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Apply dynamic defaults to a profile configuration.\n\n This function intelligently sets tensor_parallel_size for multi-GPU systems.\n For single GPU systems, it allows vLLM to use its default behavior.\n\n Note: vLLM defaults to using only 1 GPU unless tensor_parallel_size is explicitly set.\n\n Args:\n profile_config: The profile configuration to enhance\n\n Returns:\n Enhanced profile configuration with dynamic defaults applied\n \"\"\"\n config = deepcopy(profile_config)\n\n # Apply dynamic tensor_parallel_size if not specified\n # Note: vLLM defaults to single GPU, so we only set this for multi-GPU systems\n # where tensor parallelism would be beneficial\n if \"tensor_parallel_size\" not in config:\n gpu_count = self._get_gpu_count()\n if gpu_count > 1:\n config[\"tensor_parallel_size\"] = gpu_count\n logger.debug(\n f\"Set tensor_parallel_size to {gpu_count} for multi-GPU system\"\n )\n # For single GPU, let vLLM use its default (no tensor_parallel_size needed)\n\n return config\n\n def _get_gpu_count(self) -> int:\n \"\"\"\n Get the number of available GPUs for tensor parallelism.\n\n Returns:\n Number of GPUs available, defaults to 1 if detection fails\n \"\"\"\n try:\n gpus = get_gpu_info()\n gpu_count = len(gpus) if gpus else 1\n logger.debug(f\"Detected {gpu_count} GPU(s)\")\n return gpu_count\n except Exception as e:\n logger.warning(f\"Failed to detect GPU count, defaulting to 1: {e}\")\n return 1", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 14008}, "tests/proxy/test_router.py::101": {"resolved_imports": ["src/vllm_cli/proxy/router.py"], "used_names": [], "enclosing_function": "test_get_backends", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/proxy/test_models.py::117": {"resolved_imports": ["src/vllm_cli/proxy/models.py"], "used_names": ["ModelConfig", "ProxyConfig"], "enclosing_function": "test_proxy_config_creation", "extracted_code": "# Source: src/vllm_cli/proxy/models.py\nclass ModelConfig(BaseModel):\n \"\"\"Configuration for a single model in the proxy.\"\"\"\n\n name: str = Field(..., description=\"Model identifier for API requests\")\n model_path: str = Field(..., description=\"Path or HuggingFace model ID\")\n gpu_ids: List[int] = Field(default_factory=list, description=\"GPU IDs to use\")\n port: int = Field(..., description=\"Port for the vLLM server\")\n profile: Optional[str] = Field(None, description=\"vLLM CLI profile to use\")\n config_overrides: Dict[str, Any] = Field(\n default_factory=dict, description=\"Additional vLLM configuration\"\n )\n enabled: bool = Field(True, description=\"Whether model is enabled\")\n loading_priority: Optional[int] = Field(\n None,\n description=\"Loading priority (lower numbers load first). \"\n \"Models with same priority load in parallel. \"\n \"Models with None priority load after all prioritized models.\",\n )\n\nclass ProxyConfig(BaseModel):\n \"\"\"Configuration for the proxy server.\"\"\"\n\n host: str = Field(\"0.0.0.0\", description=\"Proxy server host\") # nosec B104\n port: int = Field(8000, description=\"Proxy server port\")\n models: List[ModelConfig] = Field(\n default_factory=list, description=\"List of models to serve\"\n )\n enable_cors: bool = Field(True, description=\"Enable CORS headers\")\n enable_metrics: bool = Field(True, description=\"Enable metrics endpoint\")\n log_requests: bool = Field(False, description=\"Log all requests\")", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 1518}, "tests/test_environment_variables.py::822": {"resolved_imports": ["src/vllm_cli/config/manager.py", "src/vllm_cli/server/manager.py"], "used_names": ["Mock", "VLLMServer", "patch"], "enclosing_function": "test_tensor_parallel_adjustment_with_device", "extracted_code": "# Source: src/vllm_cli/server/manager.py\nclass VLLMServer:\n \"\"\"\n Manages a vLLM server instance with comprehensive lifecycle control.\n\n This class handles the complete lifecycle of a vLLM server including\n configuration, process management, logging, monitoring, and cleanup.\n It supports both programmatically started servers and external server\n detection and management.\n\n Attributes:\n config: Server configuration dictionary\n model: Model name being served\n port: Port number the server is listening on\n process: Subprocess or external process reference\n log_file: File handle for server logs\n log_queue: Thread-safe queue for log lines\n log_thread: Background thread for log monitoring\n start_time: Timestamp when server was started\n log_path: Path to the server's log file\n \"\"\"\n\n def __init__(self, config: Dict[str, Any]) -> None:\n \"\"\"\n Initialize a vLLM server instance.\n\n Sets up the server configuration, logging infrastructure, and\n prepares the instance for server lifecycle management.\n\n Args:\n config: Server configuration dictionary containing model name,\n port, and other vLLM-specific parameters\n \"\"\"\n self.config: Dict[str, Any] = config\n\n # Extract model name - handle both string and dict (LoRA config) formats\n model_config = config.get(\"model\", \"unknown\")\n if isinstance(model_config, dict):\n # LoRA configuration - extract base model name\n self.model: str = model_config.get(\"model\", \"unknown\")\n else:\n # Regular string model name\n self.model: str = model_config\n\n self.port: int = config.get(\"port\", 8000)\n self.process: Optional[Union[subprocess.Popen, Any]] = None\n self.log_file: Optional[TextIO] = None\n self.log_queue: Queue[str] = Queue()\n self.log_thread: Optional[Thread] = None\n self.start_time: Optional[datetime] = None\n self.log_path: Path\n self._recent_logs: List[str] = []\n\n # Setup logging\n log_dir = Path.home() / \".vllm-cli\" / \"logs\"\n log_dir.mkdir(parents=True, exist_ok=True)\n\n timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n self.log_path = log_dir / f\"vllm_{self.model.replace('/', '_')}_{timestamp}.log\"\n\n def start(self) -> bool:\n \"\"\"\n Start the vLLM server.\n\n Returns:\n True if server started successfully, False otherwise\n \"\"\"\n if self.is_running():\n logger.warning(f\"Server already running for {self.model}\")\n return False\n\n try:\n # Build command - run directly without conda wrapper\n full_cmd = self._build_command()\n\n logger.info(f\"Starting vLLM server with command: {' '.join(full_cmd)}\")\n\n # Open log file for writing\n self.log_file = open(self.log_path, \"w\", buffering=1)\n\n # Start with parent environment\n env = os.environ.copy()\n # Note: No longer forcing PYTHONUNBUFFERED=1, let user control it\n\n # Layer 1: Apply universal environment variables from settings\n config_manager = ConfigManager()\n universal_env = config_manager.config.get(\"universal_environment\", {})\n if universal_env:\n logger.info(\n f\"Applying {len(universal_env)} universal environment variable(s)\"\n )\n for key, value in universal_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting universal {key}={value}\")\n else:\n logger.debug(f\"Setting universal {key}=\")\n\n # Layer 2: Apply profile environment variables (override universal)\n profile_env = self.config.get(\"profile_environment\", {})\n if profile_env:\n logger.info(\n f\"Applying {len(profile_env)} profile environment variable(s)\"\n )\n for key, value in profile_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting profile {key}={value}\")\n else:\n logger.debug(f\"Setting profile {key}=\")\n\n # Handle GPU device selection via CUDA_VISIBLE_DEVICES\n # This overrides any CUDA_VISIBLE_DEVICES from the profile\n if self.config.get(\"device\"):\n device_str = str(self.config[\"device\"])\n env[\"CUDA_VISIBLE_DEVICES\"] = device_str\n logger.info(f\"Setting CUDA_VISIBLE_DEVICES={device_str}\")\n\n # If using specific GPUs, adjust tensor parallel size if needed\n device_list = [d.strip() for d in device_str.split(\",\")]\n num_devices = len(device_list)\n\n # Check if tensor_parallel_size is set and compatible\n if self.config.get(\"tensor_parallel_size\"):\n tp_size = self.config[\"tensor_parallel_size\"]\n if tp_size > num_devices:\n logger.warning(\n f\"tensor_parallel_size ({tp_size}) > number of selected devices ({num_devices}). \"\n f\"Adjusting tensor_parallel_size to {num_devices}\"\n )\n self.config[\"tensor_parallel_size\"] = num_devices\n elif num_devices % tp_size != 0:\n logger.warning(\n f\"Number of GPUs ({num_devices}) is not evenly divisible by \"\n f\"tensor_parallel_size ({tp_size}). This may lead to inefficient GPU utilization. \"\n f\"Consider using tensor_parallel_size of: \"\n f\"{', '.join(str(i) for i in range(1, num_devices + 1) if num_devices % i == 0)}\"\n )\n\n # Add HuggingFace token if configured\n config_manager = ConfigManager()\n hf_token = config_manager.config.get(\"hf_token\")\n if hf_token:\n env[\"HF_TOKEN\"] = hf_token\n env[\"HUGGING_FACE_HUB_TOKEN\"] = hf_token # Some tools use this variant\n logger.info(\"HuggingFace token configured for server\")\n\n # Enable development mode for sleep endpoints if sleep mode is enabled\n if self.config.get(\"enable_sleep_mode\"):\n env[\"VLLM_SERVER_DEV_MODE\"] = \"1\"\n logger.info(\"Sleep mode enabled with development endpoints\")\n\n # Start the process with proper pipe configuration\n # Use start_new_session=True to create a new process group\n # This prevents the child process from receiving Ctrl+C signals\n self.process = subprocess.Popen(\n full_cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n text=True,\n bufsize=0, # Unbuffered\n universal_newlines=True,\n env=env,\n start_new_session=True, # Create new process group to isolate from parent signals\n )\n\n # Start log monitoring thread\n self._start_log_monitor()\n\n # Set start time and add to registry\n self.start_time = datetime.now()\n from .process import add_server\n\n add_server(self)\n\n # Return immediately - let the UI monitor the startup\n logger.info(\n f\"vLLM server process launched for {self.model} on port {self.port}\"\n )\n return True\n\n except Exception as e:\n logger.error(f\"Error starting vLLM server: {e}\")\n return False\n\n def _build_command(self) -> List[str]:\n \"\"\"\n Build the vLLM command from configuration using the schema.\n\n Returns:\n List of command arguments\n \"\"\"\n # Use the new ConfigManager to build CLI args\n config_manager = ConfigManager()\n\n # Start with the vllm command\n cmd = [\"vllm\"]\n\n # Add the arguments built from schema\n cli_args = config_manager.build_cli_args(self.config)\n cmd.extend(cli_args)\n\n # Handle extra_args if present (backward compatibility)\n if self.config.get(\"extra_args\"):\n self._add_extra_args_to_command(cmd)\n\n logger.debug(f\"Built command: {' '.join(cmd)}\")\n return cmd\n\n def _add_extra_args_to_command(self, cmd: List[str]) -> None:\n \"\"\"\n Add extra arguments to the vLLM command.\n\n Args:\n cmd: Command list to extend with extra arguments\n \"\"\"\n try:\n extra_args = shlex.split(self.config[\"extra_args\"])\n if extra_args:\n logger.info(f\"Adding extra arguments: {extra_args}\")\n cmd.extend(extra_args)\n except ValueError as e:\n logger.warning(f\"Failed to parse extra_args: {e}\")\n\n def _start_log_monitor(self) -> None:\n \"\"\"\n Start a thread to monitor log output from the vLLM server process.\n\n Creates a daemon thread that continuously reads stdout/stderr from\n the server process, writes to log files, and queues log lines for\n real-time display in the UI.\n \"\"\"\n self.log_thread = Thread(target=self._log_monitor_worker, daemon=True)\n self.log_thread.start()\n\n def _log_monitor_worker(self) -> None:\n \"\"\"\n Worker function for log monitoring thread.\n\n Continuously reads log output from the server process and handles\n file writing and queue management for UI display.\n \"\"\"\n try:\n self.log_queue.put(\"Starting vLLM server process...\")\n\n while self._should_continue_monitoring():\n if self._process_log_line():\n continue\n else:\n # No line read, check if process still running\n if self.process and self.process.poll() is not None:\n break\n time.sleep(0.01) # Small sleep to prevent busy waiting\n\n except Exception as e:\n logger.error(f\"Error in log monitor: {e}\")\n self.log_queue.put(f\"Log monitoring error: {e}\")\n\n def _should_continue_monitoring(self) -> bool:\n \"\"\"\n Check if log monitoring should continue.\n\n Returns:\n True if monitoring should continue, False otherwise\n \"\"\"\n return (\n self.is_running()\n and self.process\n and hasattr(self.process, \"stdout\")\n and self.process.stdout\n )\n\n def _process_log_line(self) -> bool:\n \"\"\"\n Process a single log line from the server output.\n\n Reads one line from the process stdout, writes it to the log file,\n and adds it to the queue for UI display after filtering and formatting.\n\n Returns:\n True if a line was processed, False if no line was available\n \"\"\"\n if not (self.process and self.process.stdout):\n return False\n\n line = self.process.stdout.readline()\n if not line:\n return False\n\n # Write to log file\n self._write_to_log_file(line)\n\n # Process for UI display\n line_stripped = line.strip()\n if line_stripped and self._should_display_log_line(line_stripped):\n # Truncate overly long lines\n if len(line_stripped) > 200:\n line_stripped = line_stripped[:197] + \"...\"\n\n self.log_queue.put(line_stripped)\n logger.debug(f\"Log captured: {line_stripped[:50]}...\")\n\n return True\n\n def _write_to_log_file(self, line: str) -> None:\n \"\"\"\n Write a log line to the log file.\n\n Args:\n line: Log line to write\n \"\"\"\n if self.log_file and not self.log_file.closed:\n self.log_file.write(line)\n self.log_file.flush()\n\n def _should_display_log_line(self, line: str) -> bool:\n \"\"\"\n Determine if a log line should be displayed in the UI.\n\n Filters out certain system messages that are not useful for users.\n\n Args:\n line: Stripped log line to check\n\n Returns:\n True if the line should be displayed, False otherwise\n \"\"\"\n # Filter out conda activation and system messages\n filtered_messages = [\n \"Activated CUDA\",\n \"Using nvcc from:\",\n \"Cuda compilation tools\",\n ]\n return not any(skip in line for skip in filtered_messages)\n\n def stop(self) -> bool:\n \"\"\"\n Stop the vLLM server.\n\n Returns:\n True if server stopped successfully, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n try:\n # Check if this is an external server\n if hasattr(self.process, \"terminate\"):\n # Normal subprocess\n # Since we created a new session, we need to terminate the entire process group\n try:\n # Get the process group ID (pgid)\n # Since we used start_new_session=True, the pgid is the same as the pid\n pgid = self.process.pid\n\n # Send SIGTERM to the entire process group for graceful shutdown\n logger.info(f\"Sending SIGTERM to process group {pgid}\")\n os.killpg(pgid, signal.SIGTERM)\n\n # Wait for process to terminate\n try:\n self.process.wait(timeout=10)\n logger.info(f\"Process group {pgid} terminated gracefully\")\n except subprocess.TimeoutExpired:\n # Force kill if not terminated\n logger.warning(\n f\"Process group {pgid} did not terminate, sending SIGKILL\"\n )\n os.killpg(pgid, signal.SIGKILL)\n self.process.wait()\n logger.info(f\"Process group {pgid} force killed\")\n\n except ProcessLookupError:\n # Process already dead\n logger.info(\"Process already terminated\")\n except PermissionError as e:\n # Fall back to terminating just the process\n logger.warning(\n f\"Permission denied for process group kill: {e}, falling back to process termination\"\n )\n self.process.terminate()\n try:\n self.process.wait(timeout=10)\n except subprocess.TimeoutExpired:\n self.process.kill()\n self.process.wait()\n elif hasattr(self.process, \"pid\"):\n # External server - kill entire process group or individual process\n try:\n pgid = self.process.pid\n killed = False\n\n # First attempt: try to kill process group\n try:\n os.killpg(pgid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process group {pgid}\")\n killed = True\n except (OSError, ProcessLookupError) as e:\n # Process group kill failed, try individual process\n logger.debug(\n f\"Process group kill failed: {e}, trying individual process\"\n )\n try:\n # Ensure pid is an integer (handle Mock objects)\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process {self.process.pid}\")\n killed = True\n except ProcessLookupError:\n # Process already dead\n logger.info(\n f\"Process {self.process.pid} already terminated\"\n )\n except OSError as e:\n logger.warning(\n f\"Failed to send SIGTERM to {self.process.pid}: {e}\"\n )\n\n if killed:\n # Wait for graceful shutdown\n time.sleep(2)\n\n # Check if still running and force kill if needed\n if self.is_running():\n try:\n os.killpg(pgid, signal.SIGKILL)\n logger.info(f\"Force killed process group {pgid}\")\n except (OSError, ProcessLookupError):\n # Process group kill failed, try individual\n try:\n # Ensure pid is an integer (handle Mock objects in tests)\n if hasattr(self.process, \"pid\"):\n try:\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGKILL)\n logger.info(f\"Force killed process {pid}\")\n except (TypeError, ValueError):\n # PID is not a valid integer (might be Mock)\n pass\n except ProcessLookupError:\n pass # Already dead\n except OSError as e:\n logger.error(\n f\"Failed to force kill {self.process.pid}: {e}\"\n )\n\n except Exception as e:\n logger.error(f\"Unexpected error stopping external server: {e}\")\n\n # Close log file if we have one\n if hasattr(self, \"log_file\") and self.log_file:\n self.log_file.close()\n\n # Remove from registry\n from .process import remove_server\n\n remove_server(self)\n\n logger.info(f\"vLLM server stopped for {self.model}\")\n return True\n\n except Exception as e:\n logger.error(f\"Error stopping vLLM server: {e}\")\n return False\n\n def is_running(self) -> bool:\n \"\"\"\n Check if the server is running.\n\n Returns:\n True if server is running, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n # Check if this is an external server (detected, not started by us)\n if hasattr(self.process, \"poll\"):\n # Normal subprocess\n return self.process.poll() is None\n elif hasattr(self.process, \"pid\"):\n # External server - check if PID still exists\n try:\n import psutil\n\n return psutil.pid_exists(self.process.pid)\n except ImportError:\n # Fallback to os method\n try:\n os.kill(self.process.pid, 0)\n return True\n except (OSError, ProcessLookupError):\n return False\n\n return False\n\n def get_status(self) -> Dict[str, Any]:\n \"\"\"\n Get server status information.\n\n Returns:\n Dictionary with status information\n \"\"\"\n status = {\n \"model\": self.model,\n \"port\": self.port,\n \"running\": self.is_running(),\n \"pid\": self.process.pid if self.process else None,\n \"start_time\": self.start_time.isoformat() if self.start_time else None,\n \"log_path\": str(self.log_path) if self.log_path else None,\n }\n\n if self.is_running() and self.start_time:\n uptime = datetime.now() - self.start_time\n status[\"uptime_seconds\"] = uptime.total_seconds()\n status[\"uptime_str\"] = str(uptime).split(\".\")[0]\n\n return status\n\n def wait_for_startup(self) -> bool:\n \"\"\"\n Wait for the server to complete startup.\n\n Monitors the server logs for startup completion indicators and verifies\n via HTTP endpoint. Will wait indefinitely until either startup completes\n or the process terminates.\n\n Returns:\n True if server started successfully, False if process terminated\n \"\"\"\n import time\n\n logger.info(f\"Waiting for {self.model} server to complete startup...\")\n\n # Track if we've seen startup indicators in logs\n log_indicates_ready = False\n\n while True:\n # Check if server is still running\n if not self.is_running():\n logger.error(\n f\"Server process for {self.model} terminated during startup\"\n )\n return False\n\n # Get recent logs to check for startup completion\n recent_logs = self.get_recent_logs(50)\n\n if recent_logs and not log_indicates_ready:\n # Check for startup completion indicators\n for log in recent_logs:\n log_lower = log.lower()\n # Look for the explicit \"Application startup complete\" message\n if \"application startup complete\" in log_lower:\n logger.debug(f\"Server {self.model} startup detected in logs\")\n log_indicates_ready = True\n break\n\n # Also check for other ready indicators as fallback\n if any(\n indicator in log_lower\n for indicator in [\n \"uvicorn running on\",\n \"started server process\",\n \"server is ready\",\n \"api server started\",\n ]\n ):\n logger.debug(\n f\"Server {self.model} startup detected via ready indicator\"\n )\n log_indicates_ready = True\n break\n\n # If logs indicate ready, verify via HTTP\n if log_indicates_ready:\n # Try to verify server is actually ready via HTTP\n port = self.config.get(\"port\")\n if port:\n try:\n import httpx\n\n with httpx.Client() as client:\n # Try /v1/models endpoint first (most reliable)\n response = client.get(\n f\"http://localhost:{port}/v1/models\", timeout=5.0\n )\n if response.status_code == 200:\n logger.info(\n f\"Server {self.model} startup complete \"\n \"(verified via HTTP)\"\n )\n return True\n except httpx.ConnectError:\n # Server not ready yet, continue waiting\n logger.debug(\n f\"Server {self.model} not accepting connections yet\"\n )\n except Exception as e:\n # Log but continue, might be network issue\n logger.debug(f\"HTTP verification failed: {e}\")\n else:\n # No port configured, trust the logs\n logger.info(\n f\"Server {self.model} startup complete (no port for verification)\"\n )\n return True\n\n # Small sleep to avoid busy waiting\n time.sleep(0.5)\n\n def get_recent_logs(self, n: int = 20) -> List[str]:\n \"\"\"\n Get recent log lines from the server output.\n\n Retrieves the most recent log lines from either the in-memory queue\n or the log file on disk. This method ensures logs are available even\n after the monitoring thread has processed them.\n\n Args:\n n: Number of recent lines to return (default: 20)\n\n Returns:\n List of recent log lines, with the most recent last\n \"\"\"\n # Update recent logs from queue\n self._update_recent_logs_from_queue()\n\n # Return from memory if available\n if self._recent_logs:\n return self._recent_logs[-n:]\n\n # Fallback to reading from file\n return self._read_logs_from_file(n)\n\n def _update_recent_logs_from_queue(self) -> None:\n \"\"\"\n Update the recent logs cache from the log queue.\n\n Drains all available log lines from the queue and adds them\n to the recent logs cache, maintaining a maximum of 100 lines.\n \"\"\"\n temp_logs = []\n\n # Get all available logs from queue (don't block)\n while not self.log_queue.empty():\n try:\n log_line = self.log_queue.get_nowait()\n temp_logs.append(log_line)\n except Empty:\n break\n\n if temp_logs:\n self._recent_logs.extend(temp_logs)\n # Keep only the last 100 logs in memory to prevent unbounded growth\n self._recent_logs = self._recent_logs[-100:]\n\n def _read_logs_from_file(self, n: int) -> List[str]:\n \"\"\"\n Read recent log lines from the log file.\n\n Args:\n n: Number of lines to read\n\n Returns:\n List of log lines from file\n \"\"\"\n if not (self.log_path and self.log_path.exists()):\n return []\n\n try:\n with open(self.log_path, \"r\") as f:\n file_logs = f.readlines()\n if file_logs:\n # Get last n lines, strip them\n logs = [line.strip() for line in file_logs[-n:]]\n # Update recent logs cache\n self._recent_logs = logs[-100:]\n return logs\n except Exception as e:\n logger.debug(f\"Error reading log file: {e}\")\n\n return []\n\n def restart(self) -> bool:\n \"\"\"\n Restart the server with the same configuration.\n\n Returns:\n True if restart successful, False otherwise\n \"\"\"\n logger.info(f\"Restarting vLLM server for {self.model}\")\n\n # Stop if running\n if self.is_running():\n self.stop()\n time.sleep(2) # Wait a bit before restarting\n\n # Start again\n return self.start()\n\n def health_check(self) -> bool:\n \"\"\"\n Perform a health check on the server.\n\n Returns:\n True if server is healthy, False otherwise\n \"\"\"\n if not self.is_running():\n return False\n\n try:\n import requests\n\n # Try to connect to the server\n response = requests.get(f\"http://localhost:{self.port}/health\", timeout=5)\n\n return response.status_code == 200\n\n except Exception:\n # If requests fails, just check process\n return self.is_running()", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 27979}, "tests/test_ollama_integration_fixed.py::23": {"resolved_imports": ["src/vllm_cli/models/cache.py", "src/vllm_cli/models/manager.py"], "used_names": ["ModelManager", "patch"], "enclosing_function": "test_cache_refresh_clears_and_refetches", "extracted_code": "# Source: src/vllm_cli/models/manager.py\nclass ModelManager:\n \"\"\"\n Manages model discovery, caching, and metadata operations.\n\n Provides a high-level interface for model operations including\n listing, searching, and retrieving model information with\n integrated caching for performance.\n \"\"\"\n\n def __init__(self):\n self.cache = ModelCache()\n\n def list_available_models(self, refresh: bool = False) -> List[Dict[str, Any]]:\n \"\"\"\n List all available downloaded models with caching.\n\n Model scanning can be expensive, so results are cached for a short time\n to improve performance when multiple UI components need model data.\n\n Args:\n refresh: Force refresh the model cache, ignoring TTL\n\n Returns:\n List of model dictionaries with keys:\n - name: Full model name (publisher/model)\n - size: Model size in bytes\n - path: Path to model directory\n - type: Model type (model, custom_model)\n - publisher: Model publisher/organization\n - display_name: Human-readable model name\n - metadata: Additional model metadata\n \"\"\"\n # If refresh is forced, clear cache first to ensure fresh data\n if refresh:\n self.cache.clear_cache()\n logger.debug(\"Cache cleared for forced refresh\")\n else:\n # Check cache only if not refreshing\n cached_models = self.cache.get_cached_models()\n if cached_models is not None:\n return cached_models\n\n # Fetch fresh model data\n models = scan_for_models()\n\n # Process and normalize model data\n processed_models = []\n for item in models:\n # Accept all model types from hf-model-tool\n model_types = [\"model\", \"custom_model\", \"ollama_model\", \"gguf_model\"]\n if item.get(\"type\") in model_types:\n # For Ollama/GGUF models, use the item directly (already formatted)\n if item.get(\"type\") in [\"ollama_model\", \"gguf_model\"]:\n processed_models.append(item)\n else:\n model_dict = build_model_dict(item)\n processed_models.append(model_dict)\n\n # Sort models by name\n processed_models.sort(key=lambda x: x[\"name\"])\n\n # Update cache\n self.cache.cache_models(processed_models)\n\n logger.info(f\"Found {len(processed_models)} models\")\n return processed_models\n\n def get_model_details(self, model_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get detailed information about a specific model.\n\n Args:\n model_name: Name of the model to get details for\n\n Returns:\n Dictionary with model details or None if not found\n \"\"\"\n # First, try to find from cached models\n models = self.list_available_models()\n model_info = None\n\n for model in models:\n if model[\"name\"] == model_name or model.get(\"display_name\") == model_name:\n model_info = model\n break\n\n if not model_info:\n logger.warning(f\"Model {model_name} not found\")\n return None\n\n # Build detailed information\n details = {\n \"name\": model_info[\"name\"],\n \"full_name\": model_info[\"name\"],\n \"path\": model_info.get(\"path\", \"\"),\n \"size\": model_info.get(\"size\", 0),\n \"type\": model_info.get(\"type\", \"model\"),\n \"publisher\": model_info.get(\"publisher\", \"unknown\"),\n \"display_name\": model_info.get(\"display_name\", model_name),\n }\n\n # Extract metadata if available\n metadata = model_info.get(\"metadata\", {})\n if metadata:\n details[\"architecture\"] = (\n metadata.get(\"architectures\", [\"unknown\"])[0]\n if metadata.get(\"architectures\")\n else \"unknown\"\n )\n details[\"model_type\"] = metadata.get(\"model_type\", \"unknown\")\n details[\"torch_dtype\"] = metadata.get(\"torch_dtype\", \"unknown\")\n details[\"vocab_size\"] = metadata.get(\"vocab_size\", \"unknown\")\n\n # Add to main details\n details[\"metadata\"] = metadata\n\n # Try to read config.json for more details if path exists\n if details[\"path\"]:\n from .metadata import extract_model_config\n\n config_data = extract_model_config(details[\"path\"])\n if config_data:\n details.update(config_data)\n\n return details\n\n def search_models(self, query: str) -> List[Dict[str, Any]]:\n \"\"\"\n Search for models matching a query.\n\n Args:\n query: Search query string\n\n Returns:\n List of matching models\n \"\"\"\n models = self.list_available_models()\n query_lower = query.lower()\n\n # Filter models matching the query\n matches = []\n for model in models:\n if (\n query_lower in model[\"name\"].lower()\n or query_lower in model.get(\"display_name\", \"\").lower()\n or query_lower in model.get(\"publisher\", \"\").lower()\n ):\n matches.append(model)\n\n return matches\n\n def get_model_count(self) -> int:\n \"\"\"\n Get the total number of available models.\n\n Returns:\n Number of available models\n \"\"\"\n return len(self.list_available_models())\n\n def get_models_by_publisher(self, publisher: str) -> List[Dict[str, Any]]:\n \"\"\"\n Get all models from a specific publisher.\n\n Args:\n publisher: Publisher/organization name\n\n Returns:\n List of models from the publisher\n \"\"\"\n models = self.list_available_models()\n return [\n model\n for model in models\n if model.get(\"publisher\", \"\").lower() == publisher.lower()\n ]\n\n def get_models_by_type(self, model_type: str) -> List[Dict[str, Any]]:\n \"\"\"\n Get all models of a specific type.\n\n Args:\n model_type: Type of model (e.g., 'model', 'custom_model')\n\n Returns:\n List of models of the specified type\n \"\"\"\n models = self.list_available_models()\n return [model for model in models if model.get(\"type\") == model_type]\n\n def refresh_cache(self) -> None:\n \"\"\"Force refresh of the model cache.\"\"\"\n # First, force registry refresh to pick up any changes\n try:\n import os\n from pathlib import Path\n\n from hf_model_tool import get_registry\n\n # Clear all possible cache files\n cache_locations = [\n Path.home() / \".config/hf-model-tool/registry_cache.json\",\n Path.home() / \".cache/hf-model-tool/registry.json\",\n Path.home() / \".hf-model-tool/cache.json\",\n ]\n\n for cache_file in cache_locations:\n if cache_file.exists():\n try:\n os.remove(cache_file)\n logger.debug(f\"Removed cache file: {cache_file}\")\n except Exception as e:\n logger.debug(f\"Could not remove {cache_file}: {e}\")\n\n # Get registry and clear its in-memory cache\n registry = get_registry()\n\n # Clear all in-memory collections\n registry.models.clear()\n registry.custom_models.clear()\n registry.ollama_models.clear()\n registry.gguf_models.clear()\n registry.lora_adapters.clear()\n registry.datasets.clear()\n\n # Reset scan time to force rescan\n registry._last_scan_time = 0\n\n # Force complete rescan without incremental updates\n registry.scan_all(force=True, incremental=False)\n logger.info(\"Forced complete registry refresh\")\n except Exception as e:\n logger.debug(f\"Registry refresh error: {e}\")\n\n # Clear the cache to ensure we don't get stale data\n self.cache.clear_cache()\n logger.debug(\"Cache cleared\")\n\n # Now fetch fresh models - this will populate the cache with new data\n models = self.list_available_models(refresh=True)\n logger.info(f\"Model cache refreshed with {len(models)} models\")\n\n def get_cache_stats(self) -> Dict[str, Any]:\n \"\"\"\n Get cache statistics.\n\n Returns:\n Dictionary with cache statistics\n \"\"\"\n return self.cache.get_cache_stats()", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 8654}, "tests/proxy/test_models.py::29": {"resolved_imports": ["src/vllm_cli/proxy/models.py"], "used_names": ["ModelConfig"], "enclosing_function": "test_model_config_creation", "extracted_code": "# Source: src/vllm_cli/proxy/models.py\nclass ModelConfig(BaseModel):\n \"\"\"Configuration for a single model in the proxy.\"\"\"\n\n name: str = Field(..., description=\"Model identifier for API requests\")\n model_path: str = Field(..., description=\"Path or HuggingFace model ID\")\n gpu_ids: List[int] = Field(default_factory=list, description=\"GPU IDs to use\")\n port: int = Field(..., description=\"Port for the vLLM server\")\n profile: Optional[str] = Field(None, description=\"vLLM CLI profile to use\")\n config_overrides: Dict[str, Any] = Field(\n default_factory=dict, description=\"Additional vLLM configuration\"\n )\n enabled: bool = Field(True, description=\"Whether model is enabled\")\n loading_priority: Optional[int] = Field(\n None,\n description=\"Loading priority (lower numbers load first). \"\n \"Models with same priority load in parallel. \"\n \"Models with None priority load after all prioritized models.\",\n )", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 967}, "tests/test_server_manager.py::38": {"resolved_imports": ["src/vllm_cli/server/__init__.py", "src/vllm_cli/server/process.py", "src/vllm_cli/server/manager.py"], "used_names": ["VLLMServer", "process"], "enclosing_function": "test_init", "extracted_code": "# Source: src/vllm_cli/server/__init__.py\n\nThis package provides comprehensive vLLM server management including\nprocess lifecycle, monitoring, discovery, and utilities.\n\nMain Components:\n- VLLMServer: Core server management class\n- Process management: Server registry and lifecycle\n- Discovery: External server detection\n- Monitoring: Health checks and metrics\n- Utils: Port management and cleanup utilities\n\"\"\"\n\n\n\n# Process management functions\nfrom .process import (\n add_server,\n cleanup_servers_on_exit,\n find_server_by_model,\n find_server_by_port,\n get_active_servers,\n remove_server,\n stop_all_servers,\n)\n\n\n\n# Source: src/vllm_cli/server/manager.py\nclass VLLMServer:\n \"\"\"\n Manages a vLLM server instance with comprehensive lifecycle control.\n\n This class handles the complete lifecycle of a vLLM server including\n configuration, process management, logging, monitoring, and cleanup.\n It supports both programmatically started servers and external server\n detection and management.\n\n Attributes:\n config: Server configuration dictionary\n model: Model name being served\n port: Port number the server is listening on\n process: Subprocess or external process reference\n log_file: File handle for server logs\n log_queue: Thread-safe queue for log lines\n log_thread: Background thread for log monitoring\n start_time: Timestamp when server was started\n log_path: Path to the server's log file\n \"\"\"\n\n def __init__(self, config: Dict[str, Any]) -> None:\n \"\"\"\n Initialize a vLLM server instance.\n\n Sets up the server configuration, logging infrastructure, and\n prepares the instance for server lifecycle management.\n\n Args:\n config: Server configuration dictionary containing model name,\n port, and other vLLM-specific parameters\n \"\"\"\n self.config: Dict[str, Any] = config\n\n # Extract model name - handle both string and dict (LoRA config) formats\n model_config = config.get(\"model\", \"unknown\")\n if isinstance(model_config, dict):\n # LoRA configuration - extract base model name\n self.model: str = model_config.get(\"model\", \"unknown\")\n else:\n # Regular string model name\n self.model: str = model_config\n\n self.port: int = config.get(\"port\", 8000)\n self.process: Optional[Union[subprocess.Popen, Any]] = None\n self.log_file: Optional[TextIO] = None\n self.log_queue: Queue[str] = Queue()\n self.log_thread: Optional[Thread] = None\n self.start_time: Optional[datetime] = None\n self.log_path: Path\n self._recent_logs: List[str] = []\n\n # Setup logging\n log_dir = Path.home() / \".vllm-cli\" / \"logs\"\n log_dir.mkdir(parents=True, exist_ok=True)\n\n timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n self.log_path = log_dir / f\"vllm_{self.model.replace('/', '_')}_{timestamp}.log\"\n\n def start(self) -> bool:\n \"\"\"\n Start the vLLM server.\n\n Returns:\n True if server started successfully, False otherwise\n \"\"\"\n if self.is_running():\n logger.warning(f\"Server already running for {self.model}\")\n return False\n\n try:\n # Build command - run directly without conda wrapper\n full_cmd = self._build_command()\n\n logger.info(f\"Starting vLLM server with command: {' '.join(full_cmd)}\")\n\n # Open log file for writing\n self.log_file = open(self.log_path, \"w\", buffering=1)\n\n # Start with parent environment\n env = os.environ.copy()\n # Note: No longer forcing PYTHONUNBUFFERED=1, let user control it\n\n # Layer 1: Apply universal environment variables from settings\n config_manager = ConfigManager()\n universal_env = config_manager.config.get(\"universal_environment\", {})\n if universal_env:\n logger.info(\n f\"Applying {len(universal_env)} universal environment variable(s)\"\n )\n for key, value in universal_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting universal {key}={value}\")\n else:\n logger.debug(f\"Setting universal {key}=\")\n\n # Layer 2: Apply profile environment variables (override universal)\n profile_env = self.config.get(\"profile_environment\", {})\n if profile_env:\n logger.info(\n f\"Applying {len(profile_env)} profile environment variable(s)\"\n )\n for key, value in profile_env.items():\n env[key] = str(value)\n # Log non-sensitive environment variables\n if \"KEY\" not in key.upper() and \"TOKEN\" not in key.upper():\n logger.debug(f\"Setting profile {key}={value}\")\n else:\n logger.debug(f\"Setting profile {key}=\")\n\n # Handle GPU device selection via CUDA_VISIBLE_DEVICES\n # This overrides any CUDA_VISIBLE_DEVICES from the profile\n if self.config.get(\"device\"):\n device_str = str(self.config[\"device\"])\n env[\"CUDA_VISIBLE_DEVICES\"] = device_str\n logger.info(f\"Setting CUDA_VISIBLE_DEVICES={device_str}\")\n\n # If using specific GPUs, adjust tensor parallel size if needed\n device_list = [d.strip() for d in device_str.split(\",\")]\n num_devices = len(device_list)\n\n # Check if tensor_parallel_size is set and compatible\n if self.config.get(\"tensor_parallel_size\"):\n tp_size = self.config[\"tensor_parallel_size\"]\n if tp_size > num_devices:\n logger.warning(\n f\"tensor_parallel_size ({tp_size}) > number of selected devices ({num_devices}). \"\n f\"Adjusting tensor_parallel_size to {num_devices}\"\n )\n self.config[\"tensor_parallel_size\"] = num_devices\n elif num_devices % tp_size != 0:\n logger.warning(\n f\"Number of GPUs ({num_devices}) is not evenly divisible by \"\n f\"tensor_parallel_size ({tp_size}). This may lead to inefficient GPU utilization. \"\n f\"Consider using tensor_parallel_size of: \"\n f\"{', '.join(str(i) for i in range(1, num_devices + 1) if num_devices % i == 0)}\"\n )\n\n # Add HuggingFace token if configured\n config_manager = ConfigManager()\n hf_token = config_manager.config.get(\"hf_token\")\n if hf_token:\n env[\"HF_TOKEN\"] = hf_token\n env[\"HUGGING_FACE_HUB_TOKEN\"] = hf_token # Some tools use this variant\n logger.info(\"HuggingFace token configured for server\")\n\n # Enable development mode for sleep endpoints if sleep mode is enabled\n if self.config.get(\"enable_sleep_mode\"):\n env[\"VLLM_SERVER_DEV_MODE\"] = \"1\"\n logger.info(\"Sleep mode enabled with development endpoints\")\n\n # Start the process with proper pipe configuration\n # Use start_new_session=True to create a new process group\n # This prevents the child process from receiving Ctrl+C signals\n self.process = subprocess.Popen(\n full_cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n text=True,\n bufsize=0, # Unbuffered\n universal_newlines=True,\n env=env,\n start_new_session=True, # Create new process group to isolate from parent signals\n )\n\n # Start log monitoring thread\n self._start_log_monitor()\n\n # Set start time and add to registry\n self.start_time = datetime.now()\n from .process import add_server\n\n add_server(self)\n\n # Return immediately - let the UI monitor the startup\n logger.info(\n f\"vLLM server process launched for {self.model} on port {self.port}\"\n )\n return True\n\n except Exception as e:\n logger.error(f\"Error starting vLLM server: {e}\")\n return False\n\n def _build_command(self) -> List[str]:\n \"\"\"\n Build the vLLM command from configuration using the schema.\n\n Returns:\n List of command arguments\n \"\"\"\n # Use the new ConfigManager to build CLI args\n config_manager = ConfigManager()\n\n # Start with the vllm command\n cmd = [\"vllm\"]\n\n # Add the arguments built from schema\n cli_args = config_manager.build_cli_args(self.config)\n cmd.extend(cli_args)\n\n # Handle extra_args if present (backward compatibility)\n if self.config.get(\"extra_args\"):\n self._add_extra_args_to_command(cmd)\n\n logger.debug(f\"Built command: {' '.join(cmd)}\")\n return cmd\n\n def _add_extra_args_to_command(self, cmd: List[str]) -> None:\n \"\"\"\n Add extra arguments to the vLLM command.\n\n Args:\n cmd: Command list to extend with extra arguments\n \"\"\"\n try:\n extra_args = shlex.split(self.config[\"extra_args\"])\n if extra_args:\n logger.info(f\"Adding extra arguments: {extra_args}\")\n cmd.extend(extra_args)\n except ValueError as e:\n logger.warning(f\"Failed to parse extra_args: {e}\")\n\n def _start_log_monitor(self) -> None:\n \"\"\"\n Start a thread to monitor log output from the vLLM server process.\n\n Creates a daemon thread that continuously reads stdout/stderr from\n the server process, writes to log files, and queues log lines for\n real-time display in the UI.\n \"\"\"\n self.log_thread = Thread(target=self._log_monitor_worker, daemon=True)\n self.log_thread.start()\n\n def _log_monitor_worker(self) -> None:\n \"\"\"\n Worker function for log monitoring thread.\n\n Continuously reads log output from the server process and handles\n file writing and queue management for UI display.\n \"\"\"\n try:\n self.log_queue.put(\"Starting vLLM server process...\")\n\n while self._should_continue_monitoring():\n if self._process_log_line():\n continue\n else:\n # No line read, check if process still running\n if self.process and self.process.poll() is not None:\n break\n time.sleep(0.01) # Small sleep to prevent busy waiting\n\n except Exception as e:\n logger.error(f\"Error in log monitor: {e}\")\n self.log_queue.put(f\"Log monitoring error: {e}\")\n\n def _should_continue_monitoring(self) -> bool:\n \"\"\"\n Check if log monitoring should continue.\n\n Returns:\n True if monitoring should continue, False otherwise\n \"\"\"\n return (\n self.is_running()\n and self.process\n and hasattr(self.process, \"stdout\")\n and self.process.stdout\n )\n\n def _process_log_line(self) -> bool:\n \"\"\"\n Process a single log line from the server output.\n\n Reads one line from the process stdout, writes it to the log file,\n and adds it to the queue for UI display after filtering and formatting.\n\n Returns:\n True if a line was processed, False if no line was available\n \"\"\"\n if not (self.process and self.process.stdout):\n return False\n\n line = self.process.stdout.readline()\n if not line:\n return False\n\n # Write to log file\n self._write_to_log_file(line)\n\n # Process for UI display\n line_stripped = line.strip()\n if line_stripped and self._should_display_log_line(line_stripped):\n # Truncate overly long lines\n if len(line_stripped) > 200:\n line_stripped = line_stripped[:197] + \"...\"\n\n self.log_queue.put(line_stripped)\n logger.debug(f\"Log captured: {line_stripped[:50]}...\")\n\n return True\n\n def _write_to_log_file(self, line: str) -> None:\n \"\"\"\n Write a log line to the log file.\n\n Args:\n line: Log line to write\n \"\"\"\n if self.log_file and not self.log_file.closed:\n self.log_file.write(line)\n self.log_file.flush()\n\n def _should_display_log_line(self, line: str) -> bool:\n \"\"\"\n Determine if a log line should be displayed in the UI.\n\n Filters out certain system messages that are not useful for users.\n\n Args:\n line: Stripped log line to check\n\n Returns:\n True if the line should be displayed, False otherwise\n \"\"\"\n # Filter out conda activation and system messages\n filtered_messages = [\n \"Activated CUDA\",\n \"Using nvcc from:\",\n \"Cuda compilation tools\",\n ]\n return not any(skip in line for skip in filtered_messages)\n\n def stop(self) -> bool:\n \"\"\"\n Stop the vLLM server.\n\n Returns:\n True if server stopped successfully, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n try:\n # Check if this is an external server\n if hasattr(self.process, \"terminate\"):\n # Normal subprocess\n # Since we created a new session, we need to terminate the entire process group\n try:\n # Get the process group ID (pgid)\n # Since we used start_new_session=True, the pgid is the same as the pid\n pgid = self.process.pid\n\n # Send SIGTERM to the entire process group for graceful shutdown\n logger.info(f\"Sending SIGTERM to process group {pgid}\")\n os.killpg(pgid, signal.SIGTERM)\n\n # Wait for process to terminate\n try:\n self.process.wait(timeout=10)\n logger.info(f\"Process group {pgid} terminated gracefully\")\n except subprocess.TimeoutExpired:\n # Force kill if not terminated\n logger.warning(\n f\"Process group {pgid} did not terminate, sending SIGKILL\"\n )\n os.killpg(pgid, signal.SIGKILL)\n self.process.wait()\n logger.info(f\"Process group {pgid} force killed\")\n\n except ProcessLookupError:\n # Process already dead\n logger.info(\"Process already terminated\")\n except PermissionError as e:\n # Fall back to terminating just the process\n logger.warning(\n f\"Permission denied for process group kill: {e}, falling back to process termination\"\n )\n self.process.terminate()\n try:\n self.process.wait(timeout=10)\n except subprocess.TimeoutExpired:\n self.process.kill()\n self.process.wait()\n elif hasattr(self.process, \"pid\"):\n # External server - kill entire process group or individual process\n try:\n pgid = self.process.pid\n killed = False\n\n # First attempt: try to kill process group\n try:\n os.killpg(pgid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process group {pgid}\")\n killed = True\n except (OSError, ProcessLookupError) as e:\n # Process group kill failed, try individual process\n logger.debug(\n f\"Process group kill failed: {e}, trying individual process\"\n )\n try:\n # Ensure pid is an integer (handle Mock objects)\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGTERM)\n logger.info(f\"Sent SIGTERM to process {self.process.pid}\")\n killed = True\n except ProcessLookupError:\n # Process already dead\n logger.info(\n f\"Process {self.process.pid} already terminated\"\n )\n except OSError as e:\n logger.warning(\n f\"Failed to send SIGTERM to {self.process.pid}: {e}\"\n )\n\n if killed:\n # Wait for graceful shutdown\n time.sleep(2)\n\n # Check if still running and force kill if needed\n if self.is_running():\n try:\n os.killpg(pgid, signal.SIGKILL)\n logger.info(f\"Force killed process group {pgid}\")\n except (OSError, ProcessLookupError):\n # Process group kill failed, try individual\n try:\n # Ensure pid is an integer (handle Mock objects in tests)\n if hasattr(self.process, \"pid\"):\n try:\n pid = int(self.process.pid)\n os.kill(pid, signal.SIGKILL)\n logger.info(f\"Force killed process {pid}\")\n except (TypeError, ValueError):\n # PID is not a valid integer (might be Mock)\n pass\n except ProcessLookupError:\n pass # Already dead\n except OSError as e:\n logger.error(\n f\"Failed to force kill {self.process.pid}: {e}\"\n )\n\n except Exception as e:\n logger.error(f\"Unexpected error stopping external server: {e}\")\n\n # Close log file if we have one\n if hasattr(self, \"log_file\") and self.log_file:\n self.log_file.close()\n\n # Remove from registry\n from .process import remove_server\n\n remove_server(self)\n\n logger.info(f\"vLLM server stopped for {self.model}\")\n return True\n\n except Exception as e:\n logger.error(f\"Error stopping vLLM server: {e}\")\n return False\n\n def is_running(self) -> bool:\n \"\"\"\n Check if the server is running.\n\n Returns:\n True if server is running, False otherwise\n \"\"\"\n if not self.process:\n return False\n\n # Check if this is an external server (detected, not started by us)\n if hasattr(self.process, \"poll\"):\n # Normal subprocess\n return self.process.poll() is None\n elif hasattr(self.process, \"pid\"):\n # External server - check if PID still exists\n try:\n import psutil\n\n return psutil.pid_exists(self.process.pid)\n except ImportError:\n # Fallback to os method\n try:\n os.kill(self.process.pid, 0)\n return True\n except (OSError, ProcessLookupError):\n return False\n\n return False\n\n def get_status(self) -> Dict[str, Any]:\n \"\"\"\n Get server status information.\n\n Returns:\n Dictionary with status information\n \"\"\"\n status = {\n \"model\": self.model,\n \"port\": self.port,\n \"running\": self.is_running(),\n \"pid\": self.process.pid if self.process else None,\n \"start_time\": self.start_time.isoformat() if self.start_time else None,\n \"log_path\": str(self.log_path) if self.log_path else None,\n }\n\n if self.is_running() and self.start_time:\n uptime = datetime.now() - self.start_time\n status[\"uptime_seconds\"] = uptime.total_seconds()\n status[\"uptime_str\"] = str(uptime).split(\".\")[0]\n\n return status\n\n def wait_for_startup(self) -> bool:\n \"\"\"\n Wait for the server to complete startup.\n\n Monitors the server logs for startup completion indicators and verifies\n via HTTP endpoint. Will wait indefinitely until either startup completes\n or the process terminates.\n\n Returns:\n True if server started successfully, False if process terminated\n \"\"\"\n import time\n\n logger.info(f\"Waiting for {self.model} server to complete startup...\")\n\n # Track if we've seen startup indicators in logs\n log_indicates_ready = False\n\n while True:\n # Check if server is still running\n if not self.is_running():\n logger.error(\n f\"Server process for {self.model} terminated during startup\"\n )\n return False\n\n # Get recent logs to check for startup completion\n recent_logs = self.get_recent_logs(50)\n\n if recent_logs and not log_indicates_ready:\n # Check for startup completion indicators\n for log in recent_logs:\n log_lower = log.lower()\n # Look for the explicit \"Application startup complete\" message\n if \"application startup complete\" in log_lower:\n logger.debug(f\"Server {self.model} startup detected in logs\")\n log_indicates_ready = True\n break\n\n # Also check for other ready indicators as fallback\n if any(\n indicator in log_lower\n for indicator in [\n \"uvicorn running on\",\n \"started server process\",\n \"server is ready\",\n \"api server started\",\n ]\n ):\n logger.debug(\n f\"Server {self.model} startup detected via ready indicator\"\n )\n log_indicates_ready = True\n break\n\n # If logs indicate ready, verify via HTTP\n if log_indicates_ready:\n # Try to verify server is actually ready via HTTP\n port = self.config.get(\"port\")\n if port:\n try:\n import httpx\n\n with httpx.Client() as client:\n # Try /v1/models endpoint first (most reliable)\n response = client.get(\n f\"http://localhost:{port}/v1/models\", timeout=5.0\n )\n if response.status_code == 200:\n logger.info(\n f\"Server {self.model} startup complete \"\n \"(verified via HTTP)\"\n )\n return True\n except httpx.ConnectError:\n # Server not ready yet, continue waiting\n logger.debug(\n f\"Server {self.model} not accepting connections yet\"\n )\n except Exception as e:\n # Log but continue, might be network issue\n logger.debug(f\"HTTP verification failed: {e}\")\n else:\n # No port configured, trust the logs\n logger.info(\n f\"Server {self.model} startup complete (no port for verification)\"\n )\n return True\n\n # Small sleep to avoid busy waiting\n time.sleep(0.5)\n\n def get_recent_logs(self, n: int = 20) -> List[str]:\n \"\"\"\n Get recent log lines from the server output.\n\n Retrieves the most recent log lines from either the in-memory queue\n or the log file on disk. This method ensures logs are available even\n after the monitoring thread has processed them.\n\n Args:\n n: Number of recent lines to return (default: 20)\n\n Returns:\n List of recent log lines, with the most recent last\n \"\"\"\n # Update recent logs from queue\n self._update_recent_logs_from_queue()\n\n # Return from memory if available\n if self._recent_logs:\n return self._recent_logs[-n:]\n\n # Fallback to reading from file\n return self._read_logs_from_file(n)\n\n def _update_recent_logs_from_queue(self) -> None:\n \"\"\"\n Update the recent logs cache from the log queue.\n\n Drains all available log lines from the queue and adds them\n to the recent logs cache, maintaining a maximum of 100 lines.\n \"\"\"\n temp_logs = []\n\n # Get all available logs from queue (don't block)\n while not self.log_queue.empty():\n try:\n log_line = self.log_queue.get_nowait()\n temp_logs.append(log_line)\n except Empty:\n break\n\n if temp_logs:\n self._recent_logs.extend(temp_logs)\n # Keep only the last 100 logs in memory to prevent unbounded growth\n self._recent_logs = self._recent_logs[-100:]\n\n def _read_logs_from_file(self, n: int) -> List[str]:\n \"\"\"\n Read recent log lines from the log file.\n\n Args:\n n: Number of lines to read\n\n Returns:\n List of log lines from file\n \"\"\"\n if not (self.log_path and self.log_path.exists()):\n return []\n\n try:\n with open(self.log_path, \"r\") as f:\n file_logs = f.readlines()\n if file_logs:\n # Get last n lines, strip them\n logs = [line.strip() for line in file_logs[-n:]]\n # Update recent logs cache\n self._recent_logs = logs[-100:]\n return logs\n except Exception as e:\n logger.debug(f\"Error reading log file: {e}\")\n\n return []\n\n def restart(self) -> bool:\n \"\"\"\n Restart the server with the same configuration.\n\n Returns:\n True if restart successful, False otherwise\n \"\"\"\n logger.info(f\"Restarting vLLM server for {self.model}\")\n\n # Stop if running\n if self.is_running():\n self.stop()\n time.sleep(2) # Wait a bit before restarting\n\n # Start again\n return self.start()\n\n def health_check(self) -> bool:\n \"\"\"\n Perform a health check on the server.\n\n Returns:\n True if server is healthy, False otherwise\n \"\"\"\n if not self.is_running():\n return False\n\n try:\n import requests\n\n # Try to connect to the server\n response = requests.get(f\"http://localhost:{self.port}/health\", timeout=5)\n\n return response.status_code == 200\n\n except Exception:\n # If requests fails, just check process\n return self.is_running()", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 28614}, "tests/test_ollama_integration_fixed.py::122": {"resolved_imports": ["src/vllm_cli/models/cache.py", "src/vllm_cli/models/manager.py"], "used_names": ["ModelCache"], "enclosing_function": "test_cache_stats_after_refresh", "extracted_code": "# Source: src/vllm_cli/models/cache.py\nclass ModelCache:\n \"\"\"\n Cache for model discovery results.\n\n Provides time-based caching of model listings to avoid expensive\n directory scanning operations when model data is accessed frequently.\n \"\"\"\n\n def __init__(self, ttl_seconds: float = 30.0):\n \"\"\"\n Initialize model cache.\n\n Args:\n ttl_seconds: Time-to-live for cached data in seconds\n \"\"\"\n self.ttl_seconds = ttl_seconds\n self._cache: Optional[Tuple[float, List[Dict[str, Any]]]] = None\n self._stats = {\"hits\": 0, \"misses\": 0, \"updates\": 0}\n\n def get_cached_models(self) -> Optional[List[Dict[str, Any]]]:\n \"\"\"\n Get cached model list if still valid.\n\n Returns:\n List of cached models if cache is valid, None if expired or empty\n \"\"\"\n if self._cache is None:\n self._stats[\"misses\"] += 1\n return None\n\n cache_time, cached_data = self._cache\n\n # Check if cache is still valid\n if time.time() - cache_time < self.ttl_seconds:\n self._stats[\"hits\"] += 1\n logger.debug(f\"Cache hit: returning {len(cached_data)} cached models\")\n return cached_data.copy() # Return copy to prevent modification\n else:\n # Cache expired\n self._stats[\"misses\"] += 1\n logger.debug(\"Cache expired\")\n self._cache = None\n return None\n\n def cache_models(self, models: List[Dict[str, Any]]) -> None:\n \"\"\"\n Cache a list of models.\n\n Args:\n models: List of model dictionaries to cache\n \"\"\"\n self._cache = (time.time(), models.copy())\n self._stats[\"updates\"] += 1\n logger.debug(f\"Cached {len(models)} models\")\n\n def clear_cache(self) -> None:\n \"\"\"Clear the model cache.\"\"\"\n self._cache = None\n # Increment misses to reflect that the next access will be a miss\n self._stats[\"misses\"] += 1\n logger.debug(\"Model cache cleared\")\n\n def is_cached(self) -> bool:\n \"\"\"\n Check if there is valid cached data.\n\n Returns:\n True if cache contains valid data, False otherwise\n \"\"\"\n if self._cache is None:\n return False\n\n cache_time, _ = self._cache\n return time.time() - cache_time < self.ttl_seconds\n\n def get_cache_age(self) -> Optional[float]:\n \"\"\"\n Get the age of cached data in seconds.\n\n Returns:\n Age in seconds if cache exists, None if no cache\n \"\"\"\n if self._cache is None:\n return None\n\n cache_time, _ = self._cache\n return time.time() - cache_time\n\n def get_cache_stats(self) -> Dict[str, Any]:\n \"\"\"\n Get cache statistics.\n\n Returns:\n Dictionary with cache performance statistics\n \"\"\"\n total_requests = self._stats[\"hits\"] + self._stats[\"misses\"]\n hit_rate = (\n (self._stats[\"hits\"] / total_requests * 100) if total_requests > 0 else 0\n )\n\n stats = {\n \"hits\": self._stats[\"hits\"],\n \"misses\": self._stats[\"misses\"],\n \"updates\": self._stats[\"updates\"],\n \"total_requests\": total_requests,\n \"hit_rate_percent\": round(hit_rate, 2),\n \"is_cached\": self.is_cached(),\n \"cache_age_seconds\": self.get_cache_age(),\n \"ttl_seconds\": self.ttl_seconds,\n }\n\n if self._cache:\n _, cached_data = self._cache\n stats[\"cached_models_count\"] = len(cached_data)\n else:\n stats[\"cached_models_count\"] = 0\n\n return stats\n\n def get_stats(self) -> Dict[str, Any]:\n \"\"\"\n Alias for get_cache_stats() for backward compatibility.\n\n Returns:\n Dictionary with cache performance statistics\n \"\"\"\n return self.get_cache_stats()\n\n def reset_stats(self) -> None:\n \"\"\"Reset cache statistics.\"\"\"\n self._stats = {\"hits\": 0, \"misses\": 0, \"updates\": 0}\n logger.debug(\"Cache statistics reset\")\n\n def set_ttl(self, ttl_seconds: float) -> None:\n \"\"\"\n Set new TTL for cache.\n\n Args:\n ttl_seconds: New time-to-live in seconds\n \"\"\"\n old_ttl = self.ttl_seconds\n self.ttl_seconds = ttl_seconds\n logger.debug(f\"Cache TTL changed from {old_ttl}s to {ttl_seconds}s\")\n\n def get_cached_model_count(self) -> int:\n \"\"\"\n Get the number of models currently cached.\n\n Returns:\n Number of cached models, 0 if no cache\n \"\"\"\n if self._cache is None:\n return 0\n\n _, cached_data = self._cache\n return len(cached_data)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 4761}, "tests/test_ollama_support.py::34": {"resolved_imports": ["src/vllm_cli/models/discovery.py", "src/vllm_cli/models/manager.py"], "used_names": ["build_model_dict"], "enclosing_function": "test_build_model_dict_with_ollama", "extracted_code": "# Source: src/vllm_cli/models/discovery.py\ndef build_model_dict(item: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Build a standardized model dictionary from model data.\n\n Takes raw model information from various sources and normalizes\n it into a consistent format.\n\n Args:\n item: Model item data\n\n Returns:\n Standardized model dictionary\n \"\"\"\n publisher = item.get(\"publisher\", \"unknown\")\n display_name = item.get(\"display_name\", item.get(\"name\", \"unknown\"))\n\n # Create proper model name\n if publisher and publisher != \"unknown\":\n model_name = f\"{publisher}/{display_name}\"\n else:\n model_name = display_name\n\n return {\n \"name\": model_name,\n \"size\": item.get(\"size\", 0),\n \"path\": item.get(\"path\", \"\"),\n \"type\": item.get(\"type\", \"model\"),\n \"publisher\": publisher,\n \"display_name\": display_name,\n \"metadata\": item.get(\"metadata\", {}),\n }", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 950}, "tests/test_custom_directory_integration.py::168": {"resolved_imports": ["src/vllm_cli/models/manager.py", "src/vllm_cli/models/manifest.py"], "used_names": ["apply_manifest_to_models", "load_manifest"], "enclosing_function": "test_manifest_loading", "extracted_code": "# Source: src/vllm_cli/models/manifest.py\ndef load_manifest(directory: Union[str, Path]) -> Optional[Dict[str, Any]]:\n \"\"\"\n Load manifest from a directory if it exists.\n\n Args:\n directory: Path to directory containing manifest\n\n Returns:\n Manifest data or None if not found/invalid\n \"\"\"\n directory = Path(directory)\n manifest_path = directory / MANIFEST_FILENAME\n\n if not manifest_path.exists():\n logger.debug(f\"No manifest found at {manifest_path}\")\n return None\n\n try:\n with open(manifest_path, \"r\") as f:\n manifest = json.load(f)\n\n logger.info(f\"Loaded manifest from {manifest_path}\")\n return manifest\n\n except (json.JSONDecodeError, OSError) as e:\n logger.error(f\"Error loading manifest from {manifest_path}: {e}\")\n return None\n\ndef apply_manifest_to_models(\n models: List[Dict[str, Any]], directory: Path\n) -> List[Dict[str, Any]]:\n \"\"\"\n Apply manifest data to discovered models if manifest exists.\n\n Args:\n models: List of discovered models\n directory: Directory to check for manifest\n\n Returns:\n Updated models list with manifest data applied\n \"\"\"\n manifest = load_manifest(directory)\n if not manifest:\n return models\n\n manifest_models = manifest.get(\"models\", [])\n manifest_by_path = {}\n\n # Build lookup by path\n for entry in manifest_models:\n if entry.get(\"enabled\", True):\n # Resolve path\n model_path = directory / entry[\"path\"]\n manifest_by_path[str(model_path)] = entry\n\n # Apply manifest data to models\n updated_models = []\n for model in models:\n model_path = model.get(\"path\", \"\")\n\n if model_path in manifest_by_path:\n manifest_entry = manifest_by_path[model_path]\n # Override with manifest data\n model[\"name\"] = manifest_entry.get(\"name\", model[\"name\"])\n model[\"display_name\"] = manifest_entry.get(\"name\", model[\"display_name\"])\n model[\"publisher\"] = manifest_entry.get(\n \"publisher\", model.get(\"publisher\", \"unknown\")\n )\n model[\"notes\"] = manifest_entry.get(\"notes\", \"\")\n model[\"from_manifest\"] = True\n\n updated_models.append(model)\n\n return updated_models", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 2316}, "tests/test_ollama_integration_fixed.py::69": {"resolved_imports": ["src/vllm_cli/models/cache.py", "src/vllm_cli/models/manager.py"], "used_names": ["ModelManager"], "enclosing_function": "test_refresh_cache_method", "extracted_code": "# Source: src/vllm_cli/models/manager.py\nclass ModelManager:\n \"\"\"\n Manages model discovery, caching, and metadata operations.\n\n Provides a high-level interface for model operations including\n listing, searching, and retrieving model information with\n integrated caching for performance.\n \"\"\"\n\n def __init__(self):\n self.cache = ModelCache()\n\n def list_available_models(self, refresh: bool = False) -> List[Dict[str, Any]]:\n \"\"\"\n List all available downloaded models with caching.\n\n Model scanning can be expensive, so results are cached for a short time\n to improve performance when multiple UI components need model data.\n\n Args:\n refresh: Force refresh the model cache, ignoring TTL\n\n Returns:\n List of model dictionaries with keys:\n - name: Full model name (publisher/model)\n - size: Model size in bytes\n - path: Path to model directory\n - type: Model type (model, custom_model)\n - publisher: Model publisher/organization\n - display_name: Human-readable model name\n - metadata: Additional model metadata\n \"\"\"\n # If refresh is forced, clear cache first to ensure fresh data\n if refresh:\n self.cache.clear_cache()\n logger.debug(\"Cache cleared for forced refresh\")\n else:\n # Check cache only if not refreshing\n cached_models = self.cache.get_cached_models()\n if cached_models is not None:\n return cached_models\n\n # Fetch fresh model data\n models = scan_for_models()\n\n # Process and normalize model data\n processed_models = []\n for item in models:\n # Accept all model types from hf-model-tool\n model_types = [\"model\", \"custom_model\", \"ollama_model\", \"gguf_model\"]\n if item.get(\"type\") in model_types:\n # For Ollama/GGUF models, use the item directly (already formatted)\n if item.get(\"type\") in [\"ollama_model\", \"gguf_model\"]:\n processed_models.append(item)\n else:\n model_dict = build_model_dict(item)\n processed_models.append(model_dict)\n\n # Sort models by name\n processed_models.sort(key=lambda x: x[\"name\"])\n\n # Update cache\n self.cache.cache_models(processed_models)\n\n logger.info(f\"Found {len(processed_models)} models\")\n return processed_models\n\n def get_model_details(self, model_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"\n Get detailed information about a specific model.\n\n Args:\n model_name: Name of the model to get details for\n\n Returns:\n Dictionary with model details or None if not found\n \"\"\"\n # First, try to find from cached models\n models = self.list_available_models()\n model_info = None\n\n for model in models:\n if model[\"name\"] == model_name or model.get(\"display_name\") == model_name:\n model_info = model\n break\n\n if not model_info:\n logger.warning(f\"Model {model_name} not found\")\n return None\n\n # Build detailed information\n details = {\n \"name\": model_info[\"name\"],\n \"full_name\": model_info[\"name\"],\n \"path\": model_info.get(\"path\", \"\"),\n \"size\": model_info.get(\"size\", 0),\n \"type\": model_info.get(\"type\", \"model\"),\n \"publisher\": model_info.get(\"publisher\", \"unknown\"),\n \"display_name\": model_info.get(\"display_name\", model_name),\n }\n\n # Extract metadata if available\n metadata = model_info.get(\"metadata\", {})\n if metadata:\n details[\"architecture\"] = (\n metadata.get(\"architectures\", [\"unknown\"])[0]\n if metadata.get(\"architectures\")\n else \"unknown\"\n )\n details[\"model_type\"] = metadata.get(\"model_type\", \"unknown\")\n details[\"torch_dtype\"] = metadata.get(\"torch_dtype\", \"unknown\")\n details[\"vocab_size\"] = metadata.get(\"vocab_size\", \"unknown\")\n\n # Add to main details\n details[\"metadata\"] = metadata\n\n # Try to read config.json for more details if path exists\n if details[\"path\"]:\n from .metadata import extract_model_config\n\n config_data = extract_model_config(details[\"path\"])\n if config_data:\n details.update(config_data)\n\n return details\n\n def search_models(self, query: str) -> List[Dict[str, Any]]:\n \"\"\"\n Search for models matching a query.\n\n Args:\n query: Search query string\n\n Returns:\n List of matching models\n \"\"\"\n models = self.list_available_models()\n query_lower = query.lower()\n\n # Filter models matching the query\n matches = []\n for model in models:\n if (\n query_lower in model[\"name\"].lower()\n or query_lower in model.get(\"display_name\", \"\").lower()\n or query_lower in model.get(\"publisher\", \"\").lower()\n ):\n matches.append(model)\n\n return matches\n\n def get_model_count(self) -> int:\n \"\"\"\n Get the total number of available models.\n\n Returns:\n Number of available models\n \"\"\"\n return len(self.list_available_models())\n\n def get_models_by_publisher(self, publisher: str) -> List[Dict[str, Any]]:\n \"\"\"\n Get all models from a specific publisher.\n\n Args:\n publisher: Publisher/organization name\n\n Returns:\n List of models from the publisher\n \"\"\"\n models = self.list_available_models()\n return [\n model\n for model in models\n if model.get(\"publisher\", \"\").lower() == publisher.lower()\n ]\n\n def get_models_by_type(self, model_type: str) -> List[Dict[str, Any]]:\n \"\"\"\n Get all models of a specific type.\n\n Args:\n model_type: Type of model (e.g., 'model', 'custom_model')\n\n Returns:\n List of models of the specified type\n \"\"\"\n models = self.list_available_models()\n return [model for model in models if model.get(\"type\") == model_type]\n\n def refresh_cache(self) -> None:\n \"\"\"Force refresh of the model cache.\"\"\"\n # First, force registry refresh to pick up any changes\n try:\n import os\n from pathlib import Path\n\n from hf_model_tool import get_registry\n\n # Clear all possible cache files\n cache_locations = [\n Path.home() / \".config/hf-model-tool/registry_cache.json\",\n Path.home() / \".cache/hf-model-tool/registry.json\",\n Path.home() / \".hf-model-tool/cache.json\",\n ]\n\n for cache_file in cache_locations:\n if cache_file.exists():\n try:\n os.remove(cache_file)\n logger.debug(f\"Removed cache file: {cache_file}\")\n except Exception as e:\n logger.debug(f\"Could not remove {cache_file}: {e}\")\n\n # Get registry and clear its in-memory cache\n registry = get_registry()\n\n # Clear all in-memory collections\n registry.models.clear()\n registry.custom_models.clear()\n registry.ollama_models.clear()\n registry.gguf_models.clear()\n registry.lora_adapters.clear()\n registry.datasets.clear()\n\n # Reset scan time to force rescan\n registry._last_scan_time = 0\n\n # Force complete rescan without incremental updates\n registry.scan_all(force=True, incremental=False)\n logger.info(\"Forced complete registry refresh\")\n except Exception as e:\n logger.debug(f\"Registry refresh error: {e}\")\n\n # Clear the cache to ensure we don't get stale data\n self.cache.clear_cache()\n logger.debug(\"Cache cleared\")\n\n # Now fetch fresh models - this will populate the cache with new data\n models = self.list_available_models(refresh=True)\n logger.info(f\"Model cache refreshed with {len(models)} models\")\n\n def get_cache_stats(self) -> Dict[str, Any]:\n \"\"\"\n Get cache statistics.\n\n Returns:\n Dictionary with cache statistics\n \"\"\"\n return self.cache.get_cache_stats()", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 8654}, "tests/test_config_manager.py::103": {"resolved_imports": ["src/vllm_cli/config/manager.py"], "used_names": ["ConfigManager", "patch", "yaml"], "enclosing_function": "test_get_last_config", "extracted_code": "# Source: src/vllm_cli/config/manager.py\nclass ConfigManager:\n \"\"\"\n Enhanced configuration manager with comprehensive validation support.\n\n This class manages configuration files, profiles, and validation using\n the new validation framework. It provides a clean API for configuration\n operations while ensuring data integrity through comprehensive validation.\n\n Attributes:\n config_dir: Directory for configuration files\n validation_registry: Registry of validation rules\n compatibility_validator: Validator for parameter combinations\n \"\"\"\n\n def __init__(self):\n # Paths for configuration files\n self.config_dir = Path.home() / \".config\" / \"vllm-cli\"\n self.config_file = self.config_dir / \"config.yaml\"\n\n # Ensure config directory exists\n self.config_dir.mkdir(parents=True, exist_ok=True)\n\n # Initialize sub-managers\n self.schema_manager = SchemaManager()\n self.profile_manager = ProfileManager(self.config_dir)\n self.persistence_manager = PersistenceManager()\n self.shortcut_manager = ShortcutManager(self.config_dir)\n\n # Initialize validation system\n self.validation_registry = create_vllm_validation_registry()\n self.compatibility_validator = create_compatibility_validator(\n self.validation_registry\n )\n\n # Load main configuration\n self.config = self._load_config()\n\n def _load_config(self) -> Dict[str, Any]:\n \"\"\"Load main configuration file (legacy YAML support).\"\"\"\n return self.persistence_manager.load_yaml_file(self.config_file)\n\n def _save_config(self) -> None:\n \"\"\"Save main configuration file.\"\"\"\n self.persistence_manager.save_yaml_file(self.config_file, self.config)\n\n def get_argument_info(self, arg_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get detailed information about a specific argument.\"\"\"\n return self.schema_manager.get_argument_info(arg_name)\n\n def get_arguments_by_category(self, category: str) -> List[Dict[str, Any]]:\n \"\"\"Get all arguments belonging to a specific category.\"\"\"\n return self.schema_manager.get_arguments_by_category(category)\n\n def get_category_info(self, category: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get information about a specific category.\"\"\"\n return self.schema_manager.get_category_info(category)\n\n def get_ordered_categories(self) -> List[Tuple[str, Dict[str, Any]]]:\n \"\"\"Get categories ordered by their display order.\"\"\"\n return self.schema_manager.get_ordered_categories()\n\n def get_all_profiles(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all profiles (default and user-created).\"\"\"\n return self.profile_manager.get_all_profiles()\n\n def get_profile(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific profile by name with dynamic defaults applied.\"\"\"\n profile = self.profile_manager.get_profile(name)\n if profile and \"config\" in profile:\n # Apply dynamic defaults to the profile configuration\n profile[\"config\"] = self.profile_manager.apply_dynamic_defaults(\n profile[\"config\"]\n )\n return profile\n\n def save_user_profile(self, name: str, profile: Dict[str, Any]) -> bool:\n \"\"\"Save or update a user profile with validation.\"\"\"\n # Validate profile configuration if present\n if \"config\" in profile:\n is_valid, errors = self.validate_config(profile[\"config\"])\n if not is_valid:\n from ..errors import ProfileError\n\n raise ProfileError(\n f\"Profile configuration validation failed: {'; '.join(errors)}\",\n profile_name=name,\n error_code=\"PROFILE_CONFIG_INVALID\",\n )\n\n return self.profile_manager.save_user_profile(name, profile)\n\n def delete_user_profile(self, name: str) -> bool:\n \"\"\"Delete a user profile.\"\"\"\n return self.profile_manager.delete_user_profile(name)\n\n @property\n def default_profiles(self) -> Dict[str, Any]:\n \"\"\"Get default profiles.\"\"\"\n return self.profile_manager.default_profiles\n\n @property\n def user_profiles(self) -> Dict[str, Any]:\n \"\"\"Get user profiles.\"\"\"\n return self.profile_manager.user_profiles\n\n def validate_config(self, config: Dict[str, Any]) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate a configuration using the new validation framework.\n\n This method uses the comprehensive validation system to check\n configuration values, types, ranges, and dependencies.\n\n Args:\n config: Configuration dictionary to validate\n\n Returns:\n Tuple of (is_valid, list_of_error_messages)\n\n Raises:\n ConfigurationError: If validation system fails\n \"\"\"\n try:\n # Use new validation system\n result = self.validation_registry.validate_config(config)\n\n # Convert validation errors to string messages for backward compatibility\n error_messages = result.get_error_messages()\n\n # Add warnings if any\n if result.warnings:\n for warning in result.warnings:\n logger.warning(f\"Configuration warning: {warning}\")\n\n return result.is_valid(), error_messages\n\n except Exception as e:\n logger.error(f\"Error during configuration validation: {e}\")\n raise ConfigurationError(\n f\"Validation system error: {e}\", error_code=\"VALIDATION_SYSTEM_ERROR\"\n ) from e\n\n def validate_argument_combination(\n self, config: Dict[str, Any]\n ) -> Tuple[bool, List[str]]:\n \"\"\"\n Validate that argument combinations are compatible using the new compatibility validator.\n\n Args:\n config: Configuration dictionary to check for compatibility\n\n Returns:\n Tuple of (is_valid, list_of_warnings_or_errors)\n \"\"\"\n try:\n issues = self.compatibility_validator.validate_compatibility(config)\n\n warnings = []\n errors = []\n\n for issue in issues:\n message = issue[\"message\"]\n if issue[\"severity\"] == \"error\":\n errors.append(message)\n else:\n warnings.append(message)\n\n # Log warnings\n for warning in warnings:\n logger.warning(f\"Configuration compatibility warning: {warning}\")\n\n # Return all issues as warnings for backward compatibility\n # (errors are treated as warnings in the legacy interface)\n all_issues = errors + warnings\n\n return len(errors) == 0, all_issues\n\n except Exception as e:\n logger.error(f\"Error during compatibility validation: {e}\")\n return False, [f\"Compatibility validation error: {e}\"]\n\n def build_cli_args(self, config: Dict[str, Any]) -> List[str]:\n \"\"\"\n Build command-line arguments from a configuration dictionary.\n\n Only includes arguments that are explicitly set in the config.\n Handles special cases like LoRA modules.\n \"\"\"\n args = []\n\n # Special handling for model (positional argument)\n # Check if this is a GGUF/Ollama configuration\n if (\n isinstance(config.get(\"model\"), dict)\n and \"quantization\" in config[\"model\"]\n and config[\"model\"][\"quantization\"] == \"gguf\"\n ):\n # Extract GGUF model config\n gguf_config = config[\"model\"]\n model_path = gguf_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", model_path])\n\n # Set quantization to gguf\n config[\"quantization\"] = \"gguf\"\n\n # Add served-model-name if provided (for Ollama models)\n if \"served_model_name\" in gguf_config:\n config[\"served_model_name\"] = gguf_config[\"served_model_name\"]\n logger.info(\n f\"Configuring GGUF model: {model_path} as {gguf_config['served_model_name']}\"\n )\n else:\n logger.info(f\"Configuring GGUF model: {model_path}\")\n\n # Check if this is a LoRA configuration\n elif (\n isinstance(config.get(\"model\"), dict) and \"lora_modules\" in config[\"model\"]\n ):\n # Extract base model and LoRA config\n lora_config = config[\"model\"]\n base_model = lora_config.get(\"model\", \"unknown\")\n args.extend([\"serve\", base_model])\n\n # Enable LoRA support when modules are present\n args.append(\"--enable-lora\")\n\n # Track maximum rank for all LoRA modules\n max_rank = 16 # Default minimum\n\n # Add LoRA modules\n for lora in lora_config.get(\"lora_modules\", []):\n lora_path = lora.get(\"path\", \"\")\n if lora_path:\n # vLLM expects --lora-modules with name=path format\n lora_name = lora.get(\"name\", \"adapter\")\n args.extend([\"--lora-modules\", f\"{lora_name}={lora_path}\"])\n\n # Track maximum rank\n lora_rank = lora.get(\"rank\", 16)\n max_rank = max(max_rank, lora_rank)\n\n # Add max-lora-rank parameter\n args.extend([\"--max-lora-rank\", str(max_rank)])\n\n elif \"model\" in config:\n args.extend([\"serve\", config[\"model\"]])\n\n # Handle lora_modules if present as a string (from CLI)\n if \"lora_modules\" in config and config[\"lora_modules\"]:\n # Enable LoRA support\n if \"--enable-lora\" not in args:\n args.append(\"--enable-lora\")\n\n # Parse and add LoRA modules\n lora_modules_str = config[\"lora_modules\"]\n if isinstance(lora_modules_str, str):\n # Split by space and add each module\n for module in lora_modules_str.split():\n args.extend([\"--lora-modules\", module])\n\n # Add max-lora-rank if not already added\n # Use a safe default of 64 which should cover most LoRA adapters\n if \"--max-lora-rank\" not in args:\n # Check if max_lora_rank is explicitly set in config\n if \"max_lora_rank\" not in config:\n args.extend([\"--max-lora-rank\", \"64\"])\n\n for arg_name, value in config.items():\n # Skip special keys and None values\n if (\n arg_name in [\"model\", \"name\", \"description\", \"icon\", \"lora_modules\"]\n or value is None\n ):\n continue\n\n arg_info = self.schema_manager.get_argument_info(arg_name)\n if not arg_info:\n logger.warning(f\"Unknown argument in config: {arg_name}\")\n continue\n\n cli_flag = arg_info.get(\"cli_flag\")\n if not cli_flag:\n continue\n\n arg_type = arg_info.get(\"type\")\n\n if arg_type == \"boolean\":\n if value: # Only add flag if True\n args.append(cli_flag)\n elif arg_type in [\"integer\", \"float\", \"string\", \"choice\"]:\n args.extend([cli_flag, str(value)])\n else:\n logger.warning(f\"Unknown argument type for {arg_name}: {arg_type}\")\n\n return args\n\n def export_profile(self, profile_name: str, filepath: Path) -> bool:\n \"\"\"Export a profile to a JSON file.\"\"\"\n return self.profile_manager.export_profile(profile_name, filepath)\n\n def import_profile(self, filepath: Path, new_name: Optional[str] = None) -> bool:\n \"\"\"Import a profile from a JSON file with comprehensive validation.\"\"\"\n return self.profile_manager.import_profile(\n filepath, new_name, self.validate_config\n )\n\n def get_last_config(self) -> Optional[Dict[str, Any]]:\n \"\"\"Get the last used server configuration.\"\"\"\n return self.config.get(\"last_config\")\n\n def save_last_config(self, config: Dict[str, Any]) -> None:\n \"\"\"Save the last used server configuration.\"\"\"\n self.config[\"last_config\"] = config\n self._save_config()\n\n def get_recent_models(self, limit: int = 5) -> List[str]:\n \"\"\"Get recently used models.\"\"\"\n return self.config.get(\"recent_models\", [])[:limit]\n\n def add_recent_model(self, model: str) -> None:\n \"\"\"Add a model to recent models list.\"\"\"\n recent = self.config.get(\"recent_models\", [])\n if model in recent:\n recent.remove(model)\n recent.insert(0, model)\n self.config[\"recent_models\"] = recent[:10] # Keep only last 10\n self._save_config()\n\n def clear_cache(self) -> None:\n \"\"\"Clear cached data.\"\"\"\n cache_file = self.config_dir / \"cache.json\"\n if cache_file.exists():\n cache_file.unlink()\n self.config.pop(\"last_config\", None)\n self.config.pop(\"recent_models\", None)\n self._save_config()\n logger.info(\"Cache cleared\")\n\n def get_server_defaults(self) -> Dict[str, Any]:\n \"\"\"Get default server settings.\"\"\"\n return self.config.get(\n \"server_defaults\",\n {\n \"default_port\": 8000,\n \"auto_restart\": False,\n \"log_level\": \"info\",\n \"cleanup_on_exit\": True, # Default to cleaning up servers on exit\n },\n )\n\n def save_server_defaults(self, defaults: Dict[str, Any]) -> None:\n \"\"\"Save default server settings.\"\"\"\n self.config[\"server_defaults\"] = defaults\n self._save_config()\n\n def get_ui_preferences(self) -> Dict[str, Any]:\n \"\"\"Get UI preferences including progress bar style and log display settings.\"\"\"\n return self.config.get(\n \"ui_preferences\",\n {\n \"progress_bar_style\": \"blocks\", # Default style\n \"show_gpu_in_monitor\": True,\n \"log_lines_startup\": 50, # Number of log lines to show during startup\n \"log_lines_monitor\": 50, # Number of log lines to show in server monitor\n \"startup_refresh_rate\": 4.0, # Hz for startup log refresh\n \"monitor_refresh_rate\": 1.0, # Hz for monitor log refresh\n },\n )\n\n def save_ui_preferences(self, preferences: Dict[str, Any]) -> None:\n \"\"\"Save UI preferences.\"\"\"\n self.config[\"ui_preferences\"] = preferences\n self._save_config()\n\n # Shortcut management methods\n def get_all_shortcuts(self) -> Dict[str, Dict[str, Any]]:\n \"\"\"Get all shortcuts.\"\"\"\n return self.shortcut_manager.get_all_shortcuts()\n\n def get_shortcut(self, name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get a specific shortcut by name.\"\"\"\n return self.shortcut_manager.get_shortcut(name)\n\n def save_shortcut(self, name: str, shortcut_data: Dict[str, Any]) -> bool:\n \"\"\"Save or update a shortcut.\"\"\"\n return self.shortcut_manager.save_shortcut(name, shortcut_data)\n\n def delete_shortcut(self, name: str) -> bool:\n \"\"\"Delete a shortcut.\"\"\"\n return self.shortcut_manager.delete_shortcut(name)\n\n def list_shortcuts(self) -> List[Dict[str, Any]]:\n \"\"\"List all shortcuts with summary information.\"\"\"\n return self.shortcut_manager.list_shortcuts()\n\n def get_recent_shortcuts(self, limit: int = 5) -> List[Dict[str, Any]]:\n \"\"\"Get recently used shortcuts.\"\"\"\n return self.shortcut_manager.get_recent_shortcuts(limit)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 15704}, "tests/test_ollama_support.py::137": {"resolved_imports": ["src/vllm_cli/models/discovery.py", "src/vllm_cli/models/manager.py", "src/vllm_cli/ui/model_manager.py"], "used_names": ["patch", "pytest", "select_model"], "enclosing_function": "test_select_ollama_model_format", "extracted_code": "# Source: src/vllm_cli/ui/model_manager.py\ndef select_model() -> Optional[Any]:\n \"\"\"\n Select a model from available models with provider categorization.\n Can return either a string (model name) or a dict (model with LoRA config).\n \"\"\"\n console.print(\"\\n[bold cyan]Model Selection[/bold cyan]\")\n\n try:\n # First, ask if user wants to use local or remote model\n model_source_choices = [\n \"Select from local models\",\n \"Serve model with LoRA adapters\",\n \"Use a model from HuggingFace Hub (auto-download)\",\n ]\n\n source_choice = unified_prompt(\n \"model_source\",\n \"How would you like to select a model?\",\n model_source_choices,\n allow_back=True,\n )\n\n if not source_choice or source_choice == \"BACK\":\n return None\n\n if source_choice == \"Use a model from HuggingFace Hub (auto-download)\":\n return enter_remote_model()\n\n if source_choice == \"Serve model with LoRA adapters\":\n return select_model_with_lora()\n\n # Continue with local model selection\n console.print(\"\\n[bold cyan]Fetching available models...[/bold cyan]\")\n models = list_available_models()\n\n if not models:\n console.print(\"[yellow]No local models found.[/yellow]\")\n console.print(\"\\nYou can either:\")\n console.print(\" 1. Download models using HuggingFace tools\")\n console.print(\" 2. Go back and select 'Use a model from HuggingFace Hub'\")\n input(\"\\nPress Enter to continue...\")\n return None\n\n # Group models by provider\n providers_dict = {}\n for model in models:\n # Special handling for Ollama models\n if model.get(\"type\") == \"ollama_model\":\n provider = \"ollama\"\n else:\n provider = model.get(\"publisher\", \"unknown\")\n if provider == \"unknown\" or not provider:\n # Try to extract provider from model name\n if \"/\" in model[\"name\"]:\n provider = model[\"name\"].split(\"/\")[0]\n else:\n provider = \"local\"\n\n if provider not in providers_dict:\n providers_dict[provider] = []\n providers_dict[provider].append(model)\n\n # Separate local provider from others\n local_provider = None\n other_providers = []\n\n for provider in providers_dict.keys():\n if provider == \"local\":\n local_provider = provider\n else:\n other_providers.append(provider)\n\n # Sort other providers alphabetically\n other_providers.sort()\n\n # Build provider choices with separation\n provider_choices = []\n\n # Add other providers first\n for provider in other_providers:\n count = len(providers_dict[provider])\n provider_choices.append(\n f\"{provider} ({count} model{'s' if count > 1 else ''})\"\n )\n\n # Add separator and local provider at the bottom if it exists\n if local_provider:\n # Add separator if there are other providers\n if other_providers:\n provider_choices.append(\"─\" * 30)\n count = len(providers_dict[local_provider])\n provider_choices.append(\n f\"{local_provider} ({count} model{'s' if count > 1 else ''})\"\n )\n\n # Count total providers (excluding separator)\n total_providers = len(providers_dict)\n\n selected_provider = unified_prompt(\n \"provider\",\n f\"Select Provider ({total_providers} available)\",\n provider_choices,\n allow_back=True,\n )\n\n if not selected_provider or selected_provider == \"BACK\":\n return None\n\n # Check if separator was selected (shouldn't happen, but handle it)\n if selected_provider.startswith(\"─\"):\n # Retry selection\n return select_model()\n\n # Extract provider name\n provider_name = selected_provider.split(\" (\")[0]\n\n # Now show models for selected provider\n provider_models = providers_dict[provider_name]\n\n # Create model choices for selected provider\n model_choices = []\n for model in provider_models:\n size_str = format_size(model.get(\"size\", 0))\n # Show only the model name without provider if it's already in the name\n display_name = model[\"name\"]\n if display_name.startswith(f\"{provider_name}/\"):\n display_name = display_name[len(provider_name) + 1 :] # noqa: E203\n model_choices.append(f\"{display_name} ({size_str})\")\n\n # Show model selection for the provider\n selected = unified_prompt(\n \"model\",\n f\"Select {provider_name} Model ({len(provider_models)} available)\",\n model_choices,\n allow_back=True,\n )\n\n if not selected or selected == \"BACK\":\n # Go back to provider selection\n return select_model()\n\n # Extract model name and reconstruct full name if needed\n model_display_name = selected.split(\" (\")[0]\n\n # Find the full model and return appropriate identifier\n for model in provider_models:\n check_name = model[\"name\"]\n if check_name.startswith(f\"{provider_name}/\"):\n check_name = check_name[len(provider_name) + 1 :] # noqa: E203\n if check_name == model_display_name or model[\"name\"] == model_display_name:\n # Special handling for Ollama models\n if model.get(\"type\") == \"ollama_model\":\n console.print(\"\\n[yellow]⚠ Warning: Ollama GGUF Model[/yellow]\")\n console.print(\n \"GGUF support in vLLM is experimental and varies by model architecture.\"\n )\n console.print(\n \"\\n[cyan]Important:[/cyan] Not all GGUF models are supported.\"\n )\n console.print(\"\\nFor compatibility information, see:\")\n console.print(\n \" • vLLM-CLI Guide: [cyan]https://github.com/Chen-zexi/vllm-cli/blob/main/docs/ollama-integration.md[/cyan]\"\n )\n console.print(\n \" • vLLM Docs: [cyan]https://docs.vllm.ai/en/latest/models/supported_models.html[/cyan]\"\n )\n\n console.print(\n \"\\n[cyan]Continue with this model? (Y/n):[/cyan] \", end=\"\"\n )\n confirm = input().strip().lower()\n if confirm not in [\"\", \"y\", \"yes\"]:\n return select_model() # Go back to selection\n\n # Return the GGUF file path with all metadata including name\n return {\n \"model\": model[\"path\"],\n \"path\": model[\"path\"], # Include path\n \"served_model_name\": model[\n \"name\"\n ], # Use correct field name for vLLM\n \"type\": \"ollama_model\", # Preserve type\n \"quantization\": \"gguf\",\n \"experimental\": True,\n }\n\n # For custom models, always use path regardless of publisher\n # Custom models are identified by their type\n if model.get(\"type\") == \"custom_model\" and model.get(\"path\"):\n return model[\"path\"]\n\n # For non-HF pattern models (local), also use path\n model_name = model[\"name\"]\n if model.get(\"path\") and (\n \"/\" not in model_name # No HF org/model pattern\n or model_name.startswith(\"/\") # Absolute path\n or model.get(\"publisher\")\n in [\"local\", \"unknown\", None] # Local publisher\n ):\n return model[\"path\"]\n return model[\"name\"]\n\n # Fallback\n return model_display_name\n\n except Exception as e:\n logger.error(f\"Error selecting model: {e}\")\n console.print(f\"[red]Error selecting model: {e}[/red]\")\n return None", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 8433}, "tests/test_cli_parser.py::112": {"resolved_imports": ["src/vllm_cli/cli/parser.py"], "used_names": ["create_parser"], "enclosing_function": "test_stop_command_with_port", "extracted_code": "# Source: src/vllm_cli/cli/parser.py\ndef create_parser() -> argparse.ArgumentParser:\n \"\"\"\n Create the main argument parser for vLLM CLI.\n\n Sets up the main parser with all subcommands and their arguments.\n\n Returns:\n Configured ArgumentParser instance\n \"\"\"\n parser = argparse.ArgumentParser(\n prog=\"vllm-cli\",\n description=\"vLLM CLI - Convenient LLM serving tool\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"Examples:\n vllm-cli # Interactive mode\n vllm-cli serve MODEL --profile standard # Serve with profile\n vllm-cli serve MODEL --quantization awq # Serve with AWQ quantization\n vllm-cli serve MODEL --extra-args \"--seed 42\" # With custom vLLM args\n vllm-cli info # System information\n vllm-cli models # List available models\n vllm-cli status # Show active servers\"\"\",\n )\n\n # Global options\n from .. import __version__\n\n parser.add_argument(\n \"--version\", action=\"version\", version=f\"vLLM CLI {__version__}\"\n )\n\n # Create subparsers for commands\n subparsers = parser.add_subparsers(\n dest=\"command\",\n help=\"Available commands\",\n metavar=\"{serve,proxy,info,models,shortcuts,status,stop,dirs}\",\n )\n\n # Add individual command parsers\n _add_serve_parser(subparsers)\n _add_proxy_parser(subparsers)\n _add_info_parser(subparsers)\n _add_models_parser(subparsers)\n _add_shortcuts_parser(subparsers)\n _add_status_parser(subparsers)\n _add_stop_parser(subparsers)\n _add_dirs_parser(subparsers)\n\n return parser", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1705}}}