Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Patch to add is_exposed for templates and scripts #224

Open
wants to merge 2 commits into
base: v1.0.4
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
54 changes: 44 additions & 10 deletions custom_components/extended_openai_conversation/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from openai import AsyncAzureOpenAI, AsyncOpenAI
import voluptuous as vol
import yaml
import asyncio

from homeassistant.components import (
automation,
Expand Down Expand Up @@ -58,6 +59,12 @@

AZURE_DOMAIN_PATTERN = r"\.openai\.azure\.com"

def is_exposed(entity_id, exposed_entities) -> bool:
return any(
exposed_entity["entity_id"] == entity_id
for exposed_entity in exposed_entities
)


def get_function_executor(value: str):
function_executor = FUNCTION_EXECUTORS.get(value)
Expand Down Expand Up @@ -132,9 +139,25 @@ async def validate_authentication(
organization: str = None,
skip_authentication=False,
) -> None:
"""
Validate the authentication with OpenAI or Azure.

Parameters:
hass (HomeAssistant): The Home Assistant instance.
api_key (str): The API key for OpenAI or Azure.
base_url (str): The base URL for the API.
api_version (str): The API version to use.
organization (str): The organization ID for the API (optional).
skip_authentication (bool): If True, skip the authentication check.

Returns:
None
"""
# If skip_authentication is True, return immediately
if skip_authentication:
return

# Determine if the base URL is for Azure or OpenAI and create the appropriate client
if is_azure(base_url):
client = AsyncAzureOpenAI(
api_key=api_key,
Expand All @@ -147,7 +170,13 @@ async def validate_authentication(
api_key=api_key, base_url=base_url, organization=organization
)

await client.models.list(timeout=10)
# Define an asynchronous function that lists models with a timeout using asyncio.to_thread
async def list_models_with_timeout():
# Use asyncio.to_thread to run the blocking call in a separate thread
return await asyncio.to_thread(client.models.list, timeout=10)

# Await the execution of the list_models_with_timeout function
await list_models_with_timeout()


class FunctionExecutor(ABC):
Expand Down Expand Up @@ -386,7 +415,7 @@ async def get_user_from_user_id(
):
user = await hass.auth.async_get_user(user_input.context.user_id)
return {'name': user.name if user and hasattr(user, 'name') else 'Unknown'}

async def get_statistics(
self,
hass: HomeAssistant,
Expand Down Expand Up @@ -439,6 +468,10 @@ async def execute(
user_input: conversation.ConversationInput,
exposed_entities,
):
script_context = {
"is_exposed": lambda e: is_exposed(e, exposed_entities),
}
run_variables = {**arguments, **script_context}
script = Script(
hass,
function["sequence"],
Expand All @@ -449,7 +482,7 @@ async def execute(
)

result = await script.async_run(
run_variables=arguments, context=user_input.context
run_variables=run_variables, context=user_input.context
)
return result.variables.get("_function_result", "Success")

Expand All @@ -474,9 +507,13 @@ async def execute(
user_input: conversation.ConversationInput,
exposed_entities,
):
template_context = {
"is_exposed": lambda e: is_exposed(e, exposed_entities),
}
variables = {**arguments, **template_context}
return function["value_template"].async_render(
arguments,
parse_result=function.get("parse_result", False),
variables,
parse_result=function.get("parse_result", False)
)


Expand Down Expand Up @@ -668,10 +705,7 @@ def __init__(self) -> None:
)

def is_exposed(self, entity_id, exposed_entities) -> bool:
return any(
exposed_entity["entity_id"] == entity_id
for exposed_entity in exposed_entities
)
return is_exposed(entity_id, exposed_entities)

def is_exposed_entity_in_query(self, query: str, exposed_entities) -> bool:
exposed_entity_ids = list(
Expand Down Expand Up @@ -711,7 +745,7 @@ async def execute(
query = function.get("query", "{{query}}")

template_arguments = {
"is_exposed": lambda e: self.is_exposed(e, exposed_entities),
"is_exposed": lambda e: is_exposed(e, exposed_entities),
"is_exposed_entity_in_query": lambda q: self.is_exposed_entity_in_query(
q, exposed_entities
),
Expand Down