Stability improvements

This commit is contained in:
SMKRV
2024-11-19 23:30:28 +03:00
parent 8432038f09
commit 4c56565b66
2 changed files with 13 additions and 19 deletions
+12 -18
View File
@@ -3,14 +3,13 @@ from typing import Any, Dict, Optional, Tuple
import voluptuous as vol import voluptuous as vol
import asyncio import asyncio
from async_timeout import timeout from async_timeout import timeout
import aiohttp
from urllib.parse import urlparse from urllib.parse import urlparse
from homeassistant import config_entries from homeassistant import config_entries
from homeassistant.const import CONF_API_KEY from homeassistant.const import CONF_API_KEY
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.core import callback from homeassistant.core import callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.data_entry_flow import FlowResult
from openai import AsyncOpenAI from openai import AsyncOpenAI
from openai import OpenAIError, APIError, APIConnectionError, AuthenticationError, RateLimitError from openai import OpenAIError, APIError, APIConnectionError, AuthenticationError, RateLimitError
@@ -63,12 +62,10 @@ async def async_create_client(
api_key: str, api_key: str,
endpoint: str, endpoint: str,
) -> AsyncOpenAI: ) -> AsyncOpenAI:
"""Create AsyncOpenAI client with proper session.""" """Create AsyncOpenAI client."""
session = async_get_clientsession(hass)
return AsyncOpenAI( return AsyncOpenAI(
api_key=api_key, api_key=api_key,
base_url=endpoint, base_url=endpoint
http_client=session
) )
async def validate_api_connection( async def validate_api_connection(
@@ -134,7 +131,7 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
async def async_step_user( async def async_step_user(
self, self,
user_input: Optional[Dict[str, Any]] = None user_input: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]: ) -> FlowResult:
"""Handle the initial step.""" """Handle the initial step."""
errors: Dict[str, str] = {} errors: Dict[str, str] = {}
@@ -161,29 +158,29 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
) )
# Validate input data # Validate input data
user_input = STEP_USER_DATA_SCHEMA(user_input) validated_input = STEP_USER_DATA_SCHEMA(user_input)
is_valid, error_code, available_models = await validate_api_connection( is_valid, error_code, available_models = await validate_api_connection(
self.hass, self.hass,
user_input[CONF_API_KEY], validated_input[CONF_API_KEY],
endpoint, endpoint,
user_input[CONF_MODEL] validated_input[CONF_MODEL]
) )
if is_valid: if is_valid:
await self.async_set_unique_id(user_input[CONF_API_KEY]) await self.async_set_unique_id(validated_input[CONF_API_KEY])
self._abort_if_unique_id_configured() self._abort_if_unique_id_configured()
return self.async_create_entry( return self.async_create_entry(
title="HA text AI", title="HA Text AI",
data=user_input data=validated_input
) )
errors["base"] = error_code errors["base"] = error_code
if error_code == "invalid_model": if error_code == "invalid_model":
_LOGGER.warning( _LOGGER.warning(
"Selected model %s not found in available models: %s", "Selected model %s not found in available models: %s",
user_input[CONF_MODEL], validated_input[CONF_MODEL],
", ".join(available_models) ", ".join(available_models)
) )
@@ -219,7 +216,7 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
async def async_step_init( async def async_step_init(
self, self,
user_input: Optional[Dict[str, Any]] = None user_input: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]: ) -> FlowResult:
"""Handle options flow.""" """Handle options flow."""
if user_input is not None: if user_input is not None:
return self.async_create_entry(title="", data=user_input) return self.async_create_entry(title="", data=user_input)
@@ -230,7 +227,6 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
default=self.config_entry.options.get( default=self.config_entry.options.get(
CONF_TEMPERATURE, DEFAULT_TEMPERATURE CONF_TEMPERATURE, DEFAULT_TEMPERATURE
), ),
description={"suggested_value": DEFAULT_TEMPERATURE},
): vol.All( ): vol.All(
vol.Coerce(float), vol.Coerce(float),
vol.Range(min=0, max=2) vol.Range(min=0, max=2)
@@ -240,7 +236,6 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
default=self.config_entry.options.get( default=self.config_entry.options.get(
CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS
), ),
description={"suggested_value": DEFAULT_MAX_TOKENS},
): vol.All( ): vol.All(
vol.Coerce(int), vol.Coerce(int),
vol.Range(min=1, max=4096) vol.Range(min=1, max=4096)
@@ -250,7 +245,6 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
default=self.config_entry.options.get( default=self.config_entry.options.get(
CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL
), ),
description={"suggested_value": DEFAULT_REQUEST_INTERVAL},
): vol.All( ): vol.All(
vol.Coerce(float), vol.Coerce(float),
vol.Range(min=0.1) vol.Range(min=0.1)
+1 -1
View File
@@ -15,7 +15,7 @@ CONF_REQUEST_INTERVAL: Final = "request_interval"
# Default values # Default values
DEFAULT_MODEL: Final = "gpt-3.5-turbo" DEFAULT_MODEL: Final = "gpt-3.5-turbo"
DEFAULT_TEMPERATURE: Final = 0.7 DEFAULT_TEMPERATURE: Final = 0.1
DEFAULT_MAX_TOKENS: Final = 1000 DEFAULT_MAX_TOKENS: Final = 1000
DEFAULT_API_ENDPOINT: Final = "https://api.openai.com/v1" DEFAULT_API_ENDPOINT: Final = "https://api.openai.com/v1"
DEFAULT_REQUEST_INTERVAL: Final = 1.0 DEFAULT_REQUEST_INTERVAL: Final = 1.0