Compare commits

..
6 Commits
Author SHA1 Message Date
SMKRV 43cbac2d04 feat: Add ability to edit provider, API key, and endpoint in existing integrations
- Extended OptionsFlowHandler with two-step configuration flow
- Step 1: Select provider (OpenAI, Anthropic, DeepSeek, Gemini)
- Step 2: Configure API key, endpoint, model, and other settings
- Auto-reload integration on options change
- When switching providers, show appropriate default endpoint and model
- Updated translations for all 8 languages
2025-12-30 17:22:48 +03:00
SMKRV 986c78dd90 fix: Fix OptionsFlowHandler for HA 2024.1+ compatibility
- Remove __init__ method that was passing config_entry as argument
- OptionsFlow now automatically receives config_entry from base class
- Fixes '500 Internal Server Error' when editing existing integrations
2025-12-30 17:10:06 +03:00
SMKRV 0859c35aec fix: Change release workflow to trigger on release created event 2025-12-30 16:56:27 +03:00
SMKRV 922fefbd43 chore: Bump version to 2.3.0 2025-12-30 16:54:23 +03:00
SMKRV a5ac100b06 feat: Add structured output support with JSON schema validation
- Introduced `structured_output` and `json_schema` parameters to enhance API responses.
- Updated service schemas and API client methods to handle structured output.
- Added translations for new parameters in multiple languages.
- Updated documentation to reflect changes in service capabilities.

