Skip to content

Commit

Permalink
Google Generative AI: Handle response with empty parts in generate_co…
Browse files Browse the repository at this point in the history
…ntent (home-assistant#117908)

Handle response with empty parts in generate_content
  • Loading branch information
tronikos authored May 22, 2024
1 parent 5b1677c commit e413048
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@ async def generate_content(call: ServiceCall) -> ServiceResponse:
) as err:
raise HomeAssistantError(f"Error generating content: {err}") from err

if not response.parts:
raise HomeAssistantError("Error generating content")

return {"text": response.text}

hass.services.async_register(
Expand Down
24 changes: 24 additions & 0 deletions tests/components/google_generative_ai_conversation/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,30 @@ async def test_generate_content_service_error(
)


@pytest.mark.usefixtures("mock_init_component")
async def test_generate_content_response_has_empty_parts(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test generate content service handles response with empty parts."""
with (
patch("google.generativeai.GenerativeModel") as mock_model,
pytest.raises(HomeAssistantError, match="Error generating content"),
):
mock_response = MagicMock()
mock_response.parts = []
mock_model.return_value.generate_content_async = AsyncMock(
return_value=mock_response
)
await hass.services.async_call(
"google_generative_ai_conversation",
"generate_content",
{"prompt": "write a story about an epic fail"},
blocking=True,
return_response=True,
)


async def test_generate_content_service_with_image_not_allowed_path(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
Expand Down

0 comments on commit e413048

Please sign in to comment.