diff --git a/backend/init.py b/backend/init.py index 5a4743b1..0ebf0e3a 100644 --- a/backend/init.py +++ b/backend/init.py @@ -1137,15 +1137,15 @@ def setup_fast_llm(self): def setup_fallback_llm(self): """Configure a fallback LLM that calls retry against when the primary LLM is unreachable (connection failure, timeout, 5xx). - Default: OpenAI gpt-5-nano.""" + Default: OpenAI gpt-5.4-mini.""" self.print_section("Fallback LLM (recommended)") self.console.print( "[blue][INFO][/blue] If your main LLM is unreachable (e.g. a local " "model is down), LLM calls are retried once against a fallback model." ) self.console.print( - "The default fallback is OpenAI gpt-5-nano (cheap, always available). " - "It uses your OPENAI_API_KEY." + "The default fallback is OpenAI gpt-5.4-mini. It uses your " + "OPENAI_API_KEY and requires access to that model." ) self.console.print() @@ -1161,16 +1161,34 @@ def setup_fallback_llm(self): ), {}, ) + if ( + existing_fb == "fallback-llm" + and existing_model.get("model_name") + in ("gpt-5-nano", "gpt-5-nano-2025-08-07") + and (existing_model.get("model_url") or "https://api.openai.com/v1").rstrip( + "/" + ) + == "https://api.openai.com/v1" + ): + self.console.print( + f"[yellow][WARNING][/yellow] OpenAI retires {existing_model['model_name']} " + "on December 11, 2026. Choose option 1 to replace the saved " + "fallback with the recommended model." + ) is_custom = bool(existing_fb) and ( existing_fb != "fallback-llm" or ( existing_model - and existing_model.get("model_name") not in ("", "gpt-5-nano") + and ( + existing_model.get("model_name") not in ("", "gpt-5.4-mini") + or (existing_model.get("model_url") or "").rstrip("/") + not in ("", "https://api.openai.com/v1") + ) ) ) choices = { - "1": "OpenAI gpt-5-nano (recommended)", + "1": "OpenAI gpt-5.4-mini (recommended)", "2": "Custom OpenAI-compatible endpoint", "3": "No fallback", } @@ -1188,7 +1206,7 @@ def setup_fallback_llm(self): return if choice == "1": - # Stock gpt-5-nano entry ships in defaults.yml; re-sync a stale + # Stock gpt-5.4-mini entry ships in defaults.yml; re-sync a stale # customized copy in config.yml so it doesn't shadow the default. if existing_model: self.config_manager.sync_models_from_defaults(["fallback-llm"]) @@ -1208,7 +1226,7 @@ def setup_fallback_llm(self): ) self.config_manager.update_config_defaults({"fallback_llm": "fallback-llm"}) self.console.print( - "[green][SUCCESS][/green] Fallback LLM: OpenAI gpt-5-nano " + "[green][SUCCESS][/green] Fallback LLM: OpenAI gpt-5.4-mini " "(defaults.fallback_llm: fallback-llm)" ) return @@ -1236,8 +1254,8 @@ def setup_fallback_llm(self): self.config["FALLBACK_LLM_API_KEY"] = api_key model_name = self.prompt_value( - "Fallback LLM model name (e.g., gpt-5-nano, llama-3.1-8b-instant)", - existing_model.get("model_name", "gpt-5-nano"), + "Fallback LLM model name (e.g., gpt-5.4-mini, llama-3.1-8b-instant)", + existing_model.get("model_name", "gpt-5.4-mini"), ) if not model_name: self.console.print( diff --git a/backend/src/backend/llm_client.py b/backend/src/backend/llm_client.py index 7eb3ae51..8730e388 100644 --- a/backend/src/backend/llm_client.py +++ b/backend/src/backend/llm_client.py @@ -439,6 +439,8 @@ async def _chat_once(op, model_override): api_params["temperature"] = temperature if model_override is not None: api_params["model"] = model_override + if not model_supports_temperature(api_params.get("model")): + api_params.pop("temperature", None) api_params["messages"] = op.prepare_messages(messages) if tools: api_params["tools"] = tools @@ -581,6 +583,8 @@ async def _attempt(op, model_override): api_params["temperature"] = temperature if model_override is not None: api_params["model"] = model_override + if not model_supports_temperature(api_params.get("model")): + api_params.pop("temperature", None) api_params["messages"] = op.prepare_messages(messages) if tools: api_params["tools"] = tools diff --git a/backend/tests/test_fallback_llm_requests.py b/backend/tests/test_fallback_llm_requests.py new file mode 100644 index 00000000..f4f147b4 --- /dev/null +++ b/backend/tests/test_fallback_llm_requests.py @@ -0,0 +1,210 @@ +"""Exercise fallback requests through the configured client and the OpenAI SDK.""" + +import json +from pathlib import Path + +import httpx +import pytest +from omegaconf import OmegaConf +from openai import AsyncOpenAI + +from backend import llm_client, model_registry +from backend.model_registry import AppModels, LLMOperationConfig, ModelDef + + +@pytest.mark.parametrize("entrypoint", ["generate", "chat", "stream"]) +@pytest.mark.parametrize( + "operation", + [ + "unconfigured", + "memory_extraction", + "memory_write", + "memory_search", + "timeline_merge", + "voice_conversation", + ], +) +@pytest.mark.parametrize("custom_model", [False, True], ids=["shipped", "custom"]) +@pytest.mark.parametrize("temperature", [None, 0.6]) +async def test_fallback_request_preserves_operation_and_model_contract( + monkeypatch, entrypoint, operation, custom_model, temperature +): + monkeypatch.setenv("OPENAI_API_KEY", "test-fallback-key") + defaults = OmegaConf.load( + Path(__file__).resolve().parents[2] / "config" / "defaults.yml" + ) + fallback_config = next(m for m in defaults.models if m.name == "fallback-llm") + fallback = ModelDef.model_validate( + OmegaConf.to_container(fallback_config, resolve=True) + ) + assert fallback.model_name == "gpt-5.4-mini" + if custom_model: + fallback = fallback.model_copy( + update={ + "model_name": "llama3.1", + "model_provider": "ollama", + "model_url": "http://local.test/v1", + } + ) + operation_config = ( + LLMOperationConfig.model_validate( + OmegaConf.to_container(defaults.llm_operations[operation]) + ) + if operation in defaults.llm_operations + else LLMOperationConfig() + ) + primary = ModelDef( + name=operation_config.model or "primary", + model_type="llm", + model_provider="ollama", + model_name="local-primary", + model_url="http://primary.test/v1", + api_key="test-primary-key", + ) + registry = AppModels( + defaults={"llm": primary.name, "fallback_llm": fallback.name}, + models={primary.name: primary, fallback.name: fallback}, + llm_operations={operation: operation_config}, + ) + monkeypatch.setattr(llm_client, "get_models_registry", lambda: registry) + requests = [] + tools = ( + [ + { + "type": "function", + "function": { + "name": "read_note", + "parameters": {"type": "object", "properties": {}}, + }, + } + ] + if operation in {"memory_write", "memory_search"} and entrypoint != "generate" + else None + ) + tool_call = { + "id": "call-note", + "type": "function", + "function": {"name": "read_note", "arguments": "{}"}, + } + content = '{"ok":true}' + + def respond(request): + body = json.loads(request.content) + requests.append((request, body)) + assert request.url.path == "/v1/chat/completions" + if body["model"] == primary.model_name: + return httpx.Response(503, json={"error": {"message": "unavailable"}}) + message = {"role": "assistant", "content": None if tools else content} + if tools: + message["tool_calls"] = [tool_call] + finish_reason = "tool_calls" if tools else "stop" + response = { + "id": "chatcmpl-fallback", + "object": "chat.completion", + "created": 0, + "model": fallback.model_name, + "choices": [ + {"index": 0, "message": message, "finish_reason": finish_reason} + ], + } + if body.get("stream"): + delta = {"role": "assistant", "content": None if tools else content} + if tools: + delta["tool_calls"] = [{"index": 0, **tool_call}] + chunk = { + **response, + "object": "chat.completion.chunk", + "choices": [ + {"index": 0, "delta": delta, "finish_reason": finish_reason} + ], + } + return httpx.Response( + 200, + headers={"Content-Type": "text/event-stream"}, + text=f"data: {json.dumps(chunk)}\n\ndata: [DONE]\n\n", + ) + return httpx.Response(200, json=response) + + clients = [] + + def create_client(*, api_key, base_url, is_async): + assert is_async + client = AsyncOpenAI( + api_key=api_key, + base_url=base_url, + max_retries=0, + http_client=httpx.AsyncClient(transport=httpx.MockTransport(respond)), + ) + clients.append(client) + return client + + monkeypatch.setattr(model_registry, "create_openai_client", create_client) + messages = [{"role": "user", "content": "Return JSON or use the note tool."}] + try: + if entrypoint == "generate": + result = await llm_client.async_generate( + messages[0]["content"], operation=operation, temperature=temperature + ) + assert json.loads(result) == {"ok": True} + elif entrypoint == "chat": + result = await llm_client.async_chat_with_tools( + messages, tools, operation=operation, temperature=temperature + ) + if tools: + assert ( + result.choices[0].message.tool_calls[0].function.name == "read_note" + ) + else: + assert json.loads(result.choices[0].message.content) == {"ok": True} + else: + events = [ + event + async for event in llm_client.async_chat_with_tools_stream( + messages, tools, operation=operation, temperature=temperature + ) + ] + assert events[-1]["type"] == "done" + if tools: + assert events[-1]["tool_calls"] == [tool_call] + else: + assert json.loads(events[-1]["content"]) == {"ok": True} + finally: + for client in clients: + await client.close() + + assert len(requests) == 2 + primary_request, primary_body = requests[0] + fallback_request, body = requests[1] + assert primary_request.url.host == "primary.test" + expected_temperature = ( + temperature + if temperature is not None + else ( + operation_config.temperature + if operation_config.temperature is not None + else 0.2 + ) + ) + assert primary_body["temperature"] == expected_temperature + assert fallback_request.url.host == ( + "local.test" if custom_model else "api.openai.com" + ) + assert fallback_request.headers["authorization"] == "Bearer test-fallback-key" + assert body["model"] == fallback.model_name + assert body["messages"] == messages + budget = operation_config.max_tokens or 4000 + if custom_model: + assert body["temperature"] == expected_temperature + assert body["max_tokens"] == budget + assert "max_completion_tokens" not in body + else: + assert "temperature" not in body + assert "max_tokens" not in body + assert body["max_completion_tokens"] == budget + assert body["reasoning_effort"] == ( + operation_config.reasoning_effort or "medium" + ) + if operation_config.response_format == "json": + assert body["response_format"] == {"type": "json_object"} + if tools: + assert body["tools"] == tools diff --git a/config/defaults.yml b/config/defaults.yml index b8e54dcd..de62d0ae 100644 --- a/config/defaults.yml +++ b/config/defaults.yml @@ -39,18 +39,21 @@ models: # Fallback LLM: retried once when the main LLM is unreachable (connection # failure/timeout/5xx). Enabled by setting defaults.fallback_llm: fallback-llm - # (the wizard asks). gpt-5-nano = cheapest OpenAI reasoning-class model. + # (the wizard asks). gpt-5.4-mini supports reasoning with Chat Completions tools. + # GPT-5.6/GPT-6 Luna require Responses for reasoning with tools. - name: fallback-llm description: Fallback LLM used when the primary LLM is unreachable model_type: llm model_provider: openai api_family: openai - model_name: gpt-5-nano + model_name: gpt-5.4-mini model_url: https://api.openai.com/v1 api_key: ${oc.env:OPENAI_API_KEY,''} model_params: temperature: 0.2 max_tokens: 4000 + # Preserve GPT-5 nano's effective default; operations can override it. + reasoning_effort: medium model_output: json - name: local-llm diff --git a/quickstart.md b/quickstart.md index 7140fcc7..e85b224a 100644 --- a/quickstart.md +++ b/quickstart.md @@ -155,6 +155,23 @@ The wizard will ask questions - here's what to answer: #### Optional (Both Paths): +**"Fallback LLM when the main LLM is down?"**: The recommended fallback is +`gpt-5.4-mini`, using `OPENAI_API_KEY`. Your OpenAI project must have access to it. +It supports Chronicle's Chat Completions tools with reasoning enabled. OpenAI's +listed replacement, `gpt-6-luna`, and the `gpt-5.6` family require the Responses API +for reasoning with tools. See the [GPT-6 Luna model page](https://developers.openai.com/api/docs/models/gpt-6-luna) +and [GPT-5.6 migration guide](https://developers.openai.com/api/docs/guides/upgrading-to-gpt-5p6-sol#chat-completions-and-function-tools). +The fallback costs more per token than GPT-5 nano or GPT-5.6 Luna; check +[GPT-5.4 mini pricing](https://developers.openai.com/api/docs/models/gpt-5.4-mini) +before enabling it, or choose a custom endpoint or no fallback. + +If you previously saved `gpt-5-nano` or `gpt-5-nano-2025-08-07` in +`config/config.yml`, that override takes precedence over shipped defaults. +OpenAI [retires both on December 11, 2026](https://developers.openai.com/api/docs/deprecations). +Rerun `./wizard.sh` and choose fallback option **1** to replace the saved +`fallback-llm` entry, or update your custom fallback explicitly. Existing custom +and disabled fallback choices remain selected when you rerun setup. + **"Enable Speaker Recognition"**: Say Yes if you got Hugging Face token **"Hugging Face token"**: Paste your token (if you got one) diff --git a/tests/unit/test_fallback_llm_setup.py b/tests/unit/test_fallback_llm_setup.py new file mode 100644 index 00000000..1f6522ff --- /dev/null +++ b/tests/unit/test_fallback_llm_setup.py @@ -0,0 +1,160 @@ +"""Fallback setup must update saved defaults without replacing custom choices.""" + +import importlib.util +import io +import shutil +from pathlib import Path +from unittest.mock import Mock + +import pytest +import yaml +from chronicle_setup import ConfigManager +from rich.console import Console + +REPO_ROOT = Path(__file__).resolve().parents[2] + + +@pytest.fixture(scope="module") +def init_module(): + spec = importlib.util.spec_from_file_location( + "fallback_backend_init", REPO_ROOT / "backend" / "init.py" + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +@pytest.fixture +def setup_factory(tmp_path, init_module): + config_dir = tmp_path / "config" + config_dir.mkdir() + shutil.copy2(REPO_ROOT / "config" / "defaults.yml", config_dir / "defaults.yml") + + def create(config, choice=None): + (config_dir / "config.yml").write_text(yaml.safe_dump(config)) + setup = object.__new__(init_module.ChronicleSetup) + setup.console = Console(file=io.StringIO(), width=160) + setup.config = {} + setup.config_manager = ConfigManager(repo_root=tmp_path) + setup.prompt_choice = Mock( + side_effect=lambda _prompt, _choices, default: choice or default + ) + setup.prompt_value = Mock(side_effect=lambda _prompt, default: default) + setup.prompt_with_existing_masked = Mock(return_value="") + return setup + + return create + + +def test_new_setup_selects_shipped_fallback(setup_factory): + setup = setup_factory({}) + + setup.setup_fallback_llm() + + assert setup.prompt_choice.call_args.args[2] == "1" + assert ( + setup.config_manager.get_full_config()["defaults"]["fallback_llm"] + == "fallback-llm" + ) + assert "gpt-5.4-mini" in setup.console.file.getvalue() + + +@pytest.mark.parametrize("model_name", ["gpt-5-nano", "gpt-5-nano-2025-08-07"]) +def test_recommended_choice_replaces_retired_saved_model(setup_factory, model_name): + setup = setup_factory( + { + "defaults": {"llm": "primary", "fallback_llm": "fallback-llm"}, + "models": [ + {"name": "primary", "model_name": "custom-primary"}, + { + "name": "fallback-llm", + "model_name": model_name, + "model_url": "https://api.openai.com/v1", + }, + ], + }, + choice="1", + ) + + setup.setup_fallback_llm() + + config = setup.config_manager.get_full_config() + saved_model = next(m for m in config["models"] if m["name"] == "fallback-llm") + assert saved_model["model_name"] == "gpt-5.4-mini" + assert saved_model["api_key"] == "${oc.env:OPENAI_API_KEY,''}" + assert saved_model["model_params"]["max_tokens"] == 4000 + assert saved_model["model_params"]["reasoning_effort"] == "medium" + assert config["models"][0] == {"name": "primary", "model_name": "custom-primary"} + assert config["defaults"]["llm"] == "primary" + output = setup.console.file.getvalue() + assert model_name in output + assert "December 11, 2026" in output + assert "option 1" in output + + +def test_rerun_keeps_fallback_disabled(setup_factory): + setup = setup_factory({"defaults": {"fallback_llm": ""}}) + + setup.setup_fallback_llm() + + assert setup.prompt_choice.call_args.args[2] == "3" + assert setup.config_manager.get_full_config()["defaults"]["fallback_llm"] == "" + setup.prompt_with_existing_masked.assert_not_called() + + +@pytest.mark.parametrize("model_url", [None, "", "https://api.openai.com/v1/"]) +def test_rerun_resyncs_stock_fallback_url(setup_factory, model_url): + setup = setup_factory( + { + "defaults": {"fallback_llm": "fallback-llm"}, + "models": [ + { + "name": "fallback-llm", + "model_name": "gpt-5.4-mini", + "model_url": model_url, + } + ], + } + ) + + setup.setup_fallback_llm() + + assert setup.prompt_choice.call_args.args[2] == "1" + saved_model = setup.config_manager.get_full_config()["models"][0] + assert saved_model["model_url"] == "https://api.openai.com/v1" + + +@pytest.mark.parametrize("model_name", ["custom-llama", "gpt-5.4-mini", "gpt-5-nano"]) +def test_rerun_preserves_custom_endpoint_and_model(setup_factory, model_name): + setup = setup_factory( + { + "defaults": {"fallback_llm": "fallback-llm"}, + "models": [ + { + "name": "fallback-llm", + "model_name": model_name, + "model_url": "http://local.test/v1", + } + ], + } + ) + + setup.setup_fallback_llm() + + assert setup.prompt_choice.call_args.args[2] == "2" + config = setup.config_manager.get_full_config() + saved_model = next(m for m in config["models"] if m["name"] == "fallback-llm") + assert saved_model["model_name"] == model_name + assert saved_model["model_url"] == "http://local.test/v1" + assert "December 11, 2026" not in setup.console.file.getvalue() + + +def test_custom_setup_suggests_supported_fallback(setup_factory): + setup = setup_factory({}, choice="2") + + setup.setup_fallback_llm() + + config = setup.config_manager.get_full_config() + saved_model = next(m for m in config["models"] if m["name"] == "fallback-llm") + assert saved_model["model_name"] == "gpt-5.4-mini" + assert saved_model["model_url"] == "https://api.openai.com/v1"