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
36 changes: 27 additions & 9 deletions backend/init.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand All @@ -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",
}
Expand All @@ -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"])
Expand All @@ -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
Expand Down Expand Up @@ -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(
Expand Down
4 changes: 4 additions & 0 deletions backend/src/backend/llm_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
210 changes: 210 additions & 0 deletions backend/tests/test_fallback_llm_requests.py
Original file line number Diff line number Diff line change
@@ -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
7 changes: 5 additions & 2 deletions config/defaults.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
Loading