From 2f8ad4d5bfa81e20aecffead7868c786c64d7870 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Fri, 13 Jun 2025 10:29:19 -0400 Subject: [PATCH] Clean up Ollama conversation entity (#146738) --- .../components/ollama/conversation.py | 43 +++++++++++-------- 1 file changed, 26 insertions(+), 17 deletions(-) diff --git a/homeassistant/components/ollama/conversation.py b/homeassistant/components/ollama/conversation.py index 928d5565081..4b4f79d4eed 100644 --- a/homeassistant/components/ollama/conversation.py +++ b/homeassistant/components/ollama/conversation.py @@ -218,9 +218,6 @@ class OllamaConversationEntity( """Call the API.""" settings = {**self.entry.data, **self.entry.options} - client = self.hass.data[DOMAIN][self.entry.entry_id] - model = settings[CONF_MODEL] - try: await chat_log.async_update_llm_data( DOMAIN, @@ -231,6 +228,31 @@ class OllamaConversationEntity( except conversation.ConverseError as err: return err.as_conversation_result() + await self._async_handle_chat_log(chat_log) + + # Create intent response + intent_response = intent.IntentResponse(language=user_input.language) + if not isinstance(chat_log.content[-1], conversation.AssistantContent): + raise TypeError( + f"Unexpected last message type: {type(chat_log.content[-1])}" + ) + intent_response.async_set_speech(chat_log.content[-1].content or "") + return conversation.ConversationResult( + response=intent_response, + conversation_id=chat_log.conversation_id, + continue_conversation=chat_log.continue_conversation, + ) + + async def _async_handle_chat_log( + self, + chat_log: conversation.ChatLog, + ) -> None: + """Generate an answer for the chat log.""" + settings = {**self.entry.data, **self.entry.options} + + client = self.hass.data[DOMAIN][self.entry.entry_id] + model = settings[CONF_MODEL] + tools: list[dict[str, Any]] | None = None if chat_log.llm_api: tools = [ @@ -269,7 +291,7 @@ class OllamaConversationEntity( [ _convert_content(content) async for content in chat_log.async_add_delta_content_stream( - user_input.agent_id, _transform_stream(response_generator) + self.entity_id, _transform_stream(response_generator) ) ] ) @@ -277,19 +299,6 @@ class OllamaConversationEntity( if not chat_log.unresponded_tool_results: break - # Create intent response - intent_response = intent.IntentResponse(language=user_input.language) - if not isinstance(chat_log.content[-1], conversation.AssistantContent): - raise TypeError( - f"Unexpected last message type: {type(chat_log.content[-1])}" - ) - intent_response.async_set_speech(chat_log.content[-1].content or "") - return conversation.ConversationResult( - response=intent_response, - conversation_id=chat_log.conversation_id, - continue_conversation=chat_log.continue_conversation, - ) - def _trim_history(self, message_history: MessageHistory, max_messages: int) -> None: """Trims excess messages from a single history.