Skip to content
Open
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
55 changes: 52 additions & 3 deletions backend/src/backend/controllers/system_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from datetime import UTC, datetime
from io import StringIO
from pathlib import Path
from typing import Optional
from typing import Any, Optional
from urllib.parse import urlparse

import httpx
Expand Down Expand Up @@ -48,6 +48,7 @@
_find_config_path,
get_models_registry,
load_models_config,
output_token_limit_findings,
)
from backend.model_routes import effective_model_routes, effective_operation_routes
from backend.models.user import User
Expand Down Expand Up @@ -176,6 +177,42 @@ def _is_self_hosted_model(model) -> bool:
return host.endswith(".ts.net") or "." not in host


def _output_limit_issues(registry: Any) -> list[dict[str, Any]]:
"""Report each max_tokens setting its model cannot honour.

These are errors: the operation refuses to run (see ``OutputLimitExceeded``)
until a larger-output model is chosen or the setting is lowered.
"""

timeline_pi = (load_config().get("timeline", {}) or {}).get("pi", {}) or {}
extra = [
(
"timeline.pi.max_tokens",
str(timeline_pi.get("operation") or "timeline_segmentation"),
timeline_pi.get("max_tokens"),
)
]
return [
{
"component": "Model Limits",
"severity": "error",
"message": (
f"'{finding['operation']}' needs a model with at least "
f"{finding['requested']} output tokens, but it uses "
f"{finding['model']} ({finding['model_name']}), which accepts at most "
f"{finding['limit']}. It will not run until this is fixed."
),
"resolution": (
f"Settings > AI Model Settings: route '{finding['operation']}' to a "
f"model that supports at least {finding['requested']} output "
f"tokens. Or lower {finding['setting']} to {finding['limit']} or "
f"less, if shorter results are acceptable."
),
}
for finding in output_token_limit_findings(registry, extra)
]


async def get_config_diagnostics():
"""
Get comprehensive configuration diagnostics.
Expand Down Expand Up @@ -360,6 +397,13 @@ async def get_config_diagnostics():
}
)

# Listed under issues so the health poller records a System Event.
limit_issues = _output_limit_issues(registry)
if limit_issues:
diagnostics["issues"].extend(limit_issues)
if diagnostics["overall_status"] == "healthy":
diagnostics["overall_status"] = "partial"

else:
diagnostics["overall_status"] = "unhealthy"
diagnostics["issues"].append(
Expand Down Expand Up @@ -2679,7 +2723,9 @@ async def create_plugin(
if events
else '"conversation.complete"'
)
boilerplate = inspect.cleandoc(f'''
boilerplate = (
inspect.cleandoc(
f'''
"""
{class_name} implementation.

Expand Down Expand Up @@ -2716,7 +2762,10 @@ async def cleanup(self):
async def on_conversation_complete(self, context: PluginContext) -> Optional[PluginResult]:
logger.info(f"Processing conversation for user: {{context.user_id}}")
return PluginResult(success=True, message="OK")
''') + "\n"
'''
)
+ "\n"
)
(plugin_dir / "plugin.py").write_text(boilerplate, encoding="utf-8")
created_files.append("plugin.py")

Expand Down
174 changes: 148 additions & 26 deletions backend/src/backend/model_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,17 @@ def reasoning_allowed(self) -> bool:
embedding_dimensions: Optional[int] = Field(
default=None, ge=1, description="Embedding vector dimensions"
)
max_output_tokens: Optional[int] = Field(
default=None,
ge=1,
description=(
"Largest completion the provider accepts for this model. A request for "
"more is rejected outright (OpenAI returns HTTP 400), so every requested "
"max_tokens is fitted to this value. Unset means unknown: requests pass "
"through unchanged, which is the right default for local servers whose "
"only limit is their context window."
),
)
operations: Dict[str, Any] = Field(
default_factory=dict, description="API operation definitions"
)
Expand Down Expand Up @@ -287,6 +298,94 @@ def validate_model(self) -> ModelDef:
return self


class OutputLimitExceeded(ValueError):
"""A configured max_tokens is larger than the routed model can produce.

Raised before any request is sent. Silently shrinking the allowance would run the
operation with less room than it was tuned for (a long timeline day is cut off
before its last episodes), so the operator is told to choose a bigger model.
"""

def __init__(self, *, setting: str, model: str, requested: int, limit: int):
self.setting = setting
self.model = model
self.requested = requested
self.limit = limit
super().__init__(
f"{setting} needs {requested} output tokens, but model '{model}' accepts "
f"at most {limit}. Choose a model that supports at least {requested} "
f"output tokens for this operation (Settings > AI Model Settings), or "
f"lower {setting}."
)


def check_output_tokens(model_def: Any, requested: int, *, setting: str) -> int:
"""Return ``requested`` if the model can produce it; raise otherwise."""

# Test fakes and extra-field model entries share this path with ModelDef, the
# same way callers already read ``context_window``.
return check_output_limit(
getattr(model_def, "max_output_tokens", None),
requested,
setting=setting,
model=str(model_def.name),
)


def check_output_limit(
limit: Optional[int], requested: int, *, setting: str, model: str
) -> int:
"""Core of :func:`check_output_tokens` for callers holding only the limit.

An undeclared limit means unknown, so the request passes through unchanged.
"""

if limit is not None and requested > limit:
raise OutputLimitExceeded(
setting=setting, model=model, requested=int(requested), limit=int(limit)
)
return requested


def output_token_limit_findings(
registry: "AppModels",
extra_settings: Optional[List[tuple[str, str, Any]]] = None,
) -> List[Dict[str, Any]]:
"""List every configured ``max_tokens`` larger than its model accepts.

Checks each ``llm_operations`` entry against the model it routes to, plus
``extra_settings``: ``(setting_path, operation_name, requested)`` triples for
feature settings that override an operation's limit (``timeline.pi.max_tokens``).
"""

candidates: List[tuple[str, str, Any]] = []
for name, op_config in registry.llm_operations.items():
if op_config.max_tokens is not None:
candidates.append(
(f"llm_operations.{name}.max_tokens", name, op_config.max_tokens)
)
candidates.extend(extra_settings or [])

findings: List[Dict[str, Any]] = []
for setting, operation, requested in candidates:
if requested in (None, "") or isinstance(requested, bool):
continue
model_def = registry.resolve_operation_model(operation)
limit = model_def.max_output_tokens
if limit is not None and int(requested) > limit:
findings.append(
{
"setting": setting,
"operation": operation,
"model": model_def.name,
"model_name": model_def.model_name,
"requested": int(requested),
"limit": limit,
}
)
return findings


class LLMOperationConfig(BaseModel):
"""Per-operation LLM config as written in YAML.

Expand Down Expand Up @@ -526,36 +625,20 @@ def list_model_types(self) -> List[str]:
"""
return sorted(set(m.model_type for m in self.models.values()))

def get_llm_operation(
self,
name: str,
*,
model_override: Optional[str] = None,
) -> ResolvedLLMOperation:
"""Resolve a named LLM operation to a self-contained config.

Resolution:
1. Look up llm_operations[name] (empty LLMOperationConfig if missing)
2. Resolve model_def: model_override → get_by_name, else op.model →
get_by_name, else the operation's centrally defined default role
3. Merge parameters: operation > model_def.model_params > safe fallback
4. Return ResolvedLLMOperation ready for use

Args:
name: Operation name (e.g. "memory_extraction", "chat")
model_override: pin a specific model by name, overriding both the
operation's model and the defaults (used for fallback retries).
def resolve_operation_model(
self, name: str, *, model_override: Optional[str] = None
) -> ModelDef:
"""Return the model an operation routes to, without validating its settings.

Returns:
ResolvedLLMOperation with model_def, temperature, max_tokens, response_format
Diagnostics and route explanations use this so a misconfigured operation can
still be reported; :meth:`get_llm_operation` adds the settings checks.

Raises:
RuntimeError: If no model can be resolved for the operation
"""
op_config = self.llm_operations.get(name, LLMOperationConfig())
default_role = self.llm_operation_role(name)

# Resolve model definition
if model_override:
model_def = self.get_by_name(model_override)
if not model_def:
Expand All @@ -578,6 +661,37 @@ def get_llm_operation(
raise RuntimeError(
f"No model specified for operation '{name}' and no default LLM defined"
)
return model_def

def get_llm_operation(
self,
name: str,
*,
model_override: Optional[str] = None,
) -> ResolvedLLMOperation:
"""Resolve a named LLM operation to a self-contained config.

Resolution:
1. Look up llm_operations[name] (empty LLMOperationConfig if missing)
2. Resolve model_def: model_override → get_by_name, else op.model →
get_by_name, else the operation's centrally defined default role
3. Merge parameters: operation > model_def.model_params > safe fallback
4. Return ResolvedLLMOperation ready for use

Args:
name: Operation name (e.g. "memory_extraction", "chat")
model_override: pin a specific model by name, overriding both the
operation's model and the defaults (used for fallback retries).

Returns:
ResolvedLLMOperation with model_def, temperature, max_tokens, response_format

Raises:
RuntimeError: If no model can be resolved for the operation
OutputLimitExceeded: If max_tokens is larger than the model can produce
"""
op_config = self.llm_operations.get(name, LLMOperationConfig())
model_def = self.resolve_operation_model(name, model_override=model_override)

# Merge parameters: operation config > model_params > safe fallback
model_params = model_def.model_params or {}
Expand All @@ -603,6 +717,14 @@ def get_llm_operation(
if op_config.response_format == "json":
response_format = {"type": "json_object"}

if max_tokens is not None:
source = (
f"llm_operations.{name}.max_tokens"
if op_config.max_tokens is not None
else f"models.{model_def.name}.model_params.max_tokens"
)
max_tokens = check_output_tokens(model_def, int(max_tokens), setting=source)

return ResolvedLLMOperation(
model_def=model_def,
temperature=float(temperature),
Expand All @@ -620,11 +742,11 @@ def explain_llm_operation(self, name: str) -> Dict[str, Optional[str]]:
else:
role = self.llm_operation_role(name)
source = f"defaults.{role}"
resolved = self.get_llm_operation(name)
model_def = self.resolve_operation_model(name)
return {
"model": resolved.model_def.name,
"model_name": resolved.model_name,
"provider": resolved.model_def.model_provider,
"model": model_def.name,
"model_name": model_def.model_name,
"provider": model_def.model_provider,
"role": role,
"source": source,
}
Expand Down
8 changes: 8 additions & 0 deletions backend/src/backend/routers/modules/timeline_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import backend.services.privacy as privacy
import backend.services.timeline.memory_sources as memory_sources
from backend.auth import current_active_user
from backend.model_registry import OutputLimitExceeded
from backend.models.audio_chunk import AudioChunkDocument
from backend.models.conversation import Conversation
from backend.models.notification import NotificationIntent
Expand Down Expand Up @@ -73,6 +74,9 @@
EvidenceRelationPreview,
infer_evidence_relations,
)
from backend.services.timeline.executor import (
check_output_limits as check_timeline_output_limits,
)
from backend.services.timeline.explicit_reconciliation import (
reconciliation_request_payload,
request_explicit_reconciliation,
Expand Down Expand Up @@ -551,6 +555,10 @@ async def reconcile_timeline_day(
user: User = Depends(current_active_user),
):
timezone = _validate_timezone(body.timezone)
try:
check_timeline_output_limits()
except OutputLimitExceeded as error:
raise HTTPException(status_code=409, detail=str(error)) from error
try:
request, created = await request_explicit_reconciliation(
user=user,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from typing import Any

from backend.config_loader import load_config
from backend.model_registry import check_output_limit
from backend.services.inference_artifacts import (
canonical_hash,
load_inference_runs,
Expand Down Expand Up @@ -108,8 +109,11 @@ def _optimizer_runtime_config(config: Any) -> Any:
"""Give the meta-optimizer room to reason and still emit its tool call."""

values = dict(vars(config))
values["max_tokens"] = max(
_OPTIMIZER_MIN_MAX_TOKENS, int(values.get("max_tokens") or 0)
values["max_tokens"] = check_output_limit(
values.get("max_output_tokens"),
max(_OPTIMIZER_MIN_MAX_TOKENS, int(values.get("max_tokens") or 0)),
setting="operating_memory optimizer minimum max_tokens",
model=str(values.get("model_entry") or values.get("model") or ""),
)
return type(config)(**values)

Expand Down
Loading
Loading