Closes #9
2025-12-30 16:44:01 +03:00
smkrvandGitHub ef579af7c1 Create release.yml 2025-12-30 16:27:46 +03:00
16 changed files with 576 additions and 139 deletions
+37
View File
@@ -0,0 +1,37 @@
name: Release
on:
release:
types: [created]
permissions:
contents: write
jobs:
build:
name: Build and upload release asset
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v4
with:
ref: ${{ github.event.release.tag_name }}
- name: Create zip archive
run: |
cd custom_components
zip -r ../ha_text_ai.zip ha_text_ai \
-x "ha_text_ai/__pycache__/*" \
-x "*.pyc" \
-x "*.pyo" \
-x "*/__pycache__/*" \
-x "*.DS_Store"
- name: Upload release asset
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ github.event.release.tag_name }}
files: ha_text_ai.zip
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+38 -11
View File
@@ -76,6 +76,8 @@ SERVICE_SCHEMA_ASK_QUESTION = vol.Schema({
vol.Optional("temperature"): cv.positive_float, vol.Optional("temperature"): cv.positive_float,
vol.Optional("max_tokens"): cv.positive_int, vol.Optional("max_tokens"): cv.positive_int,
vol.Optional("context_messages"): cv.positive_int, vol.Optional("context_messages"): cv.positive_int,
vol.Optional("structured_output", default=False): cv.boolean,
vol.Optional("json_schema"): cv.string,
}) })
SERVICE_SCHEMA_SET_SYSTEM_PROMPT = vol.Schema({ SERVICE_SCHEMA_SET_SYSTEM_PROMPT = vol.Schema({
@@ -127,6 +129,8 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
max_tokens=call.data.get("max_tokens"), max_tokens=call.data.get("max_tokens"),
system_prompt=call.data.get("system_prompt"), system_prompt=call.data.get("system_prompt"),
context_messages=call.data.get("context_messages"), context_messages=call.data.get("context_messages"),
structured_output=call.data.get("structured_output", False),
json_schema=call.data.get("json_schema"),
) )
# Return structured response data # Return structured response data
@@ -308,21 +312,35 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
_LOGGER.debug(f"Setting up HA Text AI entry: {entry.data}") _LOGGER.debug(f"Setting up HA Text AI entry: {entry.data}")
try: try:
if CONF_API_PROVIDER not in entry.data: # Get provider from data or options (options takes precedence)
config = {**entry.data, **entry.options}
api_provider = config.get(CONF_API_PROVIDER)
if not api_provider:
_LOGGER.error("API provider not specified") _LOGGER.error("API provider not specified")
raise ConfigEntryNotReady("API provider is required") raise ConfigEntryNotReady("API provider is required")
# Get configuration (merge data with options to apply any runtime changes)
config = {**entry.data, **entry.options}
session = aiohttp_client.async_get_clientsession(hass) session = aiohttp_client.async_get_clientsession(hass)
api_provider = config.get(CONF_API_PROVIDER)
model = config.get(CONF_MODEL, DEFAULT_MODEL) # Get default endpoint based on provider
endpoint = config.get( default_endpoint = {
CONF_API_ENDPOINT, API_PROVIDER_OPENAI: DEFAULT_OPENAI_ENDPOINT,
DEFAULT_OPENAI_ENDPOINT if api_provider == API_PROVIDER_OPENAI API_PROVIDER_ANTHROPIC: DEFAULT_ANTHROPIC_ENDPOINT,
else DEFAULT_ANTHROPIC_ENDPOINT API_PROVIDER_DEEPSEEK: DEFAULT_DEEPSEEK_ENDPOINT,
).rstrip('/') API_PROVIDER_GEMINI: DEFAULT_GEMINI_ENDPOINT,
api_key = entry.data[CONF_API_KEY] # API key stays in data, not in options }.get(api_provider, DEFAULT_OPENAI_ENDPOINT)
# Get default model based on provider
default_model = (
DEFAULT_DEEPSEEK_MODEL if api_provider == API_PROVIDER_DEEPSEEK else
DEFAULT_GEMINI_MODEL if api_provider == API_PROVIDER_GEMINI else
DEFAULT_MODEL
)
model = config.get(CONF_MODEL, default_model)
endpoint = config.get(CONF_API_ENDPOINT, default_endpoint).rstrip('/')
# API key can now be updated via options
api_key = config.get(CONF_API_KEY, entry.data.get(CONF_API_KEY))
instance_name = entry.data.get(CONF_NAME, entry.entry_id) instance_name = entry.data.get(CONF_NAME, entry.entry_id)
request_interval = config.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL) request_interval = config.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)
api_timeout = config.get(CONF_API_TIMEOUT, DEFAULT_API_TIMEOUT) api_timeout = config.get(CONF_API_TIMEOUT, DEFAULT_API_TIMEOUT)
@@ -382,6 +400,9 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
# Set up platforms # Set up platforms
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
# Register update listener for options changes
entry.async_on_unload(entry.add_update_listener(async_update_options))
_LOGGER.debug(f"Setup completed for {instance_name}") _LOGGER.debug(f"Setup completed for {instance_name}")
return True return True
@@ -390,6 +411,12 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
_LOGGER.exception(f"Error setting up HA Text AI: {err}") _LOGGER.exception(f"Error setting up HA Text AI: {err}")
raise raise
async def async_update_options(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Handle options update - reload the config entry."""
_LOGGER.info("Options updated for %s, reloading integration", entry.title)
await hass.config_entries.async_reload(entry.entry_id)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry.""" """Unload a config entry."""
try: try:
+87 -5
View File
@@ -127,6 +127,8 @@ class APIClient:
messages: List[Dict[str, str]], messages: List[Dict[str, str]],
temperature: float, temperature: float,
max_tokens: int, max_tokens: int,
structured_output: bool = False,
json_schema: Optional[str] = None,
) -> Dict[str, Any]: ) -> Dict[str, Any]:
"""Create completion using appropriate API.""" """Create completion using appropriate API."""
try: try:
@@ -134,19 +136,23 @@ class APIClient:
if self.api_provider == API_PROVIDER_ANTHROPIC: if self.api_provider == API_PROVIDER_ANTHROPIC:
return await self._create_anthropic_completion( return await self._create_anthropic_completion(
model, messages, temperature, max_tokens model, messages, temperature, max_tokens,
structured_output, json_schema
) )
elif self.api_provider == API_PROVIDER_DEEPSEEK: elif self.api_provider == API_PROVIDER_DEEPSEEK:
return await self._create_deepseek_completion( return await self._create_deepseek_completion(
model, messages, temperature, max_tokens model, messages, temperature, max_tokens,
structured_output, json_schema
) )
elif self.api_provider == API_PROVIDER_GEMINI: elif self.api_provider == API_PROVIDER_GEMINI:
return await self._create_gemini_completion( return await self._create_gemini_completion(
model, messages, temperature, max_tokens model, messages, temperature, max_tokens,
structured_output, json_schema
) )
else: else:
return await self._create_openai_completion( return await self._create_openai_completion(
model, messages, temperature, max_tokens model, messages, temperature, max_tokens,
structured_output, json_schema
) )
except Exception as e: except Exception as e:
_LOGGER.error("API request failed: %s", str(e)) _LOGGER.error("API request failed: %s", str(e))
@@ -158,6 +164,8 @@ class APIClient:
messages: List[Dict[str, str]], messages: List[Dict[str, str]],
temperature: float, temperature: float,
max_tokens: int, max_tokens: int,
structured_output: bool = False,
json_schema: Optional[str] = None,
) -> Dict[str, Any]: ) -> Dict[str, Any]:
"""Create completion using DeepSeek API.""" """Create completion using DeepSeek API."""
url = f"{self.endpoint}/chat/completions" url = f"{self.endpoint}/chat/completions"
@@ -169,6 +177,24 @@ class APIClient:
"stream": False "stream": False
} }
# Add structured output format if enabled (DeepSeek is OpenAI-compatible)
if structured_output and json_schema:
try:
import json
schema = json.loads(json_schema)
payload["response_format"] = {
"type": "json_schema",
"json_schema": {
"name": "structured_response",
"strict": True,
"schema": schema
}
}
_LOGGER.debug("DeepSeek structured output enabled with schema")
except json.JSONDecodeError as e:
_LOGGER.warning(f"Invalid JSON schema provided: {e}. Falling back to json_object mode.")
payload["response_format"] = {"type": "json_object"}
data = await self._make_request(url, payload) data = await self._make_request(url, payload)
return { return {
"choices": [ "choices": [
@@ -189,6 +215,8 @@ class APIClient:
messages: List[Dict[str, str]], messages: List[Dict[str, str]],
temperature: float, temperature: float,
max_tokens: int, max_tokens: int,
structured_output: bool = False,
json_schema: Optional[str] = None,
) -> Dict[str, Any]: ) -> Dict[str, Any]:
"""Create completion using OpenAI API.""" """Create completion using OpenAI API."""
url = f"{self.endpoint}/chat/completions" url = f"{self.endpoint}/chat/completions"
@@ -199,6 +227,24 @@ class APIClient:
"max_tokens": max_tokens, "max_tokens": max_tokens,
} }
# Add structured output format if enabled
if structured_output and json_schema:
try:
import json
schema = json.loads(json_schema)
payload["response_format"] = {
"type": "json_schema",
"json_schema": {
"name": "structured_response",
"strict": True,
"schema": schema
}
}
_LOGGER.debug("OpenAI structured output enabled with schema")
except json.JSONDecodeError as e:
_LOGGER.warning(f"Invalid JSON schema provided: {e}. Falling back to json_object mode.")
payload["response_format"] = {"type": "json_object"}
data = await self._make_request(url, payload) data = await self._make_request(url, payload)
return { return {
"choices": [ "choices": [
@@ -219,6 +265,8 @@ class APIClient:
messages: List[Dict[str, str]], messages: List[Dict[str, str]],
temperature: float, temperature: float,
max_tokens: int, max_tokens: int,
structured_output: bool = False,
json_schema: Optional[str] = None,
) -> Dict[str, Any]: ) -> Dict[str, Any]:
"""Create completion using Anthropic API.""" """Create completion using Anthropic API."""
url = f"{self.endpoint}/v1/messages" url = f"{self.endpoint}/v1/messages"
@@ -234,6 +282,20 @@ class APIClient:
else: else:
filtered_messages.append(msg) filtered_messages.append(msg)
# For Anthropic, add structured output instruction to system prompt
if structured_output and json_schema:
schema_instruction = (
f"\n\nIMPORTANT: You MUST respond ONLY with valid JSON that matches "
f"this JSON Schema:\n{json_schema}\n"
f"Do not include any text before or after the JSON. "
f"Do not wrap the JSON in markdown code blocks."
)
if system_prompt:
system_prompt += schema_instruction
else:
system_prompt = schema_instruction.strip()
_LOGGER.debug("Anthropic structured output enabled via system prompt")
payload = { payload = {
"model": model, "model": model,
"messages": filtered_messages, "messages": filtered_messages,
@@ -273,6 +335,8 @@ class APIClient:
messages: List[Dict[str, str]], messages: List[Dict[str, str]],
temperature: float, temperature: float,
max_tokens: int, max_tokens: int,
structured_output: bool = False,
json_schema: Optional[str] = None,
) -> Dict[str, Any]: ) -> Dict[str, Any]:
"""Create completion using Gemini API with google-genai library. """Create completion using Gemini API with google-genai library.
@@ -281,6 +345,8 @@ class APIClient:
messages: List of message dictionaries with role and content messages: List of message dictionaries with role and content
temperature: Sampling temperature between 0.0 and 2.0 temperature: Sampling temperature between 0.0 and 2.0
max_tokens: Maximum number of tokens to generate max_tokens: Maximum number of tokens to generate
structured_output: Enable JSON structured output mode
json_schema: JSON Schema for structured output validation
Returns: Returns:
Dictionary with response content and token usage Dictionary with response content and token usage
@@ -319,6 +385,16 @@ class APIClient:
"parts": [{"text": msg['content']}] "parts": [{"text": msg['content']}]
}) })
# Parse JSON schema if structured output is enabled
parsed_schema = None
if structured_output and json_schema:
try:
import json
parsed_schema = json.loads(json_schema)
_LOGGER.debug("Gemini structured output enabled with schema")
except json.JSONDecodeError as e:
_LOGGER.warning(f"Invalid JSON schema provided: {e}. Structured output disabled.")
# Create configuration # Create configuration
def create_config(): def create_config():
from google.genai import types from google.genai import types
@@ -331,6 +407,11 @@ class APIClient:
if system_instruction: if system_instruction:
config.system_instruction = system_instruction.strip() config.system_instruction = system_instruction.strip()
# Add structured output configuration for Gemini
if structured_output and parsed_schema:
config.response_mime_type = "application/json"
config.response_schema = parsed_schema
return config return config
config = await asyncio.to_thread(create_config) config = await asyncio.to_thread(create_config)
@@ -407,4 +488,5 @@ class APIClient:
async def shutdown(self) -> None: async def shutdown(self) -> None:
"""Shutdown API client.""" """Shutdown API client."""
_LOGGER.debug("Shutting down API client") _LOGGER.debug("Shutting down API client")
await self.session.close() self._closed = True
# Do NOT close the shared Home Assistant session
+207 -62
View File
@@ -473,84 +473,229 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
@callback @callback
def async_get_options_flow(config_entry: config_entries.ConfigEntry) -> config_entries.OptionsFlow: def async_get_options_flow(config_entry: config_entries.ConfigEntry) -> config_entries.OptionsFlow:
"""Get the options flow for this handler.""" """Get the options flow for this handler."""
return OptionsFlowHandler(config_entry) return OptionsFlowHandler()
class OptionsFlowHandler(config_entries.OptionsFlow): class OptionsFlowHandler(config_entries.OptionsFlow):
"""Handle options flow.""" """Handle options flow."""
def __init__(self, config_entry: config_entries.ConfigEntry) -> None: def __init__(self) -> None:
"""Initialize options flow.""" """Initialize options flow."""
self.config_entry = config_entry self._errors = {}
self._selected_provider = None
async def async_step_init(self, user_input: Optional[Dict[str, Any]] = None) -> FlowResult: def _get_default_endpoint(self, provider: str) -> str:
"""Manage the options.""" """Get default endpoint for provider."""
if user_input is not None: return {
return self.async_create_entry(title="", data=user_input) API_PROVIDER_OPENAI: DEFAULT_OPENAI_ENDPOINT,
API_PROVIDER_ANTHROPIC: DEFAULT_ANTHROPIC_ENDPOINT,
API_PROVIDER_DEEPSEEK: DEFAULT_DEEPSEEK_ENDPOINT,
API_PROVIDER_GEMINI: DEFAULT_GEMINI_ENDPOINT,
}.get(provider, DEFAULT_OPENAI_ENDPOINT)
current_data = {**self.config_entry.data, **self.config_entry.options} def _get_default_model(self, provider: str) -> str:
provider = current_data.get(CONF_API_PROVIDER) """Get default model for provider."""
return (
default_model = (
DEFAULT_DEEPSEEK_MODEL if provider == API_PROVIDER_DEEPSEEK else DEFAULT_DEEPSEEK_MODEL if provider == API_PROVIDER_DEEPSEEK else
DEFAULT_GEMINI_MODEL if provider == API_PROVIDER_GEMINI else DEFAULT_GEMINI_MODEL if provider == API_PROVIDER_GEMINI else
DEFAULT_MODEL DEFAULT_MODEL
) )
def _get_api_headers(self, api_key: str, provider: str) -> Dict[str, str]:
"""Get API headers based on provider."""
if provider == API_PROVIDER_ANTHROPIC:
return {
"x-api-key": api_key,
"anthropic-version": "2023-06-01",
"Content-Type": "application/json"
}
return {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
async def _async_validate_api(self, provider: str, api_key: str, endpoint: str) -> bool:
"""Validate API connection."""
try:
if not api_key:
self._errors["base"] = "invalid_auth"
return False
# For Gemini, just check if API key is present
if provider == API_PROVIDER_GEMINI:
return True
session = async_get_clientsession(self.hass)
headers = self._get_api_headers(api_key, provider)
endpoint = endpoint.rstrip('/')
check_url = (
f"{endpoint}/v1/models" if provider == API_PROVIDER_ANTHROPIC
else f"{endpoint}/models"
)
async with session.get(check_url, headers=headers) as response:
if response.status == 401:
self._errors["base"] = "invalid_auth"
return False
elif response.status not in [200, 404]:
self._errors["base"] = "cannot_connect"
return False
return True
except Exception as err:
_LOGGER.error("API validation error: %s", str(err))
self._errors["base"] = "cannot_connect"
return False
async def async_step_init(self, user_input: Optional[Dict[str, Any]] = None) -> FlowResult:
"""Handle provider selection step."""
current_data = {**self.config_entry.data, **self.config_entry.options}
current_provider = current_data.get(CONF_API_PROVIDER, API_PROVIDER_OPENAI)
if user_input is not None:
self._selected_provider = user_input.get(CONF_API_PROVIDER, current_provider)
return await self.async_step_settings()
return self.async_show_form( return self.async_show_form(
step_id="init", step_id="init",
data_schema=vol.Schema({ data_schema=vol.Schema({
vol.Optional( vol.Required(
CONF_MODEL, CONF_API_PROVIDER,
default=current_data.get(CONF_MODEL, default_model) default=current_provider
): str, ): selector.SelectSelector(
vol.Optional( selector.SelectSelectorConfig(
CONF_TEMPERATURE, options=API_PROVIDERS,
default=current_data.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE) translation_key="api_provider"
): vol.All(
vol.Coerce(float),
vol.Range(min=MIN_TEMPERATURE, max=MAX_TEMPERATURE)
),
vol.Optional(
CONF_MAX_TOKENS,
default=current_data.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS)
): vol.All(
vol.Coerce(int),
vol.Range(min=MIN_MAX_TOKENS, max=MAX_MAX_TOKENS)
),
vol.Optional(
CONF_REQUEST_INTERVAL,
default=current_data.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)
): vol.All(
vol.Coerce(float),
vol.Range(min=MIN_REQUEST_INTERVAL)
),
vol.Optional(
CONF_API_TIMEOUT,
default=current_data.get(CONF_API_TIMEOUT, DEFAULT_API_TIMEOUT)
): vol.All(
vol.Coerce(int),
vol.Range(min=MIN_API_TIMEOUT, max=MAX_API_TIMEOUT)
),
vol.Optional(
CONF_CONTEXT_MESSAGES,
default=current_data.get(
CONF_CONTEXT_MESSAGES,
DEFAULT_CONTEXT_MESSAGES
) )
): vol.All(
vol.Coerce(int),
vol.Range(min=1, max=20)
), ),
vol.Optional( }),
CONF_MAX_HISTORY_SIZE, description_placeholders={
default=current_data.get( "current_provider": current_provider
CONF_MAX_HISTORY_SIZE, }
DEFAULT_MAX_HISTORY
)
): vol.All(
vol.Coerce(int),
vol.Range(min=1, max=100)
),
})
) )
async def async_step_settings(self, user_input: Optional[Dict[str, Any]] = None) -> FlowResult:
"""Handle settings configuration step."""
self._errors = {}
current_data = {**self.config_entry.data, **self.config_entry.options}
provider = self._selected_provider or current_data.get(CONF_API_PROVIDER, API_PROVIDER_OPENAI)
# Determine if provider changed to show appropriate defaults
provider_changed = provider != current_data.get(CONF_API_PROVIDER)
# Use new defaults if provider changed, otherwise use current values
if provider_changed:
default_endpoint = self._get_default_endpoint(provider)
default_model = self._get_default_model(provider)
else:
default_endpoint = current_data.get(CONF_API_ENDPOINT, self._get_default_endpoint(provider))
default_model = current_data.get(CONF_MODEL, self._get_default_model(provider))
if user_input is not None:
# Validate API connection
api_key = user_input.get(CONF_API_KEY, current_data.get(CONF_API_KEY, ""))
endpoint = user_input.get(CONF_API_ENDPOINT, default_endpoint)
if await self._async_validate_api(provider, api_key, endpoint):
# Merge with provider selection
final_data = {
CONF_API_PROVIDER: provider,
**user_input
}
return self.async_create_entry(title="", data=final_data)
# Show form again with errors
return self.async_show_form(
step_id="settings",
data_schema=self._get_settings_schema(
provider=provider,
current_data=current_data,
user_input=user_input,
default_endpoint=default_endpoint,
default_model=default_model,
),
errors=self._errors
)
return self.async_show_form(
step_id="settings",
data_schema=self._get_settings_schema(
provider=provider,
current_data=current_data,
user_input=None,
default_endpoint=default_endpoint,
default_model=default_model,
),
description_placeholders={
"provider": provider
}
)
def _get_settings_schema(
self,
provider: str,
current_data: Dict[str, Any],
user_input: Optional[Dict[str, Any]],
default_endpoint: str,
default_model: str,
) -> vol.Schema:
"""Build settings schema."""
data = user_input or current_data
return vol.Schema({
vol.Required(
CONF_API_KEY,
default=data.get(CONF_API_KEY, "")
): str,
vol.Required(
CONF_API_ENDPOINT,
default=data.get(CONF_API_ENDPOINT, default_endpoint)
): str,
vol.Required(
CONF_MODEL,
default=data.get(CONF_MODEL, default_model)
): str,
vol.Optional(
CONF_TEMPERATURE,
default=data.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE)
): vol.All(
vol.Coerce(float),
vol.Range(min=MIN_TEMPERATURE, max=MAX_TEMPERATURE)
),
vol.Optional(
CONF_MAX_TOKENS,
default=data.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS)
): vol.All(
vol.Coerce(int),
vol.Range(min=MIN_MAX_TOKENS, max=MAX_MAX_TOKENS)
),
vol.Optional(
CONF_REQUEST_INTERVAL,
default=data.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)
): vol.All(
vol.Coerce(float),
vol.Range(min=MIN_REQUEST_INTERVAL)
),
vol.Optional(
CONF_API_TIMEOUT,
default=data.get(CONF_API_TIMEOUT, DEFAULT_API_TIMEOUT)
): vol.All(
vol.Coerce(int),
vol.Range(min=MIN_API_TIMEOUT, max=MAX_API_TIMEOUT)
),
vol.Optional(
CONF_CONTEXT_MESSAGES,
default=data.get(CONF_CONTEXT_MESSAGES, DEFAULT_CONTEXT_MESSAGES)
): vol.All(
vol.Coerce(int),
vol.Range(min=1, max=20)
),
vol.Optional(
CONF_MAX_HISTORY_SIZE,
default=data.get(CONF_MAX_HISTORY_SIZE, DEFAULT_MAX_HISTORY)
): vol.All(
vol.Coerce(int),
vol.Range(min=1, max=100)
),
})
+5 -1
View File
@@ -66,6 +66,8 @@ CONF_INSTANCE: Final = "instance"
CONF_MAX_HISTORY_SIZE: Final = "max_history_size" # Correct constant name CONF_MAX_HISTORY_SIZE: Final = "max_history_size" # Correct constant name
CONF_IS_ANTHROPIC: Final = "is_anthropic" CONF_IS_ANTHROPIC: Final = "is_anthropic"
CONF_CONTEXT_MESSAGES: Final = "context_messages" CONF_CONTEXT_MESSAGES: Final = "context_messages"
CONF_STRUCTURED_OUTPUT: Final = "structured_output"
CONF_JSON_SCHEMA: Final = "json_schema"
ABSOLUTE_MAX_HISTORY_SIZE = 500 ABSOLUTE_MAX_HISTORY_SIZE = 500
MAX_ATTRIBUTE_SIZE = 4 * 1024 MAX_ATTRIBUTE_SIZE = 4 * 1024
@@ -199,7 +201,9 @@ SERVICE_SCHEMA_ASK_QUESTION = vol.Schema({
vol.Optional("context_messages"): vol.All( vol.Optional("context_messages"): vol.All(
vol.Coerce(int), vol.Coerce(int),
vol.Range(min=1, max=20) vol.Range(min=1, max=20)
) ),
vol.Optional(CONF_STRUCTURED_OUTPUT, default=False): cv.boolean,
vol.Optional(CONF_JSON_SCHEMA): cv.string,
}) })
SERVICE_SCHEMA_SET_SYSTEM_PROMPT = vol.Schema({ SERVICE_SCHEMA_SET_SYSTEM_PROMPT = vol.Schema({
+24 -37
View File
@@ -189,16 +189,10 @@ class HATextAICoordinator(DataUpdateCoordinator):
# Maximum history file size (1 MB) from const.py # Maximum history file size (1 MB) from const.py
self._max_history_file_size = MAX_HISTORY_FILE_SIZE self._max_history_file_size = MAX_HISTORY_FILE_SIZE
# Asynchronous file initialization self.context_messages = context_messages
hass.async_create_task(self.async_initialize_history_file())
_LOGGER.info(f"Initialized HA Text AI coordinator with instance: {instance_name}") _LOGGER.info(f"Initialized HA Text AI coordinator with instance: {instance_name}")
# Register instance
self.hass.data.setdefault(DOMAIN, {})
self.hass.data[DOMAIN][instance_name] = self
self.context_messages = context_messages
@property @property
def last_response(self) -> Dict[str, Any]: def last_response(self) -> Dict[str, Any]:
""" """
@@ -826,6 +820,8 @@ class HATextAICoordinator(DataUpdateCoordinator):
max_tokens: Optional[int] = None, max_tokens: Optional[int] = None,
system_prompt: Optional[str] = None, system_prompt: Optional[str] = None,
context_messages: Optional[int] = None, context_messages: Optional[int] = None,
structured_output: bool = False,
json_schema: Optional[str] = None,
) -> dict: ) -> dict:
""" """
Process a question with optional parameters. Process a question with optional parameters.
@@ -841,12 +837,15 @@ class HATextAICoordinator(DataUpdateCoordinator):
max_tokens: Optional maximum response length max_tokens: Optional maximum response length
system_prompt: Optional system-level instruction system_prompt: Optional system-level instruction
context_messages: Optional number of context messages to include context_messages: Optional number of context messages to include
structured_output: Enable JSON structured output mode
json_schema: JSON Schema for structured output validation
Returns: Returns:
Full response dictionary from the AI Full response dictionary from the AI
""" """
return await self.async_process_question( return await self.async_process_question(
question, model, temperature, max_tokens, system_prompt, context_messages question, model, temperature, max_tokens, system_prompt, context_messages,
structured_output, json_schema
) )
async def async_process_question( async def async_process_question(
@@ -857,6 +856,8 @@ class HATextAICoordinator(DataUpdateCoordinator):
max_tokens: Optional[int] = None, max_tokens: Optional[int] = None,
system_prompt: Optional[str] = None, system_prompt: Optional[str] = None,
context_messages: Optional[int] = None, context_messages: Optional[int] = None,
structured_output: bool = False,
json_schema: Optional[str] = None,
) -> dict: ) -> dict:
"""Process question with context management.""" """Process question with context management."""
if self.client is None: if self.client is None:
@@ -895,6 +896,8 @@ class HATextAICoordinator(DataUpdateCoordinator):
"temperature": temp_temperature, "temperature": temp_temperature,
"max_tokens": temp_max_tokens, "max_tokens": temp_max_tokens,
"messages": messages, "messages": messages,
"structured_output": structured_output,
"json_schema": json_schema,
} }
response = await self.async_process_message(question, **kwargs) response = await self.async_process_message(question, **kwargs)
@@ -909,7 +912,7 @@ class HATextAICoordinator(DataUpdateCoordinator):
return response return response
except Exception as err: except Exception as err:
self._handle_error(err) await self._handle_error(err)
raise HomeAssistantError(f"Failed to process question: {err}") raise HomeAssistantError(f"Failed to process question: {err}")
finally: finally:
@@ -919,11 +922,15 @@ class HATextAICoordinator(DataUpdateCoordinator):
async def async_process_message(self, question: str, **kwargs) -> dict: async def async_process_message(self, question: str, **kwargs) -> dict:
"""Process message using the AI client.""" """Process message using the AI client."""
try: try:
structured_output = kwargs.pop("structured_output", False)
json_schema = kwargs.pop("json_schema", None)
async with asyncio.timeout(self.api_timeout): async with asyncio.timeout(self.api_timeout):
if self.is_anthropic: # APIClient.create() handles provider routing internally
response = await self._process_anthropic_message(question, **kwargs) response = await self._process_openai_message(
else: question, structured_output=structured_output,
response = await self._process_openai_message(question, **kwargs) json_schema=json_schema, **kwargs
)
# Add timestamp and model information to response # Add timestamp and model information to response
timestamp = dt_util.utcnow().isoformat() timestamp = dt_util.utcnow().isoformat()
@@ -959,30 +966,8 @@ class HATextAICoordinator(DataUpdateCoordinator):
await self._handle_error(err) await self._handle_error(err)
raise raise
async def _process_anthropic_message(self, question: str, **kwargs) -> dict: async def _process_openai_message(self, question: str, structured_output: bool = False,
"""Process message using Anthropic API.""" json_schema: Optional[str] = None, **kwargs) -> dict:
try:
_LOGGER.debug(f"Anthropic API call: model={kwargs['model']}, max_tokens={kwargs['max_tokens']}")
response = await self.client.messages.create(
model=kwargs["model"],
max_tokens=kwargs["max_tokens"],
messages=kwargs["messages"],
temperature=kwargs["temperature"],
)
_LOGGER.debug(f"Anthropic response: tokens={response.usage}")
return {
"content": response.content[0].text,
"tokens": {
"prompt": response.usage.input_tokens,
"completion": response.usage.output_tokens,
"total": response.usage.input_tokens + response.usage.output_tokens,
},
}
except Exception as e:
_LOGGER.error(f"Anthropic API error: {str(e)}")
raise
async def _process_openai_message(self, question: str, **kwargs) -> dict:
"""Process message using OpenAI API.""" """Process message using OpenAI API."""
try: try:
response = await self.client.create( response = await self.client.create(
@@ -990,6 +975,8 @@ class HATextAICoordinator(DataUpdateCoordinator):
messages=kwargs["messages"], messages=kwargs["messages"],
temperature=kwargs["temperature"], temperature=kwargs["temperature"],
max_tokens=kwargs["max_tokens"], max_tokens=kwargs["max_tokens"],
structured_output=structured_output,
json_schema=json_schema,
) )
return { return {
+6 -5
View File
@@ -14,16 +14,17 @@
"mqtt": [], "mqtt": [],
"quality_scale": "silver", "quality_scale": "silver",
"requirements": [ "requirements": [
"openai>=1.12.0", "aiofiles>=23.0.0",
"anthropic>=0.8.0",
"google-genai>=1.16.0",
"aiohttp>=3.8.0", "aiohttp>=3.8.0",
"anthropic>=0.8.0",
"async-timeout>=4.0.0", "async-timeout>=4.0.0",
"certifi>=2024.2.2" "certifi>=2024.2.2",
"google-genai>=1.16.0",
"openai>=1.12.0"
], ],
"single_config_entry": false, "single_config_entry": false,
"ssdp": [], "ssdp": [],
"usb": [], "usb": [],
"version": "2.2.0", "version": "2.3.0",
"zeroconf": [] "zeroconf": []
} }
+19 -1
View File
@@ -74,6 +74,24 @@ ask_question:
step: 1 step: 1
mode: box mode: box
structured_output:
name: Structured Output
description: Enable JSON structured output mode. When enabled, the AI will respond with valid JSON matching the provided schema.
required: false
default: false
selector:
boolean: {}
json_schema:
name: JSON Schema
description: >-
JSON Schema defining the structure of the expected response.
Required when structured_output is enabled.
required: false
selector:
text:
multiline: true
clear_history: clear_history:
name: Clear History name: Clear History
description: >- description: >-
@@ -135,7 +153,7 @@ get_history:
required: false required: false
default: false default: false
selector: selector:
boolean: boolean: {}
sort_order: sort_order:
name: Sort Order name: Sort Order
@@ -74,13 +74,22 @@
"options": { "options": {
"step": { "step": {
"init": { "init": {
"title": "Instanzeinstellungen aktualisieren", "title": "Anbieter auswählen",
"description": "Ändern Sie die Einstellungen für diese AI-Assistenteninstanz.", "description": "Wählen Sie den AI-Anbieter für diese Instanz. Die Integration wird nach dem Speichern der Änderungen neu geladen.",
"data": { "data": {
"api_provider": "API-Anbieter"
}
},
"settings": {
"title": "Verbindungs- und Modelleinstellungen",
"description": "Konfigurieren Sie API-Anmeldeinformationen und Modellparameter. Änderungen werden nach dem Neuladen der Integration wirksam.",
"data": {
"api_key": "API-Schlüssel",
"api_endpoint": "API-Endpunkt-URL",
"model": "AI-Modell", "model": "AI-Modell",
"temperature": "Kreativität der Antwort (0-2)", "temperature": "Kreativität der Antwort (0-2)",
"max_tokens": "Maximale Länge der Antwort (1-100000)", "max_tokens": "Maximale Länge der Antwort (1-100000)",
"request_interval": "Minimale Anfrageintervall (0,1-60 Sekunden)", "request_interval": "Minimales Anfrageintervall (0,1-60 Sekunden)",
"api_timeout": "API-Anfrage Timeout in Sekunden (5-600)", "api_timeout": "API-Anfrage Timeout in Sekunden (5-600)",
"context_messages": "Anzahl der vorherigen Nachrichten, die im Kontext enthalten sein sollen (1-20)", "context_messages": "Anzahl der vorherigen Nachrichten, die im Kontext enthalten sein sollen (1-20)",
"max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)" "max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)"
@@ -130,6 +139,14 @@
"max_tokens": { "max_tokens": {
"name": "Max Tokens", "name": "Max Tokens",
"description": "Maximale Länge der Antwort (1-100000 Token)" "description": "Maximale Länge der Antwort (1-100000 Token)"
},
"structured_output": {
"name": "Strukturierte Ausgabe",
"description": "JSON-Strukturausgabemodus aktivieren. Bei Aktivierung antwortet die KI mit gültigem JSON, das dem angegebenen Schema entspricht."
},
"json_schema": {
"name": "JSON-Schema",
"description": "JSON-Schema, das die Struktur der erwarteten Antwort definiert. Erforderlich wenn structured_output aktiviert ist."
} }
} }
}, },
@@ -74,9 +74,18 @@
"options": { "options": {
"step": { "step": {
"init": { "init": {
"title": "Update Instance Settings", "title": "Select Provider",
"description": "Modify settings for this AI assistant instance.", "description": "Choose the AI provider for this instance. The integration will reload after saving changes.",
"data": { "data": {
"api_provider": "API Provider"
}
},
"settings": {
"title": "Connection & Model Settings",
"description": "Configure API credentials and model parameters. Changes will take effect after the integration reloads.",
"data": {
"api_key": "API Key",
"api_endpoint": "API Endpoint URL",
"model": "AI model", "model": "AI model",
"temperature": "Response creativity (0-2)", "temperature": "Response creativity (0-2)",
"max_tokens": "Maximum response length (1-100000)", "max_tokens": "Maximum response length (1-100000)",
@@ -130,6 +139,14 @@
"max_tokens": { "max_tokens": {
"name": "Max Tokens", "name": "Max Tokens",
"description": "Maximum length of the response (1-100000 tokens)" "description": "Maximum length of the response (1-100000 tokens)"
},
"structured_output": {
"name": "Structured Output",
"description": "Enable JSON structured output mode. When enabled, the AI will respond with valid JSON matching the provided schema."
},
"json_schema": {
"name": "JSON Schema",
"description": "JSON Schema defining the structure of the expected response. Required when structured_output is enabled."
} }
} }
}, },
@@ -74,9 +74,18 @@
"options": { "options": {
"step": { "step": {
"init": { "init": {
"title": "Actualizar configuración de la instancia", "title": "Seleccionar proveedor",
"description": "Modifica la configuración para esta instancia de asistente de IA.", "description": "Elige el proveedor de IA para esta instancia. La integración se recargará después de guardar los cambios.",
"data": { "data": {
"api_provider": "Proveedor de API"
}
},
"settings": {
"title": "Configuración de conexión y modelo",
"description": "Configura las credenciales de API y los parámetros del modelo. Los cambios tendrán efecto después de recargar la integración.",
"data": {
"api_key": "Clave API",
"api_endpoint": "URL del endpoint de API",
"model": "Modelo de IA", "model": "Modelo de IA",
"temperature": "Creatividad de la respuesta (0-2)", "temperature": "Creatividad de la respuesta (0-2)",
"max_tokens": "Longitud máxima de la respuesta (1-100000)", "max_tokens": "Longitud máxima de la respuesta (1-100000)",
@@ -130,6 +139,14 @@
"max_tokens": { "max_tokens": {
"name": "Máx. Tokens", "name": "Máx. Tokens",
"description": "Longitud máxima de la respuesta (1-100000 tokens)" "description": "Longitud máxima de la respuesta (1-100000 tokens)"
},
"structured_output": {
"name": "Salida Estructurada",
"description": "Habilitar modo de salida JSON estructurada. Cuando está habilitado, la IA responderá con JSON válido que coincida con el esquema proporcionado."
},
"json_schema": {
"name": "Esquema JSON",
"description": "Esquema JSON que define la estructura de la respuesta esperada. Requerido cuando structured_output está habilitado."
} }
} }
}, },
@@ -65,9 +65,18 @@
"options": { "options": {
"step": { "step": {
"init": { "init": {
"title": "उदाहरण सेटिंग्स अपडेट करें", "title": "प्रदाता चुनें",
"description": "इस एआई सहायक उदाहरण के लिए सेटिंग्स संशोधित करें।", "description": "इस उदाहरण के लिए एआई प्रदाता चुनें। परिवर्तन सहेजने के बाद एकीकरण पुनः लोड होगा।",
"data": { "data": {
"api_provider": "एपीआई प्रदाता"
}
},
"settings": {
"title": "कनेक्शन और मॉडल सेटिंग्स",
"description": "एपीआई क्रेडेंशियल और मॉडल पैरामीटर कॉन्फ़िगर करें। एकीकरण पुनः लोड होने के बाद परिवर्तन प्रभावी होंगे।",
"data": {
"api_key": "एपीआई कुंजी",
"api_endpoint": "एपीआई एंडपॉइंट यूआरएल",
"model": "एआई मॉडल", "model": "एआई मॉडल",
"temperature": "प्रतिक्रिया की रचनात्मकता (0-2)", "temperature": "प्रतिक्रिया की रचनात्मकता (0-2)",
"max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-100000)", "max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-100000)",
@@ -121,6 +130,14 @@
"max_tokens": { "max_tokens": {
"name": "अधिकतम टोकन", "name": "अधिकतम टोकन",
"description": "प्रतिक्रिया की अधिकतम लंबाई (1-100000 टोकन)" "description": "प्रतिक्रिया की अधिकतम लंबाई (1-100000 टोकन)"
},
"structured_output": {
"name": "संरचित आउटपुट",
"description": "JSON संरचित आउटपुट मोड सक्षम करें। सक्षम होने पर, AI प्रदान किए गए स्कीमा से मेल खाने वाले वैध JSON के साथ प्रतिक्रिया देगा।"
},
"json_schema": {
"name": "JSON स्कीमा",
"description": "अपेक्षित प्रतिक्रिया की संरचना को परिभाषित करने वाला JSON स्कीमा। structured_output सक्षम होने पर आवश्यक।"
} }
} }
}, },
@@ -74,9 +74,18 @@
"options": { "options": {
"step": { "step": {
"init": { "init": {
"title": "Aggiorna impostazioni dell'istanza", "title": "Seleziona fornitore",
"description": "Modifica le impostazioni per questa istanza di assistente AI.", "description": "Scegli il fornitore AI per questa istanza. L'integrazione verrà ricaricata dopo aver salvato le modifiche.",
"data": { "data": {
"api_provider": "Fornitore API"
}
},
"settings": {
"title": "Impostazioni di connessione e modello",
"description": "Configura le credenziali API e i parametri del modello. Le modifiche avranno effetto dopo il ricaricamento dell'integrazione.",
"data": {
"api_key": "Chiave API",
"api_endpoint": "URL dell'endpoint API",
"model": "Modello AI", "model": "Modello AI",
"temperature": "Creatività della risposta (0-2)", "temperature": "Creatività della risposta (0-2)",
"max_tokens": "Lunghezza massima della risposta (1-100000)", "max_tokens": "Lunghezza massima della risposta (1-100000)",
@@ -130,6 +139,14 @@
"max_tokens": { "max_tokens": {
"name": "Token massimi", "name": "Token massimi",
"description": "Lunghezza massima della risposta (1-100000 token)" "description": "Lunghezza massima della risposta (1-100000 token)"
},
"structured_output": {
"name": "Output Strutturato",
"description": "Abilita la modalità di output JSON strutturato. Quando abilitato, l'IA risponderà con JSON valido corrispondente allo schema fornito."
},
"json_schema": {
"name": "Schema JSON",
"description": "Schema JSON che definisce la struttura della risposta attesa. Richiesto quando structured_output è abilitato."
} }
} }
}, },
@@ -74,9 +74,18 @@
"options": { "options": {
"step": { "step": {
"init": { "init": {
"title": "Обновление настроек экземпляра", "title": "Выбор провайдера",
"description": "Измените настройки для этого экземпляра ИИ-помощника.", "description": "Выберите провайдера ИИ для этого экземпляра. Интеграция перезагрузится после сохранения изменений.",
"data": { "data": {
"api_provider": "Провайдер API"
}
},
"settings": {
"title": "Настройки подключения и модели",
"description": "Настройте учётные данные API и параметры модели. Изменения вступят в силу после перезагрузки интеграции.",
"data": {
"api_key": "API-ключ",
"api_endpoint": "URL конечной точки API",
"model": "Модель ИИ", "model": "Модель ИИ",
"temperature": "Креативность ответа (0-2)", "temperature": "Креативность ответа (0-2)",
"max_tokens": "Максимальная длина ответа (1-100000)", "max_tokens": "Максимальная длина ответа (1-100000)",
@@ -130,6 +139,14 @@
"max_tokens": { "max_tokens": {
"name": "Максимум токенов", "name": "Максимум токенов",
"description": "Максимальная длина ответа (1-100000 токенов)" "description": "Максимальная длина ответа (1-100000 токенов)"
},
"structured_output": {
"name": "Структурированный вывод",
"description": "Включить режим структурированного JSON-вывода. При включении ИИ будет отвечать валидным JSON, соответствующим указанной схеме."
},
"json_schema": {
"name": "JSON Schema",
"description": "JSON-схема, определяющая структуру ожидаемого ответа. Обязательна при включении structured_output."
} }
} }
}, },
@@ -65,9 +65,18 @@
"options": { "options": {
"step": { "step": {
"init": { "init": {
"title": "Ажурирајте подешавања инстанце", "title": "Изаберите провајдера",
"description": "Измените подешавања за ову AI асистент инстанцу.", "description": "Изаберите AI провајдера за ову инстанцу. Интеграција ће се поново учитати након чувања измена.",
"data": { "data": {
"api_provider": "API провајдер"
}
},
"settings": {
"title": "Подешавања везе и модела",
"description": "Конфигуришите API акредитиве и параметре модела. Промене ће ступити на снагу након поновног учитавања интеграције.",
"data": {
"api_key": "API кључ",
"api_endpoint": "URL API крајње тачке",
"model": "AI модел", "model": "AI модел",
"temperature": "Креативност одговора (0-2)", "temperature": "Креативност одговора (0-2)",
"max_tokens": "Максимална дужина одговора (1-100000)", "max_tokens": "Максимална дужина одговора (1-100000)",
@@ -121,6 +130,14 @@
"max_tokens": { "max_tokens": {
"name": "Максимални токени", "name": "Максимални токени",
"description": "Максимална дужина одговора (1-100000 токена)" "description": "Максимална дужина одговора (1-100000 токена)"
},
"structured_output": {
"name": "Структурисани излаз",
"description": "Омогући JSON структурисани излаз. Када је омогућено, AI ће одговарати валидним JSON-ом који одговара датој шеми."
},
"json_schema": {
"name": "JSON шема",
"description": "JSON шема која дефинише структуру очекиваног одговора. Обавезна када је structured_output омогућен."
} }
} }
}, },
@@ -65,9 +65,18 @@
"options": { "options": {
"step": { "step": {
"init": { "init": {
"title": "更新实例设置", "title": "选择提供者",
"description": "修改此AI助手实例的设置。", "description": "选择此实例的AI提供者。保存更改后集成将重新加载。",
"data": { "data": {
"api_provider": "API提供者"
}
},
"settings": {
"title": "连接和模型设置",
"description": "配置API凭据和模型参数。更改将在集成重新加载后生效。",
"data": {
"api_key": "API密钥",
"api_endpoint": "API端点URL",
"model": "AI模型", "model": "AI模型",
"temperature": "响应创造力(0-2", "temperature": "响应创造力(0-2",
"max_tokens": "最大响应长度(1-100000", "max_tokens": "最大响应长度(1-100000",
@@ -121,6 +130,14 @@
"max_tokens": { "max_tokens": {
"name": "最大标记数", "name": "最大标记数",
"description": "响应的最大长度(1-100000个标记)" "description": "响应的最大长度(1-100000个标记)"
},
"structured_output": {
"name": "结构化输出",
"description": "启用JSON结构化输出模式。启用后,AI将以符合提供的模式的有效JSON进行响应。"
},
"json_schema": {
"name": "JSON模式",
"description": "定义预期响应结构的JSON模式。启用structured_output时必需。"
} }
} }
}, },