feat: one entry per provider, endpoints per type and model from a live dropdown

Reshapes setup around how a multi-model proxy is actually used: one config
entry per server/provider, then one endpoint per model added by hand, with
the model chosen from what that provider advertises right now.

Setup (async_step_user):
- Adds a Name field. With one entry per provider the title matters, and it
  was hardcoded to "ChatGPT" regardless of where the entry pointed. Blank
  falls back to the endpoint host via url_util.title_from_base_url.
  Deliberately absent from the reauth schema (now split out as
  STEP_REAUTH_DATA_SCHEMA): that step writes its input back into entry.data
  via data_updates, so a name field there would persist the title as
  connection data on every key rotation.
- Stops auto-creating four subentries. conversation/ai_task_data/stt/tts were
  all created up front carrying RECOMMENDED_* options, which pin OpenAI model
  names (gpt-4o-mini-tts, gpt-4o-mini-transcribe). Against a third-party
  endpoint those entities are dead on arrival -- the reported symptom was an
  install that "loads bits, it's all janky".
- Drops _async_abort_entries_match, so several entries may point at one
  server (one per provider-side key, for instance). Upstream aborts with
  already_configured on matching url+key.

Model discovery (new model_list.py, kept out of the vendored files like
url_util.py):
- async_fetch_model_ids asks the endpoint's GET /v1/models. It calls
  with_options(max_retries=0), because this runs while the user waits on a
  dialog and the SDK otherwise retries with backoff -- visible in the test
  run as repeated "Retrying request to /models" and a suite that went from
  5s to minutes.
- Returns [] on any OpenAIError, and model_field() then yields a plain text
  field instead of a dropdown, so an endpoint that serves /v1/responses but
  not /v1/models is still configurable by hand. The dropdown sets
  custom_value=True for the same reason (LiteLLM wildcard routes).
- Wired into all four types: conversation and ai_task_data on the additional
  step, stt (which hardcoded OpenAI's three transcribe models) and tts on
  init. TTS had no model field at all -- it silently used gpt-4o-mini-tts.

A new endpoint now starts with "recommended" unticked. Ticked, the flow ends
on the first step and never shows a model field, which is why the model
looked unpickable; reconfigure still keeps whatever was saved.

The model field stays on the additional step rather than moving to init. The
init position reads better, but 71 ported tests drive the model through the
additional step, several from parametrized option dicts that no mechanical
edit could relocate. Rewriting the only regression net against upstream to
save one click was the wrong trade.

Also: the setup description no longer says "your OpenAI API key", and
instructions_url pointed at a README anchor (#generate-an-api-key) that does
not exist -- now #configuration. strings.json re-verified against core's
RE_URL: 0 violations.

Local: 167 passed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NxJYWgGJtCw13qUHZtG8ki
This commit is contained in:
Adam SmithandClaude Opus 5 committed 2026-09-17 22:45:36 -04:00
1 parent 13c60c242a
commit e7fcb1d7a1
10 files changed
+583 -98

No files matched your search

+152
View File
@@ -0,0 +1,152 @@
"""Each endpoint type picks its model from what the provider advertises.
Upstream defaults every model field to an OpenAI name and offers no way to see
what the endpoint actually serves, so configuring a proxy meant typing exact
model ids from memory -- and for conversation/AI Task the field was skipped
entirely unless you knew to untick "recommended" first.
"""
from unittest.mock import patch
import pytest
from homeassistant import config_entries
from homeassistant.const import CONF_NAME
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers.selector import SelectSelector
from pytest_homeassistant_custom_component.common import MockConfigEntry
from custom_components.openai_compatible.const import (
CONF_CHAT_MODEL,
CONF_RECOMMENDED,
)
PROVIDER_MODELS = ["claude-sonnet-4-6", "gpt-4o-mini", "whisper-1"]
DISCOVERY = "custom_components.openai_compatible.config_flow.async_fetch_model_ids"
def _field(result: dict, key: str):
"""Return the schema field for key in a shown form."""
schema = result["data_schema"].schema
return next(value for marker, value in schema.items() if marker == key)
def _marker(result: dict, key: str):
"""Return the schema marker (which carries the default) for key."""
schema = result["data_schema"].schema
return next(marker for marker in schema if marker == key)
async def _model_step(
hass: HomeAssistant,
entry: MockConfigEntry,
subentry_type: str,
models: list[str],
) -> dict:
"""Return the form that asks for the model, for any endpoint type.
stt and tts are single-step flows that ask on init; conversation and
ai_task_data ask on the step after it.
"""
with patch(DISCOVERY, return_value=models):
result = await hass.config_entries.subentries.async_init(
(entry.entry_id, subentry_type),
context={"source": config_entries.SOURCE_USER},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "init"
if subentry_type in ("stt", "tts"):
return result
result = await hass.config_entries.subentries.async_configure(
result["flow_id"],
{CONF_NAME: "An endpoint", CONF_RECOMMENDED: False},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "additional"
return result
@pytest.mark.parametrize(
"subentry_type", ["conversation", "ai_task_data", "stt", "tts"]
)
async def test_every_type_offers_the_providers_models(
hass: HomeAssistant,
mock_init_component: None,
mock_config_entry: MockConfigEntry,
subentry_type: str,
) -> None:
"""All four endpoint types get a dropdown, not a free-text box."""
result = await _model_step(
hass, mock_config_entry, subentry_type, PROVIDER_MODELS
)
field = _field(result, CONF_CHAT_MODEL)
assert isinstance(field, SelectSelector)
assert field.config["options"] == PROVIDER_MODELS
# A provider may route a model it does not advertise.
assert field.config["custom_value"] is True
@pytest.mark.parametrize(
"subentry_type", ["conversation", "ai_task_data", "stt", "tts"]
)
async def test_falls_back_to_free_text_when_provider_lists_nothing(
hass: HomeAssistant,
mock_init_component: None,
mock_config_entry: MockConfigEntry,
subentry_type: str,
) -> None:
"""An endpoint without /v1/models must still be configurable by hand."""
result = await _model_step(hass, mock_config_entry, subentry_type, [])
assert _field(result, CONF_CHAT_MODEL) is str
async def test_new_endpoint_starts_with_recommended_unticked(
hass: HomeAssistant,
mock_init_component: None,
mock_config_entry: MockConfigEntry,
) -> None:
"""Ticked, the flow ends on the first step and never asks for a model."""
with patch(DISCOVERY, return_value=PROVIDER_MODELS):
result = await hass.config_entries.subentries.async_init(
(mock_config_entry.entry_id, "conversation"),
context={"source": config_entries.SOURCE_USER},
)
assert _marker(result, CONF_RECOMMENDED).default() is False
async def test_a_non_openai_model_name_survives_the_flow(
hass: HomeAssistant,
mock_init_component: None,
mock_config_entry: MockConfigEntry,
) -> None:
"""The point of the fork: the stored model is the provider's, and none of
upstream's OpenAI-specific model gates reject it."""
with patch(DISCOVERY, return_value=PROVIDER_MODELS):
result = await hass.config_entries.subentries.async_init(
(mock_config_entry.entry_id, "conversation"),
context={"source": config_entries.SOURCE_USER},
)
result = await hass.config_entries.subentries.async_configure(
result["flow_id"],
{CONF_NAME: "Sonnet via LiteLLM", CONF_RECOMMENDED: False},
)
result = await hass.config_entries.subentries.async_configure(
result["flow_id"], {CONF_CHAT_MODEL: "claude-sonnet-4-6"}
)
# remaining steps take their defaults
while result["type"] is FlowResultType.FORM:
result = await hass.config_entries.subentries.async_configure(
result["flow_id"], {}
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Sonnet via LiteLLM"
assert result["data"][CONF_CHAT_MODEL] == "claude-sonnet-4-6"