mirror of
https://github.com/smkrv/ha-text-ai.git
synced 2026-07-23 23:54:02 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
93558b2444 | ||
|
|
9f93f1ee18 | ||
|
|
30a9b53ba1 | ||
|
|
5175970d55 |
@@ -62,24 +62,6 @@ STEP_USER_DATA_SCHEMA = vol.Schema({
|
|||||||
),
|
),
|
||||||
})
|
})
|
||||||
|
|
||||||
async def validate_endpoint(endpoint: str) -> Tuple[bool, str]:
|
|
||||||
"""Validate API endpoint accessibility."""
|
|
||||||
try:
|
|
||||||
parsed_url = urlparse(endpoint)
|
|
||||||
if parsed_url.scheme not in ('http', 'https'):
|
|
||||||
return False, "invalid_endpoint_scheme"
|
|
||||||
|
|
||||||
connector = aiohttp.TCPConnector(ssl=SSL_CONTEXT)
|
|
||||||
async with timeout(5):
|
|
||||||
async with aiohttp.ClientSession(connector=connector) as session:
|
|
||||||
async with session.get(endpoint) as response:
|
|
||||||
if response.status != 200:
|
|
||||||
return False, "endpoint_not_available"
|
|
||||||
return True, ""
|
|
||||||
except Exception as e:
|
|
||||||
_LOGGER.error("Error validating endpoint: %s", str(e))
|
|
||||||
return False, "endpoint_error"
|
|
||||||
|
|
||||||
async def validate_api_connection(
|
async def validate_api_connection(
|
||||||
api_key: str,
|
api_key: str,
|
||||||
endpoint: str,
|
endpoint: str,
|
||||||
@@ -87,64 +69,56 @@ async def validate_api_connection(
|
|||||||
retry_count: int = 3,
|
retry_count: int = 3,
|
||||||
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 retry logic."""
|
||||||
# Validate endpoint first
|
for attempt in range(retry_count):
|
||||||
endpoint_valid, endpoint_error = await validate_endpoint(endpoint)
|
try:
|
||||||
if not endpoint_valid:
|
async with timeout(10):
|
||||||
return False, endpoint_error, []
|
client = AsyncOpenAI(
|
||||||
|
api_key=api_key,
|
||||||
connector = aiohttp.TCPConnector(ssl=SSL_CONTEXT)
|
base_url=endpoint,
|
||||||
async with aiohttp.ClientSession(connector=connector) as session:
|
|
||||||
for attempt in range(retry_count):
|
|
||||||
try:
|
|
||||||
async with timeout(10):
|
|
||||||
client = AsyncOpenAI(
|
|
||||||
api_key=api_key,
|
|
||||||
base_url=endpoint,
|
|
||||||
http_client=session
|
|
||||||
)
|
|
||||||
|
|
||||||
models = await client.models.list()
|
|
||||||
model_ids = [model.id for model in models.data]
|
|
||||||
|
|
||||||
if model not in model_ids:
|
|
||||||
_LOGGER.warning(
|
|
||||||
"Model %s not found in available models: %s",
|
|
||||||
model,
|
|
||||||
", ".join(model_ids)
|
|
||||||
)
|
|
||||||
return False, "invalid_model", model_ids
|
|
||||||
return True, "", model_ids
|
|
||||||
|
|
||||||
except asyncio.TimeoutError:
|
|
||||||
_LOGGER.warning(
|
|
||||||
"Timeout during API validation (attempt %d/%d)",
|
|
||||||
attempt + 1,
|
|
||||||
retry_count
|
|
||||||
)
|
)
|
||||||
if attempt == retry_count - 1:
|
|
||||||
return False, "timeout", []
|
|
||||||
await asyncio.sleep(retry_delay)
|
|
||||||
|
|
||||||
except AuthenticationError as err:
|
models = await client.models.list()
|
||||||
_LOGGER.error("Authentication error: %s", str(err))
|
model_ids = [model.id for model in models.data]
|
||||||
return False, "invalid_auth", []
|
|
||||||
|
|
||||||
except RateLimitError as err:
|
if model not in model_ids:
|
||||||
_LOGGER.error("Rate limit exceeded: %s", str(err))
|
_LOGGER.warning(
|
||||||
return False, "rate_limit", []
|
"Model %s not found in available models: %s",
|
||||||
|
model,
|
||||||
|
", ".join(model_ids)
|
||||||
|
)
|
||||||
|
return False, "invalid_model", model_ids
|
||||||
|
return True, "", model_ids
|
||||||
|
|
||||||
except APIConnectionError as err:
|
except asyncio.TimeoutError:
|
||||||
_LOGGER.error("API connection error: %s", str(err))
|
_LOGGER.warning(
|
||||||
return False, "cannot_connect", []
|
"Timeout during API validation (attempt %d/%d)",
|
||||||
|
attempt + 1,
|
||||||
|
retry_count
|
||||||
|
)
|
||||||
|
if attempt == retry_count - 1:
|
||||||
|
return False, "timeout", []
|
||||||
|
await asyncio.sleep(retry_delay)
|
||||||
|
|
||||||
except APIError as err:
|
except AuthenticationError as err:
|
||||||
_LOGGER.error("API error: %s", str(err))
|
_LOGGER.error("Authentication error: %s", str(err))
|
||||||
return False, "api_error", []
|
return False, "invalid_auth", []
|
||||||
|
|
||||||
except Exception as err:
|
except RateLimitError as err:
|
||||||
_LOGGER.exception("Unexpected error during validation: %s", str(err))
|
_LOGGER.error("Rate limit exceeded: %s", str(err))
|
||||||
return False, "unknown", []
|
return False, "rate_limit", []
|
||||||
|
|
||||||
|
except APIConnectionError as err:
|
||||||
|
_LOGGER.error("API connection error: %s", str(err))
|
||||||
|
return False, "cannot_connect", []
|
||||||
|
|
||||||
|
except APIError as err:
|
||||||
|
_LOGGER.error("API error: %s", str(err))
|
||||||
|
return False, "api_error", []
|
||||||
|
|
||||||
|
except Exception as err:
|
||||||
|
_LOGGER.exception("Unexpected error during validation: %s", str(err))
|
||||||
|
return False, "unknown", []
|
||||||
|
|
||||||
class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||||
"""Handle a config flow for HA text AI."""
|
"""Handle a config flow for HA text AI."""
|
||||||
|
|||||||
@@ -9,6 +9,6 @@
|
|||||||
"issue_tracker": "https://github.com/smkrv/ha-text-ai/issues",
|
"issue_tracker": "https://github.com/smkrv/ha-text-ai/issues",
|
||||||
"requirements": ["openai>=1.0.0"],
|
"requirements": ["openai>=1.0.0"],
|
||||||
"ssdp": [],
|
"ssdp": [],
|
||||||
"version": "1.0.8",
|
"version": "1.0.9",
|
||||||
"zeroconf": []
|
"zeroconf": []
|
||||||
}
|
}
|
||||||
|
|||||||
Binary file not shown.
@@ -4,6 +4,6 @@
|
|||||||
"domains": ["sensor"],
|
"domains": ["sensor"],
|
||||||
"homeassistant": "2024.11.0",
|
"homeassistant": "2024.11.0",
|
||||||
"icon": "mdi:brain",
|
"icon": "mdi:brain",
|
||||||
"version": "1.0.8",
|
"version": "1.0.9",
|
||||||
"documentation": "https://github.com/smkrv/ha-text-ai"
|
"documentation": "https://github.com/smkrv/ha-text-ai"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
```
|
||||||
|
ha-text-ai/
|
||||||
|
│
|
||||||
|
├── custom_components/
|
||||||
|
│ └── ha_text_ai/
|
||||||
|
│ ├── __init__.py
|
||||||
|
│ ├── config_flow.py
|
||||||
|
│ ├── coordinator.py
|
||||||
|
│ ├── manifest.json
|
||||||
|
│ ├── sensor.py
|
||||||
|
│ ├── services.yaml
|
||||||
|
│ └── const.py
|
||||||
|
│
|
||||||
|
└── strings/
|
||||||
|
├── en.json
|
||||||
|
└── ru.json
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user