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

V0.0.7 #24

Merged
merged 9 commits into from
Nov 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions custom_components/extended_openai_conversation/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""The OpenAI Conversation integration."""
from __future__ import annotations

from functools import partial
import logging
from typing import Literal
import json
Expand Down Expand Up @@ -38,6 +37,7 @@
CONF_TOP_P,
CONF_MAX_FUNCTION_CALLS_PER_CONVERSATION,
CONF_FUNCTIONS,
CONF_BASE_URL,
DEFAULT_CHAT_MODEL,
DEFAULT_MAX_TOKENS,
DEFAULT_PROMPT,
Expand Down Expand Up @@ -66,6 +66,7 @@
ScrapeFunctionExecutor,
CompositeFunctionExecutor,
convert_to_template,
validate_authentication,
)


Expand All @@ -82,12 +83,10 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up OpenAI Conversation from a config entry."""

try:
await hass.async_add_executor_job(
partial(
openai.Engine.list,
api_key=entry.data[CONF_API_KEY],
request_timeout=10,
)
await validate_authentication(
hass=hass,
api_key=entry.data[CONF_API_KEY],
base_url=entry.data.get(CONF_BASE_URL),
)
except error.AuthenticationError as err:
_LOGGER.error("Invalid API key: %s", err)
Expand Down Expand Up @@ -263,6 +262,7 @@ async def query(
_LOGGER.info("Prompt for %s: %s", model, messages)

response = await openai.ChatCompletion.acreate(
api_base=self.entry.data.get(CONF_BASE_URL),
api_key=self.entry.data[CONF_API_KEY],
model=model,
messages=messages,
Expand Down
18 changes: 14 additions & 4 deletions custom_components/extended_openai_conversation/config_flow.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
"""Config flow for OpenAI Conversation integration."""
from __future__ import annotations

from functools import partial
import logging
import types
import yaml
from types import MappingProxyType
from typing import Any

import openai
from openai import error
import voluptuous as vol

Expand All @@ -23,6 +21,8 @@
AttributeSelector,
)

from .helpers import validate_authentication

from .const import (
CONF_CHAT_MODEL,
CONF_MAX_TOKENS,
Expand All @@ -31,13 +31,15 @@
CONF_TOP_P,
CONF_MAX_FUNCTION_CALLS_PER_CONVERSATION,
CONF_FUNCTIONS,
CONF_BASE_URL,
DEFAULT_CHAT_MODEL,
DEFAULT_MAX_TOKENS,
DEFAULT_PROMPT,
DEFAULT_TEMPERATURE,
DEFAULT_TOP_P,
DEFAULT_MAX_FUNCTION_CALLS_PER_CONVERSATION,
DEFAULT_CONF_FUNCTIONS,
DEFAULT_CONF_BASE_URL,
DOMAIN,
DEFAULT_NAME,
)
Expand All @@ -48,6 +50,7 @@
{
vol.Optional(CONF_NAME): str,
vol.Required(CONF_API_KEY): str,
vol.Optional(CONF_BASE_URL, default=DEFAULT_CONF_BASE_URL): str,
}
)

Expand All @@ -71,8 +74,15 @@ async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> None:

Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user.
"""
openai.api_key = data[CONF_API_KEY]
await hass.async_add_executor_job(partial(openai.Engine.list, request_timeout=10))
api_key = data[CONF_API_KEY]
base_url = data.get(CONF_BASE_URL)

if base_url == DEFAULT_CONF_BASE_URL:
# Do not set base_url if using OpenAI for case of OpenAI's base_url change
base_url = None
data.pop(CONF_BASE_URL)

await validate_authentication(hass=hass, api_key=api_key, base_url=base_url)


class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
Expand Down
4 changes: 3 additions & 1 deletion custom_components/extended_openai_conversation/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
"description": "The entity_id retrieved from available devices. It must start with domain, followed by dot character.",
}
},
"required": ["entity_id"]
"required": ["entity_id"],
},
},
"required": ["domain", "service", "service_data"],
Expand All @@ -75,3 +75,5 @@
"function": {"type": "native", "name": "execute_service"},
}
]
CONF_BASE_URL = "base_url"
DEFAULT_CONF_BASE_URL = "https://api.openai.com/v1"
21 changes: 20 additions & 1 deletion custom_components/extended_openai_conversation/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import time
from bs4 import BeautifulSoup
from typing import Any
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from openai.error import AuthenticationError

from homeassistant.components import automation, rest, scrape
from homeassistant.components.automation.config import _async_validate_config_item
Expand Down Expand Up @@ -40,7 +42,7 @@
NativeNotFound,
)

from .const import DOMAIN, EVENT_AUTOMATION_REGISTERED
from .const import DOMAIN, EVENT_AUTOMATION_REGISTERED, DEFAULT_CONF_BASE_URL


_LOGGER = logging.getLogger(__name__)
Expand Down Expand Up @@ -97,6 +99,23 @@ def _get_rest_data(hass, rest_config, arguments):
return rest.create_rest_data_from_config(hass, rest_config)


async def validate_authentication(
hass: HomeAssistant, api_key: str, base_url: str
) -> None:
if not base_url:
base_url = DEFAULT_CONF_BASE_URL
session = async_get_clientsession(hass)
response = await session.get(
f"{base_url}/models",
headers={"Authorization": f"Bearer {api_key}"},
timeout=10,
)
if response.status == 401:
raise AuthenticationError()

response.raise_for_status()


class FunctionExecutor(ABC):
def __init__(self) -> None:
"""initialize function executor"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,5 @@
"requirements": [
"openai==0.27.2"
],
"version": "0.0.6"
"version": "0.0.7"
}
3 changes: 2 additions & 1 deletion custom_components/extended_openai_conversation/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
"user": {
"data": {
"name": "[%key:common::config_flow::data::name%]",
"api_key": "[%key:common::config_flow::data::api_key%]"
"api_key": "[%key:common::config_flow::data::api_key%]",
"base_url": "[%key:common::config_flow::data::base_url%]"
}
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
"user": {
"data": {
"name": "Name",
"api_key": "API Key"
"api_key": "API Key",
"base_url": "Base Url"
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
"user": {
"data": {
"name": "Name",
"api_key": "API Key"
"api_key": "API Key",
"base_url": "Base Url"
}
}
}
Expand Down