-
-
Notifications
You must be signed in to change notification settings - Fork 34.3k
Gemini: Add option to specify config_entry in generate_content service #143776
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -23,6 +23,7 @@ | |
ConfigEntryError, | ||
ConfigEntryNotReady, | ||
HomeAssistantError, | ||
ServiceValidationError, | ||
) | ||
from homeassistant.helpers import config_validation as cv | ||
from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue | ||
|
@@ -35,10 +36,12 @@ | |
RECOMMENDED_CHAT_MODEL, | ||
TIMEOUT_MILLIS, | ||
) | ||
from .model_setup import get_content_config | ||
|
||
SERVICE_GENERATE_CONTENT = "generate_content" | ||
CONF_IMAGE_FILENAME = "image_filename" | ||
CONF_FILENAMES = "filenames" | ||
CONF_CONFIG_ENTRY = "config_entry" | ||
|
||
CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) | ||
PLATFORMS = (Platform.CONVERSATION,) | ||
|
@@ -64,11 +67,31 @@ | |
translation_key="deprecated_image_filename_parameter", | ||
) | ||
|
||
prompt_parts = [call.data[CONF_PROMPT]] | ||
config_entry: GoogleGenerativeAIConfigEntry | ||
if CONF_CONFIG_ENTRY in call.data: | ||
entry_id = call.data[CONF_CONFIG_ENTRY] | ||
found_entry = hass.config_entries.async_get_entry(entry_id) | ||
if found_entry is None or found_entry.domain != DOMAIN: | ||
raise ServiceValidationError( | ||
translation_domain=DOMAIN, | ||
translation_key="invalid_config_entry", | ||
translation_placeholders={"config_entry": entry_id}, | ||
) | ||
config_entry = found_entry | ||
Comment on lines
+72
to
+80
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. we should have a second check to check if its loaded |
||
else: | ||
# Deprecated in 2025.6, to remove in 2025.10 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 6 months of deprecation |
||
async_create_issue( | ||
hass, | ||
DOMAIN, | ||
"missing_config_entry_parameter", | ||
breaks_in_ha_version="2025.10.0", | ||
is_fixable=False, | ||
severity=IssueSeverity.WARNING, | ||
translation_key="missing_config_entry_parameter", | ||
) | ||
config_entry = hass.config_entries.async_loaded_entries(DOMAIN)[0] | ||
|
||
config_entry: GoogleGenerativeAIConfigEntry = ( | ||
hass.config_entries.async_loaded_entries(DOMAIN)[0] | ||
) | ||
prompt_parts = [call.data[CONF_PROMPT]] | ||
|
||
client = config_entry.runtime_data | ||
|
||
|
@@ -93,9 +116,15 @@ | |
|
||
await hass.async_add_executor_job(append_files_to_prompt) | ||
|
||
model_name = config_entry.options.get(CONF_CHAT_MODEL, RECOMMENDED_CHAT_MODEL) | ||
|
||
try: | ||
response = await client.aio.models.generate_content( | ||
model=RECOMMENDED_CHAT_MODEL, contents=prompt_parts | ||
model=model_name, | ||
# Features like tools and custom prompts are powered by | ||
# HA's Conversation infra, so we cannot use them here. | ||
config=get_content_config(config_entry), | ||
contents=prompt_parts, | ||
) | ||
except ( | ||
APIError, | ||
|
@@ -120,6 +149,7 @@ | |
schema=vol.Schema( | ||
{ | ||
vol.Required(CONF_PROMPT): cv.string, | ||
vol.Optional(CONF_CONFIG_ENTRY): cv.string, | ||
vol.Optional(CONF_IMAGE_FILENAME, default=[]): vol.All( | ||
cv.ensure_list, [cv.string] | ||
), | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
"""Generic helper functions for setting up Gemini models.""" | ||
|
||
from google.genai import Client | ||
from google.genai.types import GenerateContentConfig, HarmCategory, SafetySetting | ||
|
||
from homeassistant.config_entries import ConfigEntry | ||
|
||
from .const import ( | ||
CONF_DANGEROUS_BLOCK_THRESHOLD, | ||
CONF_HARASSMENT_BLOCK_THRESHOLD, | ||
CONF_HATE_BLOCK_THRESHOLD, | ||
CONF_MAX_TOKENS, | ||
CONF_SEXUAL_BLOCK_THRESHOLD, | ||
CONF_TEMPERATURE, | ||
CONF_TOP_K, | ||
CONF_TOP_P, | ||
RECOMMENDED_HARM_BLOCK_THRESHOLD, | ||
RECOMMENDED_MAX_TOKENS, | ||
RECOMMENDED_TEMPERATURE, | ||
RECOMMENDED_TOP_K, | ||
RECOMMENDED_TOP_P, | ||
) | ||
|
||
type GoogleGenerativeAIConfigEntry = ConfigEntry[Client] | ||
|
||
|
||
def get_content_config( | ||
entry: GoogleGenerativeAIConfigEntry, | ||
) -> GenerateContentConfig: | ||
"""Create parameters for Gemini model inputs from a config entry.""" | ||
|
||
return GenerateContentConfig( | ||
temperature=entry.options.get(CONF_TEMPERATURE, RECOMMENDED_TEMPERATURE), | ||
top_k=entry.options.get(CONF_TOP_K, RECOMMENDED_TOP_K), | ||
top_p=entry.options.get(CONF_TOP_P, RECOMMENDED_TOP_P), | ||
max_output_tokens=entry.options.get(CONF_MAX_TOKENS, RECOMMENDED_MAX_TOKENS), | ||
safety_settings=[ | ||
SafetySetting( | ||
category=HarmCategory.HARM_CATEGORY_HATE_SPEECH, | ||
threshold=entry.options.get( | ||
CONF_HATE_BLOCK_THRESHOLD, RECOMMENDED_HARM_BLOCK_THRESHOLD | ||
), | ||
), | ||
SafetySetting( | ||
category=HarmCategory.HARM_CATEGORY_HARASSMENT, | ||
threshold=entry.options.get( | ||
CONF_HARASSMENT_BLOCK_THRESHOLD, | ||
RECOMMENDED_HARM_BLOCK_THRESHOLD, | ||
), | ||
), | ||
SafetySetting( | ||
category=HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT, | ||
threshold=entry.options.get( | ||
CONF_DANGEROUS_BLOCK_THRESHOLD, RECOMMENDED_HARM_BLOCK_THRESHOLD | ||
), | ||
), | ||
SafetySetting( | ||
category=HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT, | ||
threshold=entry.options.get( | ||
CONF_SEXUAL_BLOCK_THRESHOLD, RECOMMENDED_HARM_BLOCK_THRESHOLD | ||
), | ||
), | ||
], | ||
) |
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -6,6 +6,7 @@ | |||||
from requests.exceptions import Timeout | ||||||
from syrupy.assertion import SnapshotAssertion | ||||||
|
||||||
from homeassistant.components.google_generative_ai_conversation import CONF_CHAT_MODEL | ||||||
from homeassistant.config_entries import ConfigEntryState | ||||||
from homeassistant.core import HomeAssistant | ||||||
from homeassistant.exceptions import HomeAssistantError | ||||||
|
@@ -20,6 +21,23 @@ async def test_generate_content_service_without_images( | |||||
hass: HomeAssistant, snapshot: SnapshotAssertion | ||||||
) -> None: | ||||||
"""Test generate content service.""" | ||||||
SAMPLE_MODEL = "fake-test-model" | ||||||
|
||||||
second_entry = MockConfigEntry( | ||||||
domain="google_generative_ai_conversation", | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
title="Google Generative AI Conversation", | ||||||
data={ | ||||||
"api_key": "bla", | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
}, | ||||||
options={ | ||||||
CONF_CHAT_MODEL: SAMPLE_MODEL, | ||||||
}, | ||||||
) | ||||||
second_entry.add_to_hass(hass) | ||||||
with patch("google.genai.models.AsyncModels.get"): | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Let's patch this where we use it |
||||||
await hass.config_entries.async_setup(second_entry.entry_id) | ||||||
await hass.async_block_till_done() | ||||||
|
||||||
stubbed_generated_content = ( | ||||||
"I'm thrilled to welcome you all to the release " | ||||||
"party for the latest version of Home Assistant!" | ||||||
|
@@ -36,14 +54,18 @@ async def test_generate_content_service_without_images( | |||||
response = await hass.services.async_call( | ||||||
"google_generative_ai_conversation", | ||||||
"generate_content", | ||||||
{"prompt": "Write an opening speech for a Home Assistant release party"}, | ||||||
{ | ||||||
"config_entry": second_entry.entry_id, | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
"prompt": "Write an opening speech for a Home Assistant release party", | ||||||
}, | ||||||
blocking=True, | ||||||
return_response=True, | ||||||
) | ||||||
|
||||||
assert response == { | ||||||
"text": stubbed_generated_content, | ||||||
} | ||||||
assert mock_generate.call_args.kwargs["model"] == SAMPLE_MODEL | ||||||
assert [tuple(mock_call) for mock_call in mock_generate.mock_calls] == snapshot | ||||||
|
||||||
|
||||||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
the domain can't be wrong