diff --git a/src/memos/llms/ollama.py b/src/memos/llms/ollama.py index e87734bd5..e33050fc0 100644 --- a/src/memos/llms/ollama.py +++ b/src/memos/llms/ollama.py @@ -81,11 +81,10 @@ def generate(self, messages: MessageList, **kwargs) -> Any: if isinstance(tool_calls, list) and len(tool_calls) > 0: return self.tool_call_parser(tool_calls) - str_thinking = ( - f"{response.message.thinking}" - if hasattr(response.message, "thinking") - else "" - ) + # ollama>=0.5 always defines Message.thinking (Optional, default None). + # hasattr is therefore always true and would stringify None into the reply. + thinking = response.message.thinking if hasattr(response.message, "thinking") else None + str_thinking = f"{thinking}" if thinking else "" str_response = response.message.content if self.config.remove_think_prefix: return remove_thinking_tags(str_response or "") diff --git a/tests/llms/test_ollama.py b/tests/llms/test_ollama.py index 9ed252f37..9f9d00bc9 100644 --- a/tests/llms/test_ollama.py +++ b/tests/llms/test_ollama.py @@ -3,6 +3,8 @@ from types import SimpleNamespace from unittest.mock import MagicMock +from ollama import Message + from memos.configs.llm import LLMConfigFactory, OllamaLLMConfig from memos.llms.factory import LLMFactory from memos.llms.ollama import OllamaLLM @@ -81,3 +83,29 @@ def test_ollama_llm_with_mocked_backend(self): response, "Analyzing your request...Hello! How are you? I'm here to help and smile!", ) + + def test_generate_does_not_stringify_none_thinking(self): + """ollama>=0.5 Message.thinking defaults to None, so hasattr is always true.""" + message = Message(role="assistant", content="Hello") + self.assertTrue(hasattr(message, "thinking")) + self.assertIsNone(message.thinking) + + mock_chat = MagicMock() + mock_response = MagicMock() + mock_response.model_dump_json.return_value = "{}" + mock_response.message = message + mock_chat.return_value = mock_response + + config = OllamaLLMConfig( + model_name_or_path="qwen3:0.6b", + temperature=0.8, + max_tokens=1024, + top_p=0.9, + top_k=50, + ) + ollama = OllamaLLM(config) + ollama.client.chat = mock_chat + + response = ollama.generate([{"role": "user", "content": "Hi"}]) + + self.assertEqual(response, "Hello")