Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 33 additions & 6 deletions backend/src/backend/config_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,27 @@
from pathlib import Path
from typing import Optional

from omegaconf import DictConfig, OmegaConf
from omegaconf import DictConfig, ListConfig, OmegaConf

logger = logging.getLogger(__name__)


class ConfigSaveError(RuntimeError):
"""A runtime settings change could not be written to config.yml."""


def _save_failure(what: str, config_path: Path, error: Exception) -> ConfigSaveError:
if isinstance(error, OSError) and error.errno == 30: # EROFS
reason = (
f"{config_path} is read-only. In Kubernetes it is usually mounted from a "
"ConfigMap; edit that ConfigMap (or give the config directory writable "
"storage) instead of using the Settings page."
)
else:
reason = f"{type(error).__name__}: {error}"
return ConfigSaveError(f"Could not save {what}: {reason}")


# Global config cache
_config_cache: Optional[DictConfig] = None
_config_warnings: tuple[str, ...] = ()
Expand Down Expand Up @@ -250,8 +267,9 @@ def save_config_section(section_path: str, values: dict) -> bool:
return True

except Exception as e:
logger.error(f"Error saving config section '{section_path}': {e}")
return False
error = _save_failure(f"config section '{section_path}'", config_path, e)
logger.error(str(error))
raise error from e


def _load_raw_config() -> DictConfig:
Expand All @@ -277,7 +295,15 @@ def get_raw_models() -> list:
note it excludes default-only models that live solely in defaults.yml.
"""
raw = _load_raw_config()
models = raw.get("models", []) or []
models = raw.get("models")
# A config.yml without a ``models`` key yields None, not a ListConfig, and
# OmegaConf.to_container() rejects plain Python values.
if models is None:
return []
if not isinstance(models, ListConfig):
raise ValueError(
f"config.yml 'models' must be a list, got {type(models).__name__}"
)
return OmegaConf.to_container(models, resolve=False)


Expand Down Expand Up @@ -306,5 +332,6 @@ def save_models_list(models: list) -> bool:
return True

except Exception as e:
logger.error(f"Error saving models list: {e}")
return False
error = _save_failure("the models list", config_path, e)
logger.error(str(error))
raise error from e
28 changes: 28 additions & 0 deletions backend/src/backend/middleware/app_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
from starlette.responses import Response

from backend.app_config import get_app_config
from backend.config_loader import ConfigSaveError
from backend.model_registry import MissingModelCredentialsError

logger = logging.getLogger(__name__)
request_logger = logging.getLogger("api.requests")
Expand Down Expand Up @@ -225,6 +227,32 @@ async def connection_exception_handler(request: Request, exc: ConnectionError):
},
)

@app.exception_handler(ConfigSaveError)
async def config_save_exception_handler(request: Request, exc: ConfigSaveError):
"""A settings write failed; tell the caller why instead of a bare 500."""
return JSONResponse(
status_code=500,
content={
"detail": str(exc),
"error_type": "config_save_failure",
"error_category": "configuration",
},
)

@app.exception_handler(MissingModelCredentialsError)
async def missing_credentials_exception_handler(
request: Request, exc: MissingModelCredentialsError
):
"""An LLM call was attempted against a hosted model with no API key."""
return JSONResponse(
status_code=503,
content={
"detail": str(exc),
"error_type": "missing_model_credentials",
"error_category": "configuration",
},
)

@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
"""Handle HTTP exceptions with structured error response."""
Expand Down
41 changes: 40 additions & 1 deletion backend/src/backend/model_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,37 @@

logger = logging.getLogger(__name__)


class MissingModelCredentialsError(RuntimeError):
"""A hosted model was selected but its API key is not configured."""


def require_api_key(
api_key: Optional[str],
url: str,
model_name: str,
*,
operation: Optional[str] = None,
) -> str:
"""Return ``api_key``, or raise when a hosted HTTPS endpoint has none.

Local servers (llama.cpp, Ollama, Tailnet ASR) declare a placeholder such as
``no-key``. A key that resolved to empty for an HTTPS URL means a hosted
provider whose environment variable is unset; calling it would only fail
later as an opaque 401 inside a background job.
"""
if api_key:
return api_key
if url.startswith("https://"):
used_by = f" (used by LLM operation '{operation}')" if operation else ""
raise MissingModelCredentialsError(
f"Model '{model_name}'{used_by} calls {url} but its api_key is empty. "
"Set the environment variable its api_key references in config, "
"or select a different model in Settings > AI Model Settings."
)
return ""


# Operations whose normal routing role is not the primary LLM. Keeping this policy
# beside the resolver makes the effective route inspectable without teaching every
# caller or diagnostic which default it should use.
Expand Down Expand Up @@ -254,6 +285,12 @@ def resolved_url(self) -> str:
return _with_scheme(discovered)
return _with_scheme(self.discovery_default or "")

def require_api_key(self, operation: Optional[str] = None) -> str:
"""Return the API key, or raise when a hosted endpoint has none."""
return require_api_key(
self.api_key, self.resolved_url(), self.name, operation=operation
)

@model_validator(mode="after")
def validate_model(self) -> ModelDef:
"""Cross-field validation."""
Expand Down Expand Up @@ -319,6 +356,7 @@ class ResolvedLLMOperation(BaseModel):
max_tokens: Optional[int] = None
response_format: Optional[Dict[str, Any]] = None # {"type": "json_object"} or None
reasoning_effort: Optional[str] = None # OpenAI reasoning models OR thinking models
operation: Optional[str] = None # llm_operations name, for actionable errors

@property
def reasoning_allowed(self) -> bool:
Expand Down Expand Up @@ -433,7 +471,7 @@ def get_client(self, is_async: bool = False):
Uses create_openai_client which handles Langfuse tracing.
"""
return create_openai_client(
api_key=self.model_def.api_key or "",
api_key=self.model_def.require_api_key(self.operation),
base_url=self.model_def.resolved_url(),
is_async=is_async,
)
Expand Down Expand Up @@ -609,6 +647,7 @@ def get_llm_operation(
max_tokens=int(max_tokens) if max_tokens is not None else None,
response_format=response_format,
reasoning_effort=reasoning_effort,
operation=name,
)

def explain_llm_operation(self, name: str) -> Dict[str, Optional[str]]:
Expand Down
12 changes: 10 additions & 2 deletions backend/src/backend/services/memory/agent/pi_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,12 @@
from urllib.parse import unquote, urlsplit

import backend.services.privacy as privacy
from backend.model_registry import AppModels, ResolvedLLMOperation, get_models_registry
from backend.model_registry import (
AppModels,
ResolvedLLMOperation,
get_models_registry,
require_api_key,
)
from backend.services.inference_artifacts import canonical_hash, persist_inference_run

from ..session_write import WriteSourcePermissions
Expand Down Expand Up @@ -452,7 +457,10 @@ def _resolve_pi_config(
provider=_provider_slug(str(model_def.model_provider)),
model=resolved.model_name,
base_url=base_url,
api_key=resolved.api_key or "no-key",
api_key=require_api_key(
resolved.api_key, base_url, model_def.name, operation=operation
)
or "no-key",
thinking=_thinking_level(settings.get("thinking"), resolved),
max_tokens=max_tokens,
context_window=context_window,
Expand Down
79 changes: 79 additions & 0 deletions backend/tests/test_llm_config_errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
"""Misconfigured LLMs and unwritable settings must fail loudly, not silently."""

import os
from pathlib import Path

import pytest

from backend import config_loader
from backend.config_loader import ConfigSaveError, get_raw_models, save_config_section
from backend.model_registry import (
AppModels,
LLMOperationConfig,
MissingModelCredentialsError,
ModelDef,
)


def _model(name: str, url: str, api_key) -> ModelDef:
return ModelDef(
name=name,
model_type="llm",
model_provider="openrouter",
api_family="openai",
model_name=name,
model_url=url,
api_key=api_key,
)


def test_hosted_model_without_key_raises_when_client_is_built():
hosted = _model("openrouter-qwen", "https://openrouter.ai/api/v1", "")
registry = AppModels(
defaults={"llm": hosted.name},
models={hosted.name: hosted},
llm_operations={"memory_write": LLMOperationConfig(model=hosted.name)},
)

op = registry.get_llm_operation("memory_write")

with pytest.raises(MissingModelCredentialsError) as error:
op.get_client(is_async=True)
assert "openrouter-qwen" in str(error.value)
assert "memory_write" in str(error.value)


def test_local_model_without_key_is_allowed():
local = _model("local-llm", "http://llama-cpp-llm:8080/v1", "")
assert local.require_api_key() == ""


def test_hosted_model_with_key_returns_key():
hosted = _model("openai", "https://api.openai.com/v1", "sk-test")
assert hosted.require_api_key() == "sk-test"


@pytest.fixture
def config_dir(tmp_path: Path, monkeypatch):
monkeypatch.setenv("CONFIG_DIR", str(tmp_path))
yield tmp_path
config_loader._runtime_overrides.clear()


def test_raw_models_is_empty_when_config_has_no_models_key(config_dir: Path):
(config_dir / "config.yml").write_text("llm_operations: {}\n")
assert get_raw_models() == []


def test_save_to_read_only_config_raises_actionable_error(config_dir: Path):
config_file = config_dir / "config.yml"
config_file.write_text("llm_operations: {}\n")
os.chmod(config_dir, 0o500)
os.chmod(config_file, 0o400)
try:
with pytest.raises(ConfigSaveError) as error:
save_config_section("llm_operations", {"memory_write": {"model": "x"}})
finally:
os.chmod(config_dir, 0o700)
os.chmod(config_file, 0o600)
assert "llm_operations" in str(error.value)
Loading