From 157362f225ed21167e8a699ce3db54e18778fa53 Mon Sep 17 00:00:00 2001 From: Denis Shulyaka Date: Mon, 30 Mar 2026 17:27:39 +0300 Subject: [PATCH] Fix OpenAI image generation with reasoning (#166827) --- .../components/openai_conversation/entity.py | 8 +++++++- .../components/openai_conversation/test_ai_task.py | 13 ++++++++++--- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/openai_conversation/entity.py b/homeassistant/components/openai_conversation/entity.py index 399da7ce4d8..50a4f6f8f7e 100644 --- a/homeassistant/components/openai_conversation/entity.py +++ b/homeassistant/components/openai_conversation/entity.py @@ -346,7 +346,9 @@ async def _transform_stream( # noqa: C901 - This is complex, but better to have id=event.item.id, tool_name="web_search_call", tool_args={ - "action": event.item.action.to_dict(), + "action": event.item.action.to_dict() + if event.item.action + else None, }, external=True, ) @@ -360,6 +362,10 @@ async def _transform_stream( # noqa: C901 - This is complex, but better to have } last_role = "tool_result" elif isinstance(event.item, ImageGenerationCall): + if last_summary_index is not None: + yield {"role": "assistant"} + last_role = "assistant" + last_summary_index = None yield {"native": event.item} last_summary_index = -1 # Trigger new assistant message on next turn elif isinstance(event, ResponseTextDeltaEvent): diff --git a/tests/components/openai_conversation/test_ai_task.py b/tests/components/openai_conversation/test_ai_task.py index 783efcee40c..990c4322a04 100644 --- a/tests/components/openai_conversation/test_ai_task.py +++ b/tests/components/openai_conversation/test_ai_task.py @@ -14,7 +14,7 @@ from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity_registry as er, issue_registry as ir, selector -from . import create_image_gen_call_item, create_message_item +from . import create_image_gen_call_item, create_message_item, create_reasoning_item from tests.common import MockConfigEntry @@ -247,8 +247,15 @@ async def test_generate_image( # Mock the OpenAI response stream mock_create_stream.return_value = [ - create_image_gen_call_item(id="ig_A", output_index=0), - create_message_item(id="msg_A", text="", output_index=1), + ( + *create_reasoning_item( + id="rs_A", + output_index=0, + reasoning_summary=[["The user asks me to generate an image"]], + ), + *create_image_gen_call_item(id="ig_A", output_index=1), + *create_message_item(id="msg_A", text="", output_index=2), + ) ] with patch.object(