Skip to content

Your lightweight open-source personal agent.

Merge branch 'main' into pr-1810

Xubin Ren60c29702cc25
diff --cc nanobot/agent/memory.py
index add014bb3,e7eac8843..8cc68bce9
--- a/nanobot/agent/memory.py
+++ b/nanobot/agent/memory.py
@@@ -108,64 -124,56 +124,70 @@@ class MemoryStore
{current_memory or "(empty)"}
## Conversation to Process
- {chr(10).join(lines)}"""
+ {self._format_messages(messages)}"""
+
+ chat_messages = [
+ {"role": "system", "content": "You are a memory consolidation agent. Call the save_memory tool with your consolidation of the conversation."},
+ {"role": "user", "content": prompt},
+ ]
try:
- response = await provider.chat(
- messages=[
- {"role": "system", "content": "You are a memory consolidation agent. Call the save_memory tool with your consolidation of the conversation."},
- {"role": "user", "content": prompt},
- ],
+ forced = {"type": "function", "function": {"name": "save_memory"}}
+ response = await provider.chat_with_retry(
+ messages=chat_messages,
tools=_SAVE_MEMORY_TOOL,
model=model,
+ tool_choice=forced,
)
+ if response.finish_reason == "error" and _is_tool_choice_unsupported(
+ response.content
+ ):
+ logger.warning("Forced tool_choice unsupported, retrying with auto")
+ response = await provider.chat_with_retry(
+ messages=chat_messages,
+ tools=_SAVE_MEMORY_TOOL,
+ model=model,
+ tool_choice="auto",
+ )
+
if not response.has_tool_calls:
- logger.warning("Memory consolidation: LLM did not call save_memory, skipping")
+ logger.warning(
+ "Memory consolidation: LLM did not call save_memory "
+ "(finish_reason={}, content_len={}, content_preview={})",
+ response.finish_reason,
+ len(response.content or ""),
+ (response.content or "")[:200],
+ )
return False
- args = response.tool_calls[0].arguments
- # Some providers return arguments as a JSON string instead of dict
- if isinstance(args, str):
- args = json.loads(args)
- # Some providers return arguments as a list (handle edge case)
- if isinstance(args, list):
- if args and isinstance(args[0], dict):
- args = args[0]
- else:
- logger.warning("Memory consolidation: unexpected arguments as empty or non-dict list")
- return False
- if not isinstance(args, dict):
- logger.warning("Memory consolidation: unexpected arguments type {}", type(args).__name__)
+ args = _normalize_save_memory_args(response.tool_calls[0].arguments)
+ if args is None:
+ logger.warning("Memory consolidation: unexpected save_memory arguments")
return False
- if entry := args.get("history_entry"):
- self.append_history(_ensure_text(entry))
- if update := args.get("memory_update"):
- update = _ensure_text(update)
- if update != current_memory:
- self.write_long_term(update)
+ if "history_entry" not in args or "memory_update" not in args:
+ logger.warning("Memory consolidation: save_memory payload missing required fields")
+ return False
+
+ entry = args["history_entry"]
+ update = args["memory_update"]
+
+ if entry is None or update is None:
+ logger.warning("Memory consolidation: save_memory payload contains null required fields")
+ return False
+
- if not isinstance(entry, str):
- entry = json.dumps(entry, ensure_ascii=False)
- if not isinstance(update, str):
- update = json.dumps(update, ensure_ascii=False)
-
- entry = entry.strip()
++ entry = _ensure_text(entry).strip()
+ if not entry:
+ logger.warning("Memory consolidation: history_entry is empty after normalization")
+ return False
+
+ self.append_history(entry)
++ update = _ensure_text(update)
+ if update != current_memory:
+ self.write_long_term(update)
- session.last_consolidated = 0 if archive_all else len(session.messages) - keep_count
- logger.info("Memory consolidation done: {} messages, last_consolidated={}", len(session.messages), session.last_consolidated)
+ logger.info("Memory consolidation done for {} messages", len(messages))
return True
except Exception:
logger.exception("Memory consolidation failed")
diff --cc tests/test_memory_consolidation_types.py
index 4ba1ecd0b,f1280fcc7..a7c872e5f
--- a/tests/test_memory_consolidation_types.py
+++ b/tests/test_memory_consolidation_types.py
@@@ -219,94 -242,106 +240,194 @@@ class TestMemoryConsolidationTypeHandli
assert result is False
+ @pytest.mark.asyncio
+ async def test_missing_history_entry_returns_false_without_writing(self, tmp_path: Path) -> None:
+ """Do not persist partial results when required fields are missing."""
+ store = MemoryStore(tmp_path)
+ provider = AsyncMock()
- provider.chat = AsyncMock(
++ provider.chat_with_retry = AsyncMock(
+ return_value=LLMResponse(
+ content=None,
+ tool_calls=[
+ ToolCallRequest(
+ id="call_1",
+ name="save_memory",
+ arguments={"memory_update": "# Memory\nOnly memory update"},
+ )
+ ],
+ )
+ )
- session = _make_session(message_count=60)
++ messages = _make_messages(message_count=60)
+
- result = await store.consolidate(session, provider, "test-model", memory_window=50)
++ result = await store.consolidate(messages, provider, "test-model")
+
+ assert result is False
+ assert not store.history_file.exists()
+ assert not store.memory_file.exists()
- assert session.last_consolidated == 0
+
+ @pytest.mark.asyncio
+ async def test_missing_memory_update_returns_false_without_writing(self, tmp_path: Path) -> None:
+ """Do not append history if memory_update is missing."""
+ store = MemoryStore(tmp_path)
+ provider = AsyncMock()
- provider.chat = AsyncMock(
++ provider.chat_with_retry = AsyncMock(
+ return_value=LLMResponse(
+ content=None,
+ tool_calls=[
+ ToolCallRequest(
+ id="call_1",
+ name="save_memory",
+ arguments={"history_entry": "[2026-01-01] Partial output."},
+ )
+ ],
+ )
+ )
- session = _make_session(message_count=60)
++ messages = _make_messages(message_count=60)
+
- result = await store.consolidate(session, provider, "test-model", memory_window=50)
++ result = await store.consolidate(messages, provider, "test-model")
+
+ assert result is False
+ assert not store.history_file.exists()
+ assert not store.memory_file.exists()
- assert session.last_consolidated == 0
+
+ @pytest.mark.asyncio
+ async def test_null_required_field_returns_false_without_writing(self, tmp_path: Path) -> None:
+ """Null required fields should be rejected before persistence."""
+ store = MemoryStore(tmp_path)
+ provider = AsyncMock()
- provider.chat = AsyncMock(
++ provider.chat_with_retry = AsyncMock(
+ return_value=_make_tool_response(
+ history_entry=None,
+ memory_update="# Memory\nUser likes testing.",
+ )
+ )
- session = _make_session(message_count=60)
++ messages = _make_messages(message_count=60)
+
- result = await store.consolidate(session, provider, "test-model", memory_window=50)
++ result = await store.consolidate(messages, provider, "test-model")
+
+ assert result is False
+ assert not store.history_file.exists()
+ assert not store.memory_file.exists()
- assert session.last_consolidated == 0
+
+ @pytest.mark.asyncio
+ async def test_empty_history_entry_returns_false_without_writing(self, tmp_path: Path) -> None:
+ """Empty history entries should be rejected to avoid blank archival records."""
+ store = MemoryStore(tmp_path)
+ provider = AsyncMock()
- provider.chat = AsyncMock(
++ provider.chat_with_retry = AsyncMock(
+ return_value=_make_tool_response(
+ history_entry=" ",
+ memory_update="# Memory\nUser likes testing.",
+ )
+ )
- session = _make_session(message_count=60)
++ messages = _make_messages(message_count=60)
+
- result = await store.consolidate(session, provider, "test-model", memory_window=50)
++ result = await store.consolidate(messages, provider, "test-model")
+
+ assert result is False
+ assert not store.history_file.exists()
+ assert not store.memory_file.exists()
- assert session.last_consolidated == 0
++
+ @pytest.mark.asyncio
+ async def test_retries_transient_error_then_succeeds(self, tmp_path: Path, monkeypatch) -> None:
+ store = MemoryStore(tmp_path)
+ provider = ScriptedProvider([
+ LLMResponse(content="503 server error", finish_reason="error"),
+ _make_tool_response(
+ history_entry="[2026-01-01] User discussed testing.",
+ memory_update="# Memory\nUser likes testing.",
+ ),
+ ])
+ messages = _make_messages(message_count=60)
+ delays: list[int] = []
+
+ async def _fake_sleep(delay: int) -> None:
+ delays.append(delay)
+
+ monkeypatch.setattr("nanobot.providers.base.asyncio.sleep", _fake_sleep)
+
+ result = await store.consolidate(messages, provider, "test-model")
+
+ assert result is True
+ assert provider.calls == 2
+ assert delays == [1]
+
+ @pytest.mark.asyncio
+ async def test_consolidation_delegates_to_provider_defaults(self, tmp_path: Path) -> None:
+ """Consolidation no longer passes generation params — the provider owns them."""
+ store = MemoryStore(tmp_path)
+ provider = AsyncMock()
+ provider.chat_with_retry = AsyncMock(
+ return_value=_make_tool_response(
+ history_entry="[2026-01-01] User discussed testing.",
+ memory_update="# Memory\nUser likes testing.",
+ )
+ )
+ messages = _make_messages(message_count=60)
+
+ result = await store.consolidate(messages, provider, "test-model")
+
+ assert result is True
+ provider.chat_with_retry.assert_awaited_once()
+ _, kwargs = provider.chat_with_retry.await_args
+ assert kwargs["model"] == "test-model"
+ assert "temperature" not in kwargs
+ assert "max_tokens" not in kwargs
+ assert "reasoning_effort" not in kwargs
+
+ @pytest.mark.asyncio
+ async def test_tool_choice_fallback_on_unsupported_error(self, tmp_path: Path) -> None:
+ """Forced tool_choice rejected by provider -> retry with auto and succeed."""
+ store = MemoryStore(tmp_path)
+ error_resp = LLMResponse(
+ content="Error calling LLM: litellm.BadRequestError: "
+ "The tool_choice parameter does not support being set to required or object",
+ finish_reason="error",
+ tool_calls=[],
+ )
+ ok_resp = _make_tool_response(
+ history_entry="[2026-01-01] Fallback worked.",
+ memory_update="# Memory\nFallback OK.",
+ )
+
+ call_log: list[dict] = []
+
+ async def _tracking_chat(**kwargs):
+ call_log.append(kwargs)
+ return error_resp if len(call_log) == 1 else ok_resp
+
+ provider = AsyncMock()
+ provider.chat_with_retry = AsyncMock(side_effect=_tracking_chat)
+ messages = _make_messages(message_count=60)
+
+ result = await store.consolidate(messages, provider, "test-model")
+
+ assert result is True
+ assert len(call_log) == 2
+ assert isinstance(call_log[0]["tool_choice"], dict)
+ assert call_log[1]["tool_choice"] == "auto"
+ assert "Fallback worked." in store.history_file.read_text()
+
+ @pytest.mark.asyncio
+ async def test_tool_choice_fallback_auto_no_tool_call(self, tmp_path: Path) -> None:
+ """Forced rejected, auto retry also produces no tool call -> return False."""
+ store = MemoryStore(tmp_path)
+ error_resp = LLMResponse(
+ content="Error: tool_choice must be none or auto",
+ finish_reason="error",
+ tool_calls=[],
+ )
+ no_tool_resp = LLMResponse(
+ content="Here is a summary.",
+ finish_reason="stop",
+ tool_calls=[],
+ )
+
+ provider = AsyncMock()
+ provider.chat_with_retry = AsyncMock(side_effect=[error_resp, no_tool_resp])
+ messages = _make_messages(message_count=60)
+
+ result = await store.consolidate(messages, provider, "test-model")
+
+ assert result is False
+ assert not store.history_file.exists()