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:
1 parent
13c60c242a
commit
e7fcb1d7a1
10 files changed
+583
-98
No files matched your search
@@ -104,12 +104,31 @@ from .const import (
|
||||
UNSUPPORTED_PRIORITY_SERVICE_TIERS_MODELS,
|
||||
UNSUPPORTED_WEB_SEARCH_MODELS,
|
||||
)
|
||||
from .url_util import CredentialsInBaseURL, InvalidBaseURL, normalize_base_url
|
||||
from .model_list import async_fetch_model_ids, model_field
|
||||
from .url_util import (
|
||||
CredentialsInBaseURL,
|
||||
InvalidBaseURL,
|
||||
normalize_base_url,
|
||||
title_from_base_url,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
STEP_REAUTH_DATA_SCHEMA = vol.Schema(
|
||||
{
|
||||
vol.Required(CONF_BASE_URL, default=DEFAULT_BASE_URL): str,
|
||||
vol.Optional(CONF_API_KEY, default=""): str,
|
||||
}
|
||||
)
|
||||
|
||||
# The user step additionally names the provider, since there is one entry per
|
||||
# server and the host alone is a poor label. Reauth deliberately reuses the
|
||||
# schema *without* the name: that step writes its input straight back into
|
||||
# entry.data via data_updates, so a name field there would persist the title
|
||||
# as connection data on every key rotation.
|
||||
STEP_USER_DATA_SCHEMA = vol.Schema(
|
||||
{
|
||||
vol.Optional(CONF_NAME, default=""): str,
|
||||
vol.Required(CONF_BASE_URL, default=DEFAULT_BASE_URL): str,
|
||||
vol.Optional(CONF_API_KEY, default=""): str,
|
||||
}
|
||||
@@ -145,7 +164,11 @@ class OpenAIConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
errors: dict[str, str] = {}
|
||||
|
||||
if user_input is not None:
|
||||
self._async_abort_entries_match(user_input)
|
||||
# Deliberately no _async_abort_entries_match() here: upstream
|
||||
# aborts when url+key match an existing entry, which blocks
|
||||
# legitimate setups such as one entry per provider-side key, or a
|
||||
# second entry against the same server kept for a different
|
||||
# purpose. Duplicate entries are the user's call to make.
|
||||
try:
|
||||
await validate_input(self.hass, user_input)
|
||||
except CredentialsInBaseURL:
|
||||
@@ -164,35 +187,10 @@ class OpenAIConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
return self.async_update_reload_and_abort(
|
||||
self._get_reauth_entry(), data_updates=user_input
|
||||
)
|
||||
name = (user_input.pop(CONF_NAME, "") or "").strip()
|
||||
return self.async_create_entry(
|
||||
title="ChatGPT",
|
||||
title=name or title_from_base_url(user_input[CONF_BASE_URL]),
|
||||
data=user_input,
|
||||
subentries=[
|
||||
{
|
||||
"subentry_type": "conversation",
|
||||
"data": RECOMMENDED_CONVERSATION_OPTIONS,
|
||||
"title": DEFAULT_CONVERSATION_NAME,
|
||||
"unique_id": None,
|
||||
},
|
||||
{
|
||||
"subentry_type": "ai_task_data",
|
||||
"data": RECOMMENDED_AI_TASK_OPTIONS,
|
||||
"title": DEFAULT_AI_TASK_NAME,
|
||||
"unique_id": None,
|
||||
},
|
||||
{
|
||||
"subentry_type": "stt",
|
||||
"data": RECOMMENDED_STT_OPTIONS,
|
||||
"title": DEFAULT_STT_NAME,
|
||||
"unique_id": None,
|
||||
},
|
||||
{
|
||||
"subentry_type": "tts",
|
||||
"data": RECOMMENDED_TTS_OPTIONS,
|
||||
"title": DEFAULT_TTS_NAME,
|
||||
"unique_id": None,
|
||||
},
|
||||
],
|
||||
)
|
||||
|
||||
return self.async_show_form(
|
||||
@@ -202,7 +200,7 @@ class OpenAIConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
),
|
||||
errors=errors,
|
||||
description_placeholders={
|
||||
"instructions_url": "https://github.com/adamjs83/ha-openai-compatible#generate-an-api-key",
|
||||
"instructions_url": "https://github.com/adamjs83/ha-openai-compatible#configuration",
|
||||
},
|
||||
)
|
||||
|
||||
@@ -220,7 +218,7 @@ class OpenAIConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
return self.async_show_form(
|
||||
step_id="reauth_confirm",
|
||||
data_schema=self.add_suggested_values_to_schema(
|
||||
STEP_USER_DATA_SCHEMA, self._get_reauth_entry().data
|
||||
STEP_REAUTH_DATA_SCHEMA, self._get_reauth_entry().data
|
||||
),
|
||||
)
|
||||
|
||||
@@ -259,6 +257,14 @@ class OpenAISubentryFlowHandler(ConfigSubentryFlow):
|
||||
self.options = RECOMMENDED_AI_TASK_OPTIONS.copy()
|
||||
else:
|
||||
self.options = RECOMMENDED_CONVERSATION_OPTIONS.copy()
|
||||
# Start a new endpoint with "recommended" unticked. Ticked (upstream's
|
||||
# default) creates the subentry straight from this first step, which
|
||||
# silently pins RECOMMENDED_CHAT_MODEL -- an OpenAI model name that a
|
||||
# third-party provider will not serve -- and never shows the model
|
||||
# field at all. Unticked, the next step asks which model to use.
|
||||
# Reconfigure is untouched: it keeps whatever the subentry was saved
|
||||
# with, via async_step_reconfigure.
|
||||
self.options[CONF_RECOMMENDED] = False
|
||||
return await self.async_step_init()
|
||||
|
||||
async def async_step_reconfigure(
|
||||
@@ -359,10 +365,14 @@ class OpenAISubentryFlowHandler(ConfigSubentryFlow):
|
||||
errors: dict[str, str] = {}
|
||||
|
||||
step_schema: VolDictType = {
|
||||
# Upstream makes this a free-text box defaulting to an OpenAI
|
||||
# model name. Offer what the provider actually serves instead.
|
||||
vol.Optional(
|
||||
CONF_CHAT_MODEL,
|
||||
default=RECOMMENDED_CHAT_MODEL,
|
||||
): str,
|
||||
): model_field(
|
||||
await async_fetch_model_ids(self._get_entry().runtime_data)
|
||||
),
|
||||
vol.Optional(
|
||||
CONF_MAX_TOKENS,
|
||||
default=RECOMMENDED_MAX_TOKENS,
|
||||
@@ -406,7 +416,7 @@ class OpenAISubentryFlowHandler(ConfigSubentryFlow):
|
||||
|
||||
step_schema: VolDictType = {}
|
||||
|
||||
model = options[CONF_CHAT_MODEL]
|
||||
model = options.get(CONF_CHAT_MODEL, RECOMMENDED_CHAT_MODEL)
|
||||
|
||||
if not model.startswith(tuple(UNSUPPORTED_CODE_INTERPRETER_MODELS)):
|
||||
step_schema.update(
|
||||
@@ -763,18 +773,12 @@ class OpenAISubentrySTTFlowHandler(ConfigSubentryFlow):
|
||||
): TextSelector(
|
||||
TextSelectorConfig(multiline=True, type=TextSelectorType.TEXT)
|
||||
),
|
||||
# Upstream hardcodes OpenAI's three transcribe models here;
|
||||
# ask the provider instead.
|
||||
vol.Optional(
|
||||
CONF_CHAT_MODEL, default=RECOMMENDED_STT_MODEL
|
||||
): SelectSelector(
|
||||
SelectSelectorConfig(
|
||||
options=[
|
||||
"gpt-4o-transcribe",
|
||||
"gpt-4o-mini-transcribe",
|
||||
"whisper-1",
|
||||
],
|
||||
mode=SelectSelectorMode.DROPDOWN,
|
||||
custom_value=True,
|
||||
)
|
||||
): model_field(
|
||||
await async_fetch_model_ids(self._get_entry().runtime_data)
|
||||
),
|
||||
}
|
||||
)
|
||||
@@ -847,6 +851,15 @@ class OpenAISubentryTTSFlowHandler(ConfigSubentryFlow):
|
||||
vol.Optional(CONF_PROMPT): TextSelector(
|
||||
TextSelectorConfig(multiline=True, type=TextSelectorType.TEXT)
|
||||
),
|
||||
# Upstream offers no model field for TTS at all -- it silently
|
||||
# uses RECOMMENDED_TTS_OPTIONS' gpt-4o-mini-tts, which a
|
||||
# third-party endpoint is unlikely to serve.
|
||||
vol.Optional(
|
||||
CONF_CHAT_MODEL,
|
||||
default=RECOMMENDED_TTS_OPTIONS[CONF_CHAT_MODEL],
|
||||
): model_field(
|
||||
await async_fetch_model_ids(self._get_entry().runtime_data)
|
||||
),
|
||||
vol.Optional(
|
||||
CONF_TTS_SPEED, default=RECOMMENDED_TTS_SPEED
|
||||
): NumberSelector(NumberSelectorConfig(min=0.25, max=4.0, step=0.01)),
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Model discovery for an OpenAI-compatible endpoint.
|
||||
|
||||
Upstream hardcodes OpenAI's model names as defaults and validates them
|
||||
against lists of OpenAI models, which is useless against a proxy or a
|
||||
self-hosted server serving entirely different names. This asks the endpoint
|
||||
what it actually serves, so the config flow can offer a dropdown instead of
|
||||
a free-text box the user has to get exactly right.
|
||||
|
||||
Kept separate from the vendored upstream files so re-syncing with
|
||||
home-assistant/core never conflicts with it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import openai
|
||||
|
||||
from homeassistant.helpers.selector import (
|
||||
SelectSelector,
|
||||
SelectSelectorConfig,
|
||||
SelectSelectorMode,
|
||||
)
|
||||
|
||||
from .const import LOGGER
|
||||
|
||||
DEFAULT_TIMEOUT = 10.0
|
||||
|
||||
|
||||
async def async_fetch_model_ids(
|
||||
client: openai.AsyncOpenAI, *, timeout: float = DEFAULT_TIMEOUT
|
||||
) -> list[str]:
|
||||
"""Return the endpoint's model ids, sorted and de-duplicated.
|
||||
|
||||
Returns an empty list if the endpoint cannot or will not list them. Model
|
||||
discovery is a convenience: an endpoint that serves /v1/responses but not
|
||||
/v1/models, or a key scoped so narrowly it cannot enumerate, must still be
|
||||
configurable by typing a model name in by hand.
|
||||
"""
|
||||
try:
|
||||
# max_retries=0: the SDK otherwise retries with backoff, and this call
|
||||
# runs while the user waits on a config-flow dialog. Discovery is a
|
||||
# convenience with a free-text fallback, so one quick attempt is the
|
||||
# right trade -- retrying would just stall the form.
|
||||
page = await client.with_options(
|
||||
max_retries=0, timeout=timeout
|
||||
).models.list()
|
||||
except openai.OpenAIError as err:
|
||||
LOGGER.debug("Could not list models: %s", err)
|
||||
return []
|
||||
|
||||
return sorted({model.id for model in page.data if getattr(model, "id", None)})
|
||||
|
||||
|
||||
def model_field(model_ids: list[str]) -> Any:
|
||||
"""Return a schema field for choosing a model.
|
||||
|
||||
A dropdown of what the endpoint advertises when that is known, otherwise a
|
||||
plain string field. The dropdown accepts a typed-in value too, since an
|
||||
endpoint may route a model it does not list (LiteLLM wildcard routes, for
|
||||
instance).
|
||||
"""
|
||||
if not model_ids:
|
||||
return str
|
||||
|
||||
return SelectSelector(
|
||||
SelectSelectorConfig(
|
||||
options=model_ids,
|
||||
custom_value=True,
|
||||
mode=SelectSelectorMode.DROPDOWN,
|
||||
sort=True,
|
||||
)
|
||||
)
|
||||
@@ -26,13 +26,15 @@
|
||||
"user": {
|
||||
"data": {
|
||||
"api_key": "[%key:common::config_flow::data::api_key%]",
|
||||
"base_url": "API base URL"
|
||||
"base_url": "API base URL",
|
||||
"name": "[%key:common::config_flow::data::name%]"
|
||||
},
|
||||
"data_description": {
|
||||
"api_key": "Your OpenAI API key.",
|
||||
"base_url": "The base URL of the OpenAI-compatible API, including any version path such as /v1. The endpoint must implement the Responses API."
|
||||
"api_key": "The API key for this endpoint. Leave blank if it does not require authentication.",
|
||||
"base_url": "The base URL of the OpenAI-compatible API, including any version path such as /v1. The endpoint must implement the Responses API.",
|
||||
"name": "A label for this provider, for example LiteLLM. Defaults to the endpoint's host."
|
||||
},
|
||||
"description": "Set up OpenAI Conversation integration by providing your OpenAI API key. Instructions to obtain an API key can be found [here]({instructions_url})."
|
||||
"description": "Connect to an OpenAI-compatible API. One entry per server or provider; you add endpoints for individual models afterwards. See the [setup notes]({instructions_url}) for what the endpoint has to support."
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
"base_url": "API base URL"
|
||||
},
|
||||
"data_description": {
|
||||
"api_key": "Your OpenAI API key.",
|
||||
"api_key": "The API key for this endpoint. Leave blank if it does not require authentication.",
|
||||
"base_url": "The base URL of the OpenAI-compatible API, including any version path such as /v1. The endpoint must implement the Responses API."
|
||||
},
|
||||
"description": "Reauthentication required. Please enter your updated API key and confirm the API base URL."
|
||||
@@ -26,13 +26,15 @@
|
||||
"user": {
|
||||
"data": {
|
||||
"api_key": "API key",
|
||||
"base_url": "API base URL"
|
||||
"base_url": "API base URL",
|
||||
"name": "Name"
|
||||
},
|
||||
"data_description": {
|
||||
"api_key": "Your OpenAI API key.",
|
||||
"base_url": "The base URL of the OpenAI-compatible API, including any version path such as /v1. The endpoint must implement the Responses API."
|
||||
"api_key": "The API key for this endpoint. Leave blank if it does not require authentication.",
|
||||
"base_url": "The base URL of the OpenAI-compatible API, including any version path such as /v1. The endpoint must implement the Responses API.",
|
||||
"name": "A label for this provider, for example LiteLLM. Defaults to the endpoint's host."
|
||||
},
|
||||
"description": "Set up OpenAI Conversation integration by providing your OpenAI API key. Instructions to obtain an API key can be found [here]({instructions_url})."
|
||||
"description": "Connect to an OpenAI-compatible API. One entry per server or provider; you add endpoints for individual models afterwards. See the [setup notes]({instructions_url}) for what the endpoint has to support."
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -72,3 +72,19 @@ def sanitize_url_for_logging(url: str) -> str:
|
||||
if parsed.port:
|
||||
host = f"{host}:{parsed.port}"
|
||||
return urlunparse(parsed._replace(netloc=f"***@{host}"))
|
||||
|
||||
|
||||
def title_from_base_url(url: str) -> str:
|
||||
"""Return a config entry title identifying the provider.
|
||||
|
||||
Upstream titles every entry "ChatGPT", which is wrong the moment the
|
||||
endpoint is not OpenAI's and useless when there is one entry per provider.
|
||||
The host (with port, when given) is what actually distinguishes them.
|
||||
Falls back to the whole string if it cannot be parsed, so this never
|
||||
raises in the middle of creating an entry.
|
||||
"""
|
||||
try:
|
||||
netloc = urlparse(url).netloc
|
||||
except ValueError:
|
||||
return url
|
||||
return netloc or url
|
||||
Reference in new issue
Block a user