🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
feat: add Memanto long-term agent memory (#4175)
Neel Patel2b861f69d378
diff --git a/camel/memories/__init__.py b/camel/memories/__init__.pyindex ef9ec6e28..2f6c866c3 100644--- a/camel/memories/__init__.py+++ b/camel/memories/__init__.py@@ -21,6 +21,7 @@ from .base import AgentMemory, BaseContextCreator, MemoryBlockfrom .blocks.chat_history_block import ChatHistoryBlockfrom .blocks.vectordb_block import VectorDBBlockfrom .context_creators.score_based import ScoreBasedContextCreator+from .memanto import MemantoMemoryfrom .records import ContextRecord, MemoryRecord__all__ = [@@ -35,4 +36,5 @@ __all__ = ['ChatHistoryBlock','VectorDBBlock','LongtermAgentMemory',+ 'MemantoMemory',]diff --git a/camel/memories/memanto.py b/camel/memories/memanto.pynew file mode 100644index 000000000..a64974e40--- /dev/null+++ b/camel/memories/memanto.py@@ -0,0 +1,227 @@+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========++import os+from typing import Any, Dict, List, Optional+from uuid import NAMESPACE_URL, uuid5++import httpx++from camel.memories.agent_memories import ChatHistoryMemory+from camel.memories.base import BaseContextCreator+from camel.memories.records import ContextRecord, MemoryRecord+from camel.messages import BaseMessage, FunctionCallingMessage+from camel.storages.key_value_storages.base import BaseKeyValueStorage+from camel.types import OpenAIBackendRole+++class _MemantoRESTClient:+ r"""Session-aware client for Memanto memory writes and semantic recall."""++ def __init__(self, agent_id: str, base_url: str, timeout: float) -> None:+ self._url = f"{base_url.rstrip('/')}/api/v2/agents/{agent_id}"+ self._client = httpx.Client(timeout=timeout)+ self._session_token = ""+ try:+ self._activate()+ except Exception:+ self.close()+ raise++ def _activate(self) -> None:+ response = self._client.post(f"{self._url}/activate")+ response.raise_for_status()+ self._session_token = response.json()["session_token"]++ def _request(+ self, operation: str, payload: Dict[str, Any]+ ) -> Dict[str, Any]:+ for attempt in range(2):+ response = self._client.post(+ f"{self._url}/{operation}",+ headers={"X-Session-Token": self._session_token},+ json=payload,+ )+ if response.status_code == 401 and attempt == 0:+ self._activate()+ continue+ response.raise_for_status()+ return response.json()+ raise RuntimeError("Memanto session retry exhausted")++ def remember(self, content: str, record_id: str) -> None:+ self._request(+ "remember",+ {+ "content": content,+ "type": "context",+ "tags": [f"camel-record:{record_id}"],+ },+ )++ def recall(self, query: str, limit: int) -> List[Dict[str, Any]]:+ return self._request("recall", {"query": query, "limit": limit}).get(+ "memories", []+ )++ def close(self) -> None:+ self._client.close()+++class MemantoMemory(ChatHistoryMemory):+ r"""Chat history augmented with automatic Memanto semantic memory.++ Complete conversation records remain in the chat-history storage. User+ and assistant text is also stored in Memanto. Retrieval searches Memanto+ using the latest user message and adds matching text as recalled context.+ System instructions, tool-call metadata, and attachments are kept in chat+ history; Memanto is not a lossless backup of that history.++ Clearing or rolling back this memory only changes chat history. Archived+ Memanto memories survive agent initialization and conversation resets.+ HTTP errors propagate to the caller; a failed remote write leaves the+ original records in chat history.++ Args:+ context_creator (BaseContextCreator): Creates model context.+ agent_id (Optional[str], optional): Existing Memanto agent identifier.+ Defaults to the MEMANTO_AGENT_ID environment variable.+ base_url (Optional[str], optional): Memanto server URL. Defaults to+ MEMANTO_BASE_URL or http://localhost:8000.+ storage (Optional[BaseKeyValueStorage], optional): Chat-history+ storage. Defaults to in-memory storage.+ window_size (Optional[int], optional): Recent chat-history window.+ Defaults to the complete current conversation.+ retrieve_limit (int, optional): Maximum semantic recall results,+ between 1 and 100. (default: :obj:`3`)+ timeout (float, optional): HTTP timeout in seconds.+ (default: :obj:`30.0`)+ """++ def __init__(+ self,+ context_creator: BaseContextCreator,+ agent_id: Optional[str] = None,+ base_url: Optional[str] = None,+ storage: Optional[BaseKeyValueStorage] = None,+ window_size: Optional[int] = None,+ retrieve_limit: int = 3,+ timeout: float = 30.0,+ ) -> None:+ resolved_agent_id = agent_id or os.getenv("MEMANTO_AGENT_ID")+ if not resolved_agent_id:+ raise ValueError(+ "agent_id must be provided or set via MEMANTO_AGENT_ID."+ )+ if not 1 <= retrieve_limit <= 100:+ raise ValueError("retrieve_limit must be between 1 and 100.")+ super().__init__(+ context_creator, storage, window_size, resolved_agent_id+ )+ self._memanto_agent_id = resolved_agent_id+ self._retrieve_limit = retrieve_limit+ self._client = _MemantoRESTClient(+ resolved_agent_id,+ base_url+ or os.getenv("MEMANTO_BASE_URL")+ or "http://localhost:8000",+ timeout,+ )++ def write_records(self, records: List[MemoryRecord]) -> None:+ r"""Keep complete chat records and archive conversational text."""+ super().write_records(records)+ for record in records:+ if (+ record.role_at_backend+ in {OpenAIBackendRole.USER, OpenAIBackendRole.ASSISTANT}+ and not isinstance(record.message, FunctionCallingMessage)+ and record.message.content.strip()+ ):+ self._client.remember(+ f"{record.role_at_backend.value}: "+ f"{record.message.content}",+ str(record.uuid),+ )++ def retrieve(self) -> List[ContextRecord]:+ r"""Combine recent chat history with relevant long-term memories."""+ history = super().retrieve()+ query = next(+ (+ item.memory_record.message.content+ for item in reversed(history)+ if item.memory_record.role_at_backend == OpenAIBackendRole.USER+ ),+ "",+ )+ if not query.strip():+ return history++ memories = self._client.recall(query, self._retrieve_limit)+ local_tags = {+ f"camel-record:{item.memory_record.uuid}" for item in history+ }+ recalled = []+ # Place recalled context before the conversation, so it cannot split+ # assistant tool calls from their tool responses.+ prefix = 0+ while history[prefix].memory_record.role_at_backend in {+ OpenAIBackendRole.SYSTEM,+ OpenAIBackendRole.DEVELOPER,+ }:+ prefix += 1+ timestamp = history[prefix].timestamp+ for memory in memories:+ if local_tags.intersection(memory.get("tags") or []):+ continue+ content = memory.get("content")+ if not content:+ continue+ memory_id = memory["id"]+ record = MemoryRecord(+ uuid=uuid5(+ NAMESPACE_URL,+ f"memanto:{self._memanto_agent_id}:{memory_id}",+ ),+ message=BaseMessage.make_user_message(+ role_name="Memanto memory",+ content=(+ f"Recalled memory (historical context):\n{content}"+ ),+ ),+ role_at_backend=OpenAIBackendRole.USER,+ extra_info={"memanto_id": memory_id},+ timestamp=timestamp,+ agent_id=self.agent_id or "",+ )+ recalled.append(+ ContextRecord(+ memory_record=record, score=1.0, timestamp=timestamp+ )+ )+ # Semantic recall can change content without changing message count.+ # Cached estimates for an append-only conversation are then stale.+ clear_cache = getattr(self._context_creator, "clear_cache", None)+ if callable(clear_cache):+ clear_cache()+ return history[:prefix] + recalled + history[prefix:]++ def clear(self) -> None:+ r"""Clear current chat history while retaining Memanto memories."""+ super().clear()++ def close(self) -> None:+ r"""Close the HTTP client without deleting any memories."""+ self._client.close()diff --git a/docs/mintlify/docs.json b/docs/mintlify/docs.jsonindex ed632619a..63b54a525 100644--- a/docs/mintlify/docs.json+++ b/docs/mintlify/docs.json@@ -383,6 +383,7 @@"group": "Memory","pages": ["reference/camel.memories.agent_memories",+ "reference/camel.memories.memanto","reference/camel.memories.base","reference/camel.memories.records","reference/camel.memories.blocks.chat_history_block",diff --git a/docs/mintlify/key_modules/memory.mdx b/docs/mintlify/key_modules/memory.mdxindex 26f5f0e2a..009e17c7e 100644--- a/docs/mintlify/key_modules/memory.mdx+++ b/docs/mintlify/key_modules/memory.mdx@@ -335,6 +335,64 @@ Add [Mem0](https://mem0.ai/) for cloud-based memory with automatic sync.**Use when:** you need reliable, persistent chat history in the cloud (not advanced semantic search).</Card>++<Card title="Memanto Memory" icon="warehouse">+[Memanto](https://docs.memanto.ai) provides semantic long-term memory through+`MemantoMemory`, an implementation of CAMEL's agent memory interface.+`ChatAgent` automatically archives user and assistant text and retrieves+relevant memories using the current user message.++Start a Memanto server and create an agent once:++```bash+pip install memanto+memanto serve+# In another terminal:+memanto agent create my-camel-agent+```++```python+from camel.agents import ChatAgent+from camel.memories import MemantoMemory, ScoreBasedContextCreator+from camel.types import ModelType+from camel.utils import OpenAITokenCounter++memory = MemantoMemory(+ context_creator=ScoreBasedContextCreator(+ OpenAITokenCounter(ModelType.GPT_4O_MINI), token_limit=4096,+ ),+ agent_id="my-camel-agent",+ base_url="http://localhost:8000",+ retrieve_limit=3,+)+try:+ agent = ChatAgent(+ system_message="You are a helpful assistant.",+ agent_id="my-camel-agent",+ memory=memory,+ )+ response = agent.step("I prefer concise Python examples.")+ print(response.msgs[0].content)+finally:+ memory.close()+```++Set `OPENAI_API_KEY` for the default ChatAgent model. `agent_id` and `base_url`+can also be configured through `MEMANTO_AGENT_ID` and `MEMANTO_BASE_URL`.++Complete current conversation records, including system roles, attachments,+and tool calls/results, remain in the configured chat-history storage+(in-memory by default). Memanto stores user/assistant text and returns it as+historical context; it is not a lossless backup of the conversation.++`clear()`, `ChatAgent.reset()`, and rollback operations affect current chat+history only. Archived Memanto memories remain available for later recall.+Manage deletion of archived memories in Memanto. Remote writes and retrieval+can depend on server indexing latency; current user input remains available+in local chat history immediately. HTTP errors are raised to the caller.++See the [memory reference](/reference/camel.memories.memanto).+</Card></Card><Card title="Advanced Topics" icon="star">diff --git a/docs/mintlify/reference/camel.memories.memanto.mdx b/docs/mintlify/reference/camel.memories.memanto.mdxnew file mode 100644index 000000000..11651d6c7--- /dev/null+++ b/docs/mintlify/reference/camel.memories.memanto.mdx@@ -0,0 +1,81 @@+<a id="camel.memories.memanto"></a>++# Memanto Memory++<a id="camel.memories.memanto.MemantoMemory"></a>++## MemantoMemory++```python+class MemantoMemory(ChatHistoryMemory):+```++Automatic semantic long-term memory for `ChatAgent`. Complete conversation+records use the normal chat-history storage. User and assistant text is also+archived in Memanto, and relevant memories are added as historical context+when generating model input.++**Parameters:**++- **context_creator** (`BaseContextCreator`): Context creation strategy.+- **agent_id** (`str`, optional): Existing Memanto agent ID; falls back to+ `MEMANTO_AGENT_ID`. This selects the remote archive at construction time.+- **base_url** (`str`, optional): Memanto server URL; falls back to+ `MEMANTO_BASE_URL`, then `http://localhost:8000`.+- **storage** (`BaseKeyValueStorage`, optional): Storage for current chat+ history. Defaults to in-memory storage.+- **window_size** (`int`, optional): Recent chat-history window. Defaults to+ the complete current conversation.+- **retrieve_limit** (`int`, optional): Maximum semantic recall results,+ from 1 to 100. Defaults to 3.+- **timeout** (`float`, optional): HTTP timeout in seconds. Defaults to 30.++### write_records++```python+def write_records(self, records: List[MemoryRecord]) -> None:+```++Stores complete records in chat history, then archives nonempty user and+assistant text in Memanto. System instructions, tool-call metadata, and+attachments stay in chat history. Remote text memories supplement context;+they do not provide exact conversation restoration.++HTTP failures propagate. If a remote write fails, the original records remain+in chat history. Session expiration triggers one retry with a fresh token.++### retrieve++```python+def retrieve(self) -> List[ContextRecord]:+```++Searches Memanto with the latest user message in the chat-history window and+combines matching memories with that history. Memories corresponding to+records already in the window are omitted. Recalled context is placed after+initial instructions and before conversation turns, preserving tool-call and+tool-response pairs.++Without a user message, retrieval returns chat history without a remote query.++### clear++```python+def clear(self) -> None:+```++Clears current chat history. Remote memories remain available across agent+initialization and resets; delete archived memories through Memanto itself.+Inherited rollback and tool-cleanup operations also affect chat history only.++### close++```python+def close(self) -> None:+```++Closes the HTTP client without deleting memory. Call when finished using the+memory instance.++See the [usage example](/key_modules/memory) and+[Memanto documentation](https://docs.memanto.ai).diff --git a/examples/memories/memanto_memory_example.py b/examples/memories/memanto_memory_example.pynew file mode 100644index 000000000..4da2ea9e9--- /dev/null+++ b/examples/memories/memanto_memory_example.py@@ -0,0 +1,57 @@+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========++from camel.agents import ChatAgent+from camel.memories import MemantoMemory, ScoreBasedContextCreator+from camel.types import ModelType+from camel.utils import OpenAITokenCounter+++def run_memanto_memory_example() -> None:+ r"""Use Memanto as automatic long-term memory for a ChatAgent.++ Prerequisites:+ 1. Install Memanto: ``pip install memanto``.+ 2. Start the server: ``memanto serve``.+ 3. Create an agent: ``memanto agent create my-camel-agent``.+ 4. Set OPENAI_API_KEY for the default ChatAgent model.+ """+ memory = MemantoMemory(+ context_creator=ScoreBasedContextCreator(+ token_counter=OpenAITokenCounter(ModelType.GPT_4O_MINI),+ token_limit=4096,+ ),+ agent_id="my-camel-agent",+ base_url="http://localhost:8000",+ retrieve_limit=3,+ )+ try:+ agent = ChatAgent(+ system_message="You are a helpful assistant.",+ agent_id="my-camel-agent",+ memory=memory,+ )+ response = agent.step("I prefer concise Python examples.")+ print(response.msgs[0].content)++ # Current chat history is reset; Memanto's archive remains available.+ agent.reset()+ response = agent.step("What coding examples do I prefer?")+ print(response.msgs[0].content)+ finally:+ memory.close()+++if __name__ == "__main__":+ run_memanto_memory_example()diff --git a/test/memories/test_memanto_memory.py b/test/memories/test_memanto_memory.pynew file mode 100644index 000000000..91bd06340--- /dev/null+++ b/test/memories/test_memanto_memory.py@@ -0,0 +1,284 @@+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========++import json+from unittest.mock import patch++import httpx+import pytest++from camel.agents import ChatAgent+from camel.memories import (+ MemantoMemory,+ MemoryRecord,+ ScoreBasedContextCreator,+)+from camel.messages import BaseMessage, FunctionCallingMessage+from camel.storages import InMemoryKeyValueStorage+from camel.types import ModelType, OpenAIBackendRole, RoleType+from camel.utils import OpenAITokenCounter+++def make_record(content, role=OpenAIBackendRole.USER):+ return MemoryRecord(+ message=BaseMessage.make_user_message(+ role_name="User", content=content+ ),+ role_at_backend=role,+ )+++def memanto_http():+ requests = []+ archive = [+ {"id": "old-memory", "content": "User prefers Python", "tags": []}+ ]+ responses = []++ def handle(request):+ requests.append(request)+ operation = request.url.path.rsplit("/", 1)[-1]+ if operation == "activate":+ return httpx.Response(200, json={"session_token": "test-token"})+ if responses:+ return responses.pop(0)+ payload = json.loads(request.content)+ if operation == "remember":+ memory_id = str(len(archive))+ archive.append({"id": memory_id, **payload})+ return httpx.Response(200, json={"memory_id": memory_id})+ assert operation == "recall"+ return httpx.Response(200, json={"memories": list(archive)})++ storage = InMemoryKeyValueStorage()+ creator = ScoreBasedContextCreator(+ OpenAITokenCounter(ModelType.GPT_4O_MINI), 10000+ )+ with httpx.Client(transport=httpx.MockTransport(handle)) as client:+ with patch("httpx.Client", return_value=client):+ memory = MemantoMemory(+ context_creator=creator,+ agent_id="test-agent",+ base_url="https://memanto.example/",+ storage=storage,+ )+ try:+ yield memory, storage, archive, requests, responses+ finally:+ memory.close()+++def test_agent_automatically_writes_and_recalls_without_tools(+ memanto_http, monkeypatch, tmp_path+):+ monkeypatch.chdir(tmp_path)+ memory, storage, archive, requests, _ = memanto_http+ agent = ChatAgent(+ system_message="Be helpful.",+ model=ModelType.STUB,+ memory=memory,+ agent_id="test-agent",+ )+ with patch.object(+ agent.model_backend.models[0],+ "_run",+ wraps=agent.model_backend.models[0]._run,+ ) as run:+ agent.step("Which language do I prefer?")+ messages = run.call_args.kwargs.get("messages") or run.call_args.args[0]+ assert messages[0]["role"] == "system"+ assert any(+ "Recalled memory" in m.get("content", "") and "Python" in m["content"]+ for m in messages+ )+ assert messages[-1]["content"] == "Which language do I prefer?"+ assert archive[0]["id"] == "old-memory"+ assert any(r.url.path.endswith("/remember") for r in requests)+ assert any(r.url.path.endswith("/recall") for r in requests)+ assert all(r.method == "POST" for r in requests)+ assert not agent._internal_tools+++def test_roles_and_tool_results_survive_roundtrip(memanto_http):+ memory, storage, archive, _, _ = memanto_http+ call = FunctionCallingMessage(+ role_name="Agent",+ role_type=RoleType.ASSISTANT,+ meta_dict=None,+ content="",+ func_name="weather",+ args={"city": "Paris"},+ tool_call_id="call_1",+ )+ result = FunctionCallingMessage(+ role_name="Agent",+ role_type=RoleType.ASSISTANT,+ meta_dict=None,+ content="",+ func_name="weather",+ result="Sunny, 25 C",+ tool_call_id="call_1",+ )+ records = [+ make_record("Follow policy", OpenAIBackendRole.SYSTEM),+ make_record("Weather?"),+ MemoryRecord(+ message=call, role_at_backend=OpenAIBackendRole.ASSISTANT+ ),+ MemoryRecord(+ message=result, role_at_backend=OpenAIBackendRole.FUNCTION+ ),+ ]+ memory.write_records(records)+ assert storage.load() == [r.to_dict() for r in records]+ messages, _ = memory.get_context()+ conversation = [+ m+ for m in messages+ if not m.get("content", "").startswith("Recalled memory")+ ]+ assert conversation == [r.to_openai_message() for r in records]+ assert conversation[-1]["content"] == "Sunny, 25 C"+ assert len(archive) == 2 # Existing memory and the user text only.+++def test_recall_payload_and_current_record_deduplication(memanto_http):+ memory, _, _, requests, _ = memanto_http+ record = make_record("Preferred language?")+ memory.write_record(record)+ messages, _ = memory.get_context()+ assert len(messages) == 2 # One historical memory plus current user input.+ remember = next(r for r in requests if r.url.path.endswith("/remember"))+ assert json.loads(remember.content) == {+ "content": "user: Preferred language?",+ "type": "context",+ "tags": [f"camel-record:{record.uuid}"],+ }+ assert json.loads(requests[-1].content) == {+ "query": "Preferred language?",+ "limit": 3,+ }+ assert requests[-1].headers["X-Session-Token"] == "test-token"+++def test_rollback_keeps_all_other_history_and_remote_memories(memanto_http):+ memory, storage, archive, requests, _ = memanto_http+ memory.write_records([make_record(str(i)) for i in range(150)])+ before = list(archive)+ request_count = len(requests)+ removed = memory.pop_records(1)+ assert len(storage.load()) == 149+ assert removed[0].message.content == "149"+ memory.remove_records_by_indices([0])+ assert len(storage.load()) == 148+ assert archive == before+ assert len(requests) == request_count+++def test_clear_and_new_session_preserve_long_term_memory(memanto_http):+ memory, storage, archive, requests, _ = memanto_http+ memory.write_record(make_record("My preference is Python"))+ before = list(archive)+ request_count = len(requests)+ memory.clear()+ assert storage.load() == []+ assert memory.retrieve() == []+ assert archive == before+ assert len(requests) == request_count+ memory.write_record(make_record("What was my preference?"))+ assert any(+ "My preference is Python" in r.memory_record.message.content+ for r in memory.retrieve()+ )+++def test_recall_refreshes_context_token_count(memanto_http):+ memory, _, archive, _, _ = memanto_http+ memory.write_record(make_record("Preference?"))+ messages, tokens = memory.get_context()+ memory.get_context_creator().set_cached_token_count(tokens, len(messages))+ archive[0]["content"] = "A much longer remembered preference. " * 100+ new_messages, new_tokens = memory.get_context()+ assert len(new_messages) == len(messages)+ assert new_tokens > tokens+++def test_expired_session_retries_with_new_token(memanto_http):+ memory, _, _, requests, responses = memanto_http+ memory._client._session_token = "expired"+ responses.extend(+ [httpx.Response(401), httpx.Response(200, json={"memory_id": "new"})]+ )+ memory.write_record(make_record("A fact"))+ assert [r.url.path.rsplit("/", 1)[-1] for r in requests] == [+ "activate",+ "remember",+ "activate",+ "remember",+ ]+ assert requests[1].headers["X-Session-Token"] == "expired"+ assert requests[3].headers["X-Session-Token"] == "test-token"+ assert requests[1].content == requests[3].content++[email protected]("status", [401, 500])+def test_failed_write_raises_and_keeps_local_record(memanto_http, status):+ memory, storage, _, requests, responses = memanto_http+ responses.extend([httpx.Response(status), httpx.Response(status)])+ record = make_record("Keep this record")+ with pytest.raises(httpx.HTTPStatusError):+ memory.write_record(record)+ assert storage.load() == [record.to_dict()]+ assert len(requests) == (4 if status == 401 else 2)+++def test_failed_recall_raises(memanto_http):+ memory, _, _, _, responses = memanto_http+ memory.write_record(make_record("Question"))+ responses.append(httpx.Response(500))+ with pytest.raises(httpx.HTTPStatusError):+ memory.retrieve()+++def test_invalid_configuration_fails_before_http(monkeypatch):+ monkeypatch.delenv("MEMANTO_AGENT_ID", raising=False)+ with patch("httpx.Client") as client:+ with pytest.raises(ValueError, match="agent_id"):+ MemantoMemory(context_creator=None)+ with pytest.raises(ValueError, match="retrieve_limit"):+ MemantoMemory(+ context_creator=None, agent_id="test", retrieve_limit=101+ )+ client.assert_not_called()+++def test_failed_activation_closes_client():+ with httpx.Client(+ transport=httpx.MockTransport(lambda request: httpx.Response(404))+ ) as client:+ with patch("httpx.Client", return_value=client):+ with pytest.raises(httpx.HTTPStatusError):+ MemantoMemory(context_creator=None, agent_id="missing")+ assert client.is_closed+++def test_close_preserves_memories(memanto_http):+ memory, storage, archive, _, _ = memanto_http+ memory.write_record(make_record("Keep this"))+ local = storage.load()+ remote = list(archive)+ memory.close()+ assert memory._client._client.is_closed+ assert storage.load() == local and archive == remote