hass-core/homeassistant/components/openai_conversation/config_flow.py
Paulus Schoutsen 7d641e4d3e
Add OpenAI integration (#86621)
* Add OpenAI integration

* Remove empty manifest fields

* More prompt tweaks

* Update manifest

* Update homeassistant/components/openai_conversation/config_flow.py

Co-authored-by: Franck Nijhof <git@frenck.dev>

* Address comments

* Add full integration tests

* Cripple the integration

* Test single instance

Co-authored-by: Franck Nijhof <git@frenck.dev>
2023-01-25 11:30:13 -05:00

70 lines
2.1 KiB
Python

"""Config flow for OpenAI Conversation integration."""
from __future__ import annotations
from functools import partial
import logging
from typing import Any
import openai
from openai import error
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_API_KEY
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResult
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
STEP_USER_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_API_KEY): str,
}
)
async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> None:
"""Validate the user input allows us to connect.
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))
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for OpenAI Conversation."""
VERSION = 1
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle the initial step."""
if self._async_current_entries():
return self.async_abort(reason="single_instance_allowed")
if user_input is None:
return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA
)
errors = {}
try:
await validate_input(self.hass, user_input)
except error.APIConnectionError:
errors["base"] = "cannot_connect"
except error.AuthenticationError:
errors["base"] = "invalid_auth"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
return self.async_create_entry(title="OpenAI Conversation", data=user_input)
return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
)