Main changes:

Created global SSL_CONTEXT at module level
Removed blocking create_default_context calls from async functions
Optimized aiohttp.ClientSession handling:
Using single connector with SSL context
Session is created once for all requests in validate_api_connection
Improved resource management:
Automatic session closure using context managers
More efficient connection handling
These changes should eliminate the blocking call warning and improve
overall code performance.
This commit is contained in:
SMKRV
2024-11-19 16:33:30 +03:00
parent 42324a793b
commit 2bdef2b494
+9 -14
View File
@@ -32,6 +32,9 @@ from .const import (
import logging import logging
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
# Create SSL context at module level
SSL_CONTEXT = ssl.create_default_context(cafile=certifi.where())
STEP_USER_DATA_SCHEMA = vol.Schema({ STEP_USER_DATA_SCHEMA = vol.Schema({
vol.Required(CONF_API_KEY): str, vol.Required(CONF_API_KEY): str,
vol.Optional(CONF_MODEL, default=DEFAULT_MODEL): str, vol.Optional(CONF_MODEL, default=DEFAULT_MODEL): str,
@@ -66,10 +69,10 @@ async def validate_endpoint(endpoint: str) -> Tuple[bool, str]:
if parsed_url.scheme not in ('http', 'https'): if parsed_url.scheme not in ('http', 'https'):
return False, "invalid_endpoint_scheme" return False, "invalid_endpoint_scheme"
ssl_context = ssl.create_default_context(cafile=certifi.where()) connector = aiohttp.TCPConnector(ssl=SSL_CONTEXT)
async with timeout(5): async with timeout(5):
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession(connector=connector) as session:
async with session.get(endpoint, ssl=ssl_context) as response: async with session.get(endpoint) as response:
if response.status != 200: if response.status != 200:
return False, "endpoint_not_available" return False, "endpoint_not_available"
return True, "" return True, ""
@@ -85,32 +88,24 @@ async def validate_api_connection(
retry_delay: float = 1.0 retry_delay: float = 1.0
) -> Tuple[bool, str, list]: ) -> Tuple[bool, str, list]:
"""Validate API connection with improved retry logic.""" """Validate API connection with improved retry logic."""
ssl_context = ssl.create_default_context(cafile=certifi.where())
# Validate endpoint first # Validate endpoint first
endpoint_valid, endpoint_error = await validate_endpoint(endpoint) endpoint_valid, endpoint_error = await validate_endpoint(endpoint)
if not endpoint_valid: if not endpoint_valid:
return False, endpoint_error, [] return False, endpoint_error, []
connector = aiohttp.TCPConnector(ssl=SSL_CONTEXT)
async with aiohttp.ClientSession(connector=connector) as session:
for attempt in range(retry_count): for attempt in range(retry_count):
try: try:
async with timeout(10): async with timeout(10):
client = AsyncOpenAI( client = AsyncOpenAI(
api_key=api_key, api_key=api_key,
base_url=endpoint, base_url=endpoint,
http_client=aiohttp.ClientSession( http_client=session
connector=aiohttp.TCPConnector(
ssl=ssl_context,
enable_cleanup_closed=True
)
)
) )
try:
models = await client.models.list() models = await client.models.list()
model_ids = [model.id for model in models.data] model_ids = [model.id for model in models.data]
finally:
await client.http_client.close()
if model not in model_ids: if model not in model_ids:
_LOGGER.warning( _LOGGER.warning(