1 """The OpenAI Conversation integration."""
3 from __future__
import annotations
6 import voluptuous
as vol
19 ServiceValidationError,
25 from .const
import DOMAIN, LOGGER
27 SERVICE_GENERATE_IMAGE =
"generate_image"
28 PLATFORMS = (Platform.CONVERSATION,)
29 CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)
31 type OpenAIConfigEntry = ConfigEntry[openai.AsyncClient]
34 async
def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
35 """Set up OpenAI Conversation."""
37 async
def render_image(call: ServiceCall) -> ServiceResponse:
38 """Render an image with dall-e."""
39 entry_id = call.data[
"config_entry"]
40 entry = hass.config_entries.async_get_entry(entry_id)
42 if entry
is None or entry.domain != DOMAIN:
44 translation_domain=DOMAIN,
45 translation_key=
"invalid_config_entry",
46 translation_placeholders={
"config_entry": entry_id},
49 client: openai.AsyncClient = entry.runtime_data
52 response = await client.images.generate(
54 prompt=call.data[
"prompt"],
55 size=call.data[
"size"],
56 quality=call.data[
"quality"],
57 style=call.data[
"style"],
58 response_format=
"url",
61 except openai.OpenAIError
as err:
64 return response.data[0].model_dump(exclude={
"b64_json"})
66 hass.services.async_register(
68 SERVICE_GENERATE_IMAGE,
72 vol.Required(
"config_entry"): selector.ConfigEntrySelector(
74 "integration": DOMAIN,
77 vol.Required(
"prompt"): cv.string,
78 vol.Optional(
"size", default=
"1024x1024"): vol.In(
79 (
"1024x1024",
"1024x1792",
"1792x1024")
81 vol.Optional(
"quality", default=
"standard"): vol.In((
"standard",
"hd")),
82 vol.Optional(
"style", default=
"vivid"): vol.In((
"vivid",
"natural")),
85 supports_response=SupportsResponse.ONLY,
91 """Set up OpenAI Conversation from a config entry."""
92 client = openai.AsyncOpenAI(
93 api_key=entry.data[CONF_API_KEY],
98 _ = await hass.async_add_executor_job(client.platform_headers)
101 await hass.async_add_executor_job(client.with_options(timeout=10.0).models.list)
102 except openai.AuthenticationError
as err:
103 LOGGER.error(
"Invalid API key: %s", err)
105 except openai.OpenAIError
as err:
108 entry.runtime_data = client
110 await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
117 return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
bool async_setup(HomeAssistant hass, ConfigType config)
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
bool async_setup_entry(HomeAssistant hass, OpenAIConfigEntry entry)
httpx.AsyncClient get_async_client(HomeAssistant hass, bool verify_ssl=True)