Files
ha-text-ai/custom_components/ha_text_ai/providers.py
T
SMKRV a8a91972ba fix: Comprehensive v2.4.0 quality pass — 24 review findings + review agent fixes
Phase A — Critical:
- Remove dual timeout stacking in coordinator._send_to_api
- Add Gemini-specific asyncio.timeout (sync SDK via to_thread)
- Store full text in history for context; cap per-field at 32KB on disk
- Fix instance lookup to match by normalized_name
- Add Bearer/sk-/x-api-key credential sanitization patterns

Phase B — Dead code removal:
- Merge async_ask_question/async_process_question into single method
- Remove dead is_anthropic flag from coordinator and __init__
- Remove unused DEFAULT_TIMEOUT and API_TIMEOUT constants
- Remove redundant _create_history_dir calls
- Consolidate async_check_api to use provider registry

Phase C — Config flow correctness:
- Truncate name before uniqueness check (prevent post-truncation collisions)
- Add async_set_unique_id + _abort_if_unique_id_configured
- Extract shared _build_parameter_schema for ConfigFlow/OptionsFlow dedup

Phase D — UX improvements:
- Optimize history write: serialize from memory, single file write
- Show last 5 history entries in sensor attributes (was 1)
- Return actual error type in ask_question service response
- Add dedicated api_key_required error for provider/endpoint changes
- Pass config_entry to DataUpdateCoordinator (HA 2024.8+)

Phase E — Cleanup:
- Extract _apply_structured_output for OpenAI/DeepSeek dedup
- Reduce ABSOLUTE_MAX_HISTORY_SIZE to 200 with Final annotation
- Remove dead translation keys (queued, invalid_characters)
- Migrate to _attr_has_entity_name = True
- Add from __future__ import annotations to all modules
- Remove redundant api_status sensor attribute
- Add missing translation keys (last_model, last_timestamp, etc.)

Review agent fixes:
- Add archive file cleanup (max 3 archives) to prevent disk exhaustion
- Per-entry storage cap (32KB per field) for history on disk
2026-03-12 02:24:09 +03:00

98 lines
2.9 KiB
Python

"""
Provider registry for HA Text AI integration.
Centralizes provider-specific configuration to avoid dispatch duplication
across __init__.py, config_flow.py, and api_client.py.
@license: CC BY-NC-SA 4.0 International
@author: SMKRV
@github: https://github.com/smkrv/ha-text-ai
@source: https://github.com/smkrv/ha-text-ai
"""
from __future__ import annotations
from typing import Any
from .const import (
API_PROVIDER_OPENAI,
API_PROVIDER_ANTHROPIC,
API_PROVIDER_DEEPSEEK,
API_PROVIDER_GEMINI,
DEFAULT_MODEL,
DEFAULT_ANTHROPIC_MODEL,
DEFAULT_DEEPSEEK_MODEL,
DEFAULT_GEMINI_MODEL,
DEFAULT_OPENAI_ENDPOINT,
DEFAULT_ANTHROPIC_ENDPOINT,
DEFAULT_DEEPSEEK_ENDPOINT,
DEFAULT_GEMINI_ENDPOINT,
)
PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {
API_PROVIDER_OPENAI: {
"default_model": DEFAULT_MODEL,
"default_endpoint": DEFAULT_OPENAI_ENDPOINT,
"auth_header": "Authorization",
"auth_prefix": "Bearer ",
"check_path": "/models",
},
API_PROVIDER_ANTHROPIC: {
"default_model": DEFAULT_ANTHROPIC_MODEL,
"default_endpoint": DEFAULT_ANTHROPIC_ENDPOINT,
"auth_header": "x-api-key",
"auth_prefix": "",
"check_path": "/v1/models",
"extra_headers": {
"anthropic-version": "2023-06-01",
},
},
API_PROVIDER_DEEPSEEK: {
"default_model": DEFAULT_DEEPSEEK_MODEL,
"default_endpoint": DEFAULT_DEEPSEEK_ENDPOINT,
"auth_header": "Authorization",
"auth_prefix": "Bearer ",
"check_path": "/models",
},
API_PROVIDER_GEMINI: {
"default_model": DEFAULT_GEMINI_MODEL,
"default_endpoint": DEFAULT_GEMINI_ENDPOINT,
"auth_header": "Authorization",
"auth_prefix": "Bearer ",
"check_path": None, # Gemini does not support /models check
},
}
def get_provider_config(provider: str) -> dict[str, Any]:
"""Get full provider configuration.
Raises ValueError for unknown providers to avoid sending
credentials to the wrong endpoint.
"""
if provider not in PROVIDER_REGISTRY:
raise ValueError(f"Unknown API provider: {provider}")
return PROVIDER_REGISTRY[provider]
def get_default_endpoint(provider: str) -> str:
"""Get default API endpoint for a provider."""
return get_provider_config(provider)["default_endpoint"]
def get_default_model(provider: str) -> str:
"""Get default model for a provider."""
return get_provider_config(provider)["default_model"]
def build_auth_headers(provider: str, api_key: str) -> dict[str, str]:
"""Build authentication headers for a provider."""
config = get_provider_config(provider)
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
}
headers[config["auth_header"]] = f"{config['auth_prefix']}{api_key}"
if "extra_headers" in config:
headers.update(config["extra_headers"])
return headers