diff --git a/homeassistant/components/ollama/entity.py b/homeassistant/components/ollama/entity.py index 2581698e185..95ddcc402c0 100644 --- a/homeassistant/components/ollama/entity.py +++ b/homeassistant/components/ollama/entity.py @@ -95,6 +95,7 @@ def _convert_content( return ollama.Message( role=MessageRole.ASSISTANT.value, content=chat_content.content, + thinking=chat_content.thinking_content, tool_calls=[ ollama.Message.ToolCall( function=ollama.Message.ToolCall.Function( @@ -103,7 +104,8 @@ def _convert_content( ) ) for tool_call in chat_content.tool_calls or () - ], + ] + or None, ) if isinstance(chat_content, conversation.UserContent): images: list[ollama.Image] = [] @@ -162,6 +164,8 @@ async def _transform_stream( ] if (content := response_message.get("content")) is not None: chunk["content"] = content + if (thinking := response_message.get("thinking")) is not None: + chunk["thinking_content"] = thinking if response_message.get("done"): new_msg = True yield chunk diff --git a/tests/components/ollama/test_conversation.py b/tests/components/ollama/test_conversation.py index 4904829a31c..4e5ddf286ba 100644 --- a/tests/components/ollama/test_conversation.py +++ b/tests/components/ollama/test_conversation.py @@ -145,6 +145,70 @@ async def test_chat_stream( assert result.response.speech["plain"]["speech"] == "test response" +async def test_thinking_content( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_init_component, +) -> None: + """Test that thinking content is retained in multi-turn conversation.""" + + entry = MockConfigEntry() + entry.add_to_hass(hass) + + subentry = next(iter(mock_config_entry.subentries.values())) + hass.config_entries.async_update_subentry( + mock_config_entry, + subentry, + data={ + **subentry.data, + ollama.CONF_THINK: True, + }, + ) + + conversation_id = "conversation_id_1234" + + with patch( + "ollama.AsyncClient.chat", + return_value=stream_generator( + { + "message": { + "role": "assistant", + "content": "test response", + "thinking": "test thinking", + }, + "done": True, + "done_reason": "stop", + }, + ), + ) as mock_chat: + await conversation.async_converse( + hass, + "test message", + conversation_id, + Context(), + agent_id=mock_config_entry.entry_id, + ) + + await conversation.async_converse( + hass, + "test message 2", + conversation_id, + Context(), + agent_id=mock_config_entry.entry_id, + ) + + assert mock_chat.call_count == 2 + assert mock_chat.call_args.kwargs["messages"][1:] == [ + Message(role="user", content="test message"), + Message( + role="assistant", + content="test response", + thinking="test thinking", + ), + Message(role="user", content="test message 2"), + ] + + async def test_template_variables( hass: HomeAssistant, mock_config_entry: MockConfigEntry ) -> None: