diff --git a/backend/src/backend/controllers/system_controller.py b/backend/src/backend/controllers/system_controller.py index 8c62da77..4325890f 100644 --- a/backend/src/backend/controllers/system_controller.py +++ b/backend/src/backend/controllers/system_controller.py @@ -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 @@ -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 @@ -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. @@ -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( @@ -2679,7 +2723,9 @@ async def create_plugin( if events else '"conversation.complete"' ) - boilerplate = inspect.cleandoc(f''' + boilerplate = ( + inspect.cleandoc( + f''' """ {class_name} implementation. @@ -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") diff --git a/backend/src/backend/model_registry.py b/backend/src/backend/model_registry.py index 9b8ff584..f9e3b5a9 100644 --- a/backend/src/backend/model_registry.py +++ b/backend/src/backend/model_registry.py @@ -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" ) @@ -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. @@ -526,28 +625,13 @@ 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 @@ -555,7 +639,6 @@ def get_llm_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: @@ -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 {} @@ -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), @@ -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, } diff --git a/backend/src/backend/routers/modules/timeline_routes.py b/backend/src/backend/routers/modules/timeline_routes.py index 6f8dcf16..dc83c48b 100644 --- a/backend/src/backend/routers/modules/timeline_routes.py +++ b/backend/src/backend/routers/modules/timeline_routes.py @@ -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 @@ -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, @@ -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, diff --git a/backend/src/backend/services/memory/agent/operating_memory_optimizer.py b/backend/src/backend/services/memory/agent/operating_memory_optimizer.py index 673f74b4..739eb3a4 100644 --- a/backend/src/backend/services/memory/agent/operating_memory_optimizer.py +++ b/backend/src/backend/services/memory/agent/operating_memory_optimizer.py @@ -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, @@ -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) diff --git a/backend/src/backend/services/memory/agent/pi_agent.py b/backend/src/backend/services/memory/agent/pi_agent.py index dc7f82a0..5a10f664 100644 --- a/backend/src/backend/services/memory/agent/pi_agent.py +++ b/backend/src/backend/services/memory/agent/pi_agent.py @@ -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, + check_output_tokens, + get_models_registry, +) from backend.services.inference_artifacts import canonical_hash, persist_inference_run from ..session_write import WriteSourcePermissions @@ -202,6 +207,10 @@ class _PiRuntimeConfig: system_prompt_prefix: str = "" compat: Dict[str, Any] = field(default_factory=dict) reasoning_allowed: bool = False + # The model's declared completion cap, kept so a later per-feature override of + # max_tokens (timeline.pi.max_tokens) is checked against the same model. + max_output_tokens: Optional[int] = None + model_entry: str = "" def __post_init__(self) -> None: if not self.reasoning_allowed: @@ -437,6 +446,11 @@ def _resolve_pi_config( name="max_tokens", default=DEFAULT_MAX_TOKENS, ) + # resolved.max_tokens is already checked by the registry; the settings fallback + # and the built-in default are not. + max_tokens = check_output_tokens( + model_def, max_tokens, setting="memory.backends.pi.max_tokens" + ) if max_tokens > context_window - MIN_PROMPT_HEADROOM_TOKENS: raise PiExecutorError( "memory.backends.pi.max_tokens must leave at least " @@ -463,6 +477,8 @@ def _resolve_pi_config( ), reasoning=bool(model_def.thinking), reasoning_allowed=resolved.reasoning_allowed, + max_output_tokens=getattr(model_def, "max_output_tokens", None), + model_entry=str(model_def.name), temperature=resolved.temperature, sampling={ key: model_params[key] diff --git a/backend/src/backend/services/timeline/executor.py b/backend/src/backend/services/timeline/executor.py index 4191b32d..26f98a8e 100644 --- a/backend/src/backend/services/timeline/executor.py +++ b/backend/src/backend/services/timeline/executor.py @@ -10,6 +10,11 @@ from omegaconf import OmegaConf from backend.config_loader import load_config +from backend.model_registry import ( + OutputLimitExceeded, + get_models_registry, + output_token_limit_findings, +) from backend.services.job_progress import report_job_progress from .codex_executor import CodexTimelineExecutor @@ -485,6 +490,39 @@ def settings_dict() -> dict[str, Any]: return converted if isinstance(converted, dict) else {} +def check_output_limits() -> None: + """Refuse a timeline run that the configured model cannot complete. + + Called before a day is queued so the person asking sees the model-choice + message at once, rather than a background failure after the run starts. The + executor repeats the check at run time; this is only the early warning. + """ + + settings = settings_dict() + if str(settings.get("executor") or "pi") != "pi": + return # Codex runs on its own subscription model and limits. + registry = get_models_registry() + if registry is None: + return # The run itself raises the precise registry error. + pi = settings.get("pi") or {} + operation = str(pi.get("operation") or "timeline_segmentation") + findings = [ + finding + for finding in output_token_limit_findings( + registry, [("timeline.pi.max_tokens", operation, pi.get("max_tokens"))] + ) + if finding["operation"] == operation + ] + if findings: + finding = findings[0] + raise OutputLimitExceeded( + setting=finding["setting"], + model=finding["model"], + requested=finding["requested"], + limit=finding["limit"], + ) + + def build_executor(): settings = settings_dict() executor = str(settings.get("executor") or "pi") diff --git a/backend/src/backend/services/timeline/pi_executor.py b/backend/src/backend/services/timeline/pi_executor.py index b56d9986..126b6516 100644 --- a/backend/src/backend/services/timeline/pi_executor.py +++ b/backend/src/backend/services/timeline/pi_executor.py @@ -19,6 +19,7 @@ import backend.services.timeline.pi_tasks as pi_tasks import backend.services.timeline.prompt as prompt +from backend.model_registry import check_output_limit from backend.services.inference_artifacts import ( invalidate_reusable_result, load_reusable_result, @@ -753,6 +754,16 @@ def _final_stage_config(self, reasoning_effort: str | None) -> Any: raise ValueError( "timeline.pi.max_tokens must be a positive integer" ) from exc + if max_tokens > 0: + # The shipped 32K allowance needs a large-output model. Stop with a + # model-choice message rather than send a request the provider + # rejects, or quietly shrink the room a dense day needs. + max_tokens = check_output_limit( + config.max_output_tokens, + max_tokens, + setting="timeline.pi.max_tokens", + model=config.model_entry, + ) if max_tokens <= 0 or max_tokens > config.context_window - 1024: raise ValueError( "timeline.pi.max_tokens must be positive and leave at least " diff --git a/backend/tests/test_model_output_limits.py b/backend/tests/test_model_output_limits.py new file mode 100644 index 00000000..ee9c1add --- /dev/null +++ b/backend/tests/test_model_output_limits.py @@ -0,0 +1,195 @@ +"""An operation whose max_tokens its model cannot produce refuses to run. + +Regression: timeline days failed with OpenAI HTTP 400 ("max_tokens is too large: +32000. This model supports at most 16384") because the shipped 32K timeline +allowance was sent unchanged to gpt-4o-mini. The fix stops before the request and +asks for a larger-output model; it does not shrink the allowance silently. +""" + +from pathlib import Path + +import pytest +import yaml + +import backend.services.timeline.executor as timeline_executor +import backend.services.timeline.pi_executor as pi_executor +from backend.model_registry import ( + AppModels, + LLMOperationConfig, + ModelDef, + OutputLimitExceeded, + output_token_limit_findings, +) +from backend.services.memory.agent.pi_agent import _PiRuntimeConfig + +DEFAULTS_YML = Path(__file__).resolve().parents[2] / "config" / "defaults.yml" + + +def _model(name: str, max_output_tokens=None) -> ModelDef: + return ModelDef( + name=name, + model_type="llm", + model_provider="openai", + model_name="gpt-4o-mini", + model_url="https://api.openai.com/v1", + max_output_tokens=max_output_tokens, + model_params={"max_tokens": 2000}, + ) + + +def _registry(model: ModelDef, **operations) -> AppModels: + return AppModels( + defaults={"llm": model.name}, + models={model.name: model}, + llm_operations={ + name: LLMOperationConfig(max_tokens=value) + for name, value in operations.items() + }, + ) + + +def test_oversized_operation_refuses_and_names_the_model(): + registry = _registry(_model("small", 16384), timeline_segmentation=32000) + + with pytest.raises(OutputLimitExceeded) as raised: + registry.get_llm_operation("timeline_segmentation") + + message = str(raised.value) + assert "llm_operations.timeline_segmentation.max_tokens needs 32000" in message + assert "model 'small' accepts at most 16384" in message + assert "Choose a model that supports at least 32000" in message + + +def test_operation_within_limit_is_unchanged(): + registry = _registry(_model("small", 16384), chat=8000) + + assert registry.get_llm_operation("chat").max_tokens == 8000 + + +def test_model_without_declared_limit_passes_requests_through(): + registry = _registry(_model("local"), timeline_segmentation=32000) + + assert registry.get_llm_operation("timeline_segmentation").max_tokens == 32000 + + +def test_route_explanation_still_works_for_a_misconfigured_operation(): + registry = _registry(_model("small", 16384), timeline_segmentation=32000) + + assert registry.explain_llm_operation("timeline_segmentation")["model"] == "small" + + +def test_findings_name_each_oversized_setting(): + registry = _registry(_model("small", 16384), timeline_segmentation=32000, chat=8000) + + findings = output_token_limit_findings( + registry, + [("timeline.pi.max_tokens", "timeline_segmentation", 32000)], + ) + + assert [f["setting"] for f in findings] == [ + "llm_operations.timeline_segmentation.max_tokens", + "timeline.pi.max_tokens", + ] + assert findings[0]["model"] == "small" + assert findings[0]["requested"] == 32000 + assert findings[0]["limit"] == 16384 + + +def _pi_config(max_output_tokens) -> _PiRuntimeConfig: + return _PiRuntimeConfig( + binary="pi", + provider="openai", + model="gpt-4o-mini", + base_url="https://api.openai.com/v1", + api_key="k", + thinking="off", + max_tokens=4096, + context_window=98304, + timeout_seconds=30, + reasoning=False, + temperature=0.0, + max_output_tokens=max_output_tokens, + model_entry="openai-llm", + ) + + +def test_timeline_pi_override_refuses_a_small_model(monkeypatch): + monkeypatch.setattr( + pi_executor, "_resolve_pi_config", lambda operation: _pi_config(16384) + ) + executor = pi_executor.PiTimelineExecutor({"max_tokens": 32000}) + + with pytest.raises(OutputLimitExceeded, match="timeline.pi.max_tokens needs 32000"): + executor._final_stage_config(None) + + +def test_timeline_pi_override_kept_for_a_large_model(monkeypatch): + monkeypatch.setattr( + pi_executor, "_resolve_pi_config", lambda operation: _pi_config(None) + ) + + config = pi_executor.PiTimelineExecutor({"max_tokens": 32000})._final_stage_config( + None + ) + + assert config.max_tokens == 32000 + + +def test_timeline_preflight_refuses_before_a_day_is_queued(monkeypatch): + monkeypatch.setattr( + timeline_executor, + "settings_dict", + lambda: {"executor": "pi", "pi": {"max_tokens": 32000}}, + ) + monkeypatch.setattr( + timeline_executor, + "get_models_registry", + lambda: _registry(_model("openai-llm", 16384)), + ) + + with pytest.raises(OutputLimitExceeded, match="model 'openai-llm'"): + timeline_executor.check_output_limits() + + +def test_timeline_preflight_ignores_the_codex_executor(monkeypatch): + monkeypatch.setattr( + timeline_executor, + "settings_dict", + lambda: {"executor": "codex", "pi": {"max_tokens": 32000}}, + ) + monkeypatch.setattr( + timeline_executor, + "get_models_registry", + lambda: _registry(_model("openai-llm", 16384)), + ) + + timeline_executor.check_output_limits() + + +def test_shipped_openai_models_declare_their_output_limits(): + models = {m["name"]: m for m in yaml.safe_load(DEFAULTS_YML.read_text())["models"]} + + assert models["openai-llm"]["model_name"] == "gpt-4.1-mini" + assert models["openai-llm"]["max_output_tokens"] == 32768 + assert models["fallback-llm"]["model_name"] == "gpt-5-nano" + assert models["fallback-llm"]["max_output_tokens"] == 128000 + + +def test_config_diagnostics_ask_for_a_bigger_model(monkeypatch): + # Imported here to keep the controller's import graph out of the other tests. + import backend.controllers.system_controller as system_controller + + monkeypatch.setattr( + system_controller, + "load_config", + lambda: {"timeline": {"pi": {"max_tokens": 32000}}}, + ) + registry = _registry(_model("openai-llm", 16384)) + + issues = system_controller._output_limit_issues(registry) + + assert len(issues) == 1 + assert issues[0]["severity"] == "error" + assert "needs a model with at least 32000 output tokens" in issues[0]["message"] + assert "accepts at most 16384" in issues[0]["message"] + assert issues[0]["resolution"].startswith("Settings > AI Model Settings") diff --git a/backend/webui/src/pages/Timeline.tsx b/backend/webui/src/pages/Timeline.tsx index 2de34764..e4313006 100644 --- a/backend/webui/src/pages/Timeline.tsx +++ b/backend/webui/src/pages/Timeline.tsx @@ -208,6 +208,16 @@ export default function Timeline() { setReconciliationRequestId(request.request_id) }, }) + // A start can be refused before anything is queued (e.g. the timeline model's + // output limit is too small); show the server's reason, not a silent no-op. + const startFailure = (reconcile.error || bypassImmich.error) as + | { response?: { status?: number; data?: { detail?: unknown } }; message?: string } + | null + const startDetail = startFailure?.response?.data?.detail + const reconcileStartError = startFailure + ? typeof startDetail === 'string' ? startDetail : startFailure.message || 'Request failed' + : null + const reconcileStartModelProblem = startFailure?.response?.status === 409 const reconciliation = useQuery({ queryKey: ['timeline-reconciliation', reconciliationRequestId], queryFn: async () => (await timelineApi.getReconciliation(reconciliationRequestId!)).data, @@ -390,6 +400,13 @@ export default function Timeline() { The previous analysis failed. {status.error} )} + {reconcileStartError && ( +
+ + Could not start analysis. {reconcileStartError} + {reconcileStartModelProblem && Change model} +
+ )} {timeline.isError && (
diff --git a/config/config.yml.template b/config/config.yml.template index 0710947e..99265218 100644 --- a/config/config.yml.template +++ b/config/config.yml.template @@ -58,12 +58,13 @@ models: embedding_dimensions: 768 model_output: vector - name: openai-llm - description: OpenAI GPT-4o-mini + description: OpenAI GPT-4.1-mini model_type: llm model_provider: openai api_family: openai - model_name: gpt-4o-mini + model_name: gpt-4.1-mini model_url: https://api.openai.com/v1 + max_output_tokens: 32768 api_key: ${oc.env:OPENAI_API_KEY,''} model_params: temperature: 0.2 diff --git a/config/defaults.yml b/config/defaults.yml index b8e54dcd..1026b7f3 100644 --- a/config/defaults.yml +++ b/config/defaults.yml @@ -25,12 +25,15 @@ models: # LLM Models # =========================== - name: openai-llm - description: OpenAI GPT-4o-mini + description: OpenAI GPT-4.1-mini model_type: llm model_provider: openai api_family: openai - model_name: gpt-4o-mini + model_name: gpt-4.1-mini model_url: https://api.openai.com/v1 + # Completion cap enforced by OpenAI. An operation that asks for more is refused + # with a prompt to choose a larger-output model. + max_output_tokens: 32768 api_key: ${oc.env:OPENAI_API_KEY,''} model_params: temperature: 0.2 @@ -47,6 +50,7 @@ models: api_family: openai model_name: gpt-5-nano model_url: https://api.openai.com/v1 + max_output_tokens: 128000 api_key: ${oc.env:OPENAI_API_KEY,''} model_params: temperature: 0.2 @@ -902,7 +906,7 @@ backend: provider: openai # or ollama api_key: ${oc.env:OPENAI_API_KEY,''} base_url: https://api.openai.com/v1 - model: gpt-4o-mini + model: gpt-4.1-mini timeout: 60 # Transcription provider configuration diff --git a/wizard.py b/wizard.py index 9c4c72fa..083ee39d 100755 --- a/wizard.py +++ b/wizard.py @@ -1438,7 +1438,7 @@ def select_llm_provider( default_choice = llm_to_choice.get(existing_llm, "1") choices = { - "1": "OpenAI (GPT-4o-mini, requires API key)", + "1": "OpenAI (GPT-4.1-mini, requires API key)", "2": "Ollama (local models, runs on your machine)", "3": "llama.cpp (Chronicle-managed, local GGUF models, GPU recommended)", "4": "None (skip memory extraction)",