fleet-memory/hindsight-integrations/llamaindex-memory/tests/test_memory.py
DK09876 2d787c4ffd
feat: add LlamaIndex integration (#672)
* feat: add LlamaIndex integration for Hindsight

Add hindsight-llamaindex package providing persistent memory tools for
LlamaIndex agents via the native BaseToolSpec pattern. Includes retain,
recall, and reflect tools, a convenience factory, global config, full
test suite, docs page, blog post, and integrations.json entry.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: address PR review feedback for llamaindex integration

- Fix ReActAgent API: from_tools() → constructor, chat() → await run()
- Add create_bank step to all quickstart examples
- Add production patterns section to docs (tags, error handling, bank lifecycle)
- Add memory scoping recommendation to README
- Add when-not-to-use section to blog post
- Add LlamaIndex compatibility tests (agent acceptance, FunctionTool.call)
- Fix self-hosted auth wording in cookbook notebook

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: use async client methods and asyncio.run() for runnable examples

- Use await client.acreate_bank() instead of sync create_bank() to
  avoid "event loop already running" errors in notebooks and async contexts
- Wrap plain Python examples in async def main() + asyncio.run(main())
  so they are copy-paste runnable as scripts
- Add Jupyter notebook tip to docs showing top-level await pattern
- Bank lifecycle example in docs now uses async acreate_bank

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: add async tool methods to avoid event loop conflicts

HindsightToolSpec now provides both sync and async tool implementations
using LlamaIndex's (sync_fn, async_fn) tuple pattern in spec_functions.
Async agents (ReActAgent, etc.) use aretain/arecall/areflect natively,
avoiding the "Timeout context manager should be used inside a task"
error that occurred when sync _run_async() was called from within an
active event loop.

- Add aretain_memory, arecall_memory, areflect_on_memory async methods
- Extract shared kwargs builders (_retain_kwargs, _recall_kwargs, etc.)
- spec_functions now uses tuples: [("retain_memory", "aretain_memory"), ...]
- Tests verify tools have both sync fn and async fn set
- Notebook verified end-to-end with nbclient against local Hindsight

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* chore: remove blog post from integration PR

The blog post will be pulled in separately from its own PR.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Address PR review: add context label, document_id auto-gen, bank mission, graceful errors

- Add `retain_context` param (default: "llamaindex") as source label on retain ops
- Auto-generate `document_id` as `{session_id}-{timestamp_ms}` when not provided
- Add `retain_async` param (default: True) for non-blocking retain processing
- Add `mission` param for automatic bank creation/management on first use
- Change error handling from raising HindsightError to graceful log + return message
- Add per-operation timeout constants in _client.py
- Add `context` and `mission` fields to config.py and configure()
- Update docs: document as standalone package (not LlamaHub), new params, patterns
- Tests: 51 passing (up from 34), covering all new features

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Restructure to LlamaIndex namespace packages + add BaseMemory implementation

Tools package (llama-index-tools-hindsight):
- Restructured from hindsight_llamaindex/ to llama_index/tools/hindsight/
- Import: from llama_index.tools.hindsight import HindsightToolSpec
- Follows PEP 420 implicit namespace package convention
- Removed retain_async param (client.retain() doesn't support async_processing)

Memory package (llama-index-memory-hindsight):
- New package: llama_index/memory/hindsight/
- HindsightMemory(BaseMemory) for automatic memory
- put() auto-retains user/assistant messages to Hindsight
- get(input) auto-recalls relevant memories, prepends as system message
- Graceful error handling, bank mission management, document_id generation
- 28 unit tests passing

Both packages follow LlamaIndex community conventions for future LlamaHub submission.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-30 10:43:35 +02:00

348 lines
12 KiB
Python

"""Unit tests for Hindsight LlamaIndex memory."""
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from llama_index.core.llms import ChatMessage, MessageRole
from llama_index.memory.hindsight import HindsightMemory
def _mock_client():
"""Create a mock Hindsight client."""
client = MagicMock()
client.retain = MagicMock()
client.recall = MagicMock()
client.create_bank = MagicMock()
client.aretain = AsyncMock()
client.arecall = AsyncMock()
client.acreate_bank = AsyncMock()
return client
def _mock_recall_response(texts: list[str]):
response = MagicMock()
results = []
for t in texts:
r = MagicMock()
r.text = t
results.append(r)
response.results = results
return response
class TestHindsightMemoryCreation:
def test_from_client(self):
client = _mock_client()
memory = HindsightMemory.from_client(
client=client,
bank_id="test-bank",
)
assert memory.bank_id == "test-bank"
assert memory.context == "llamaindex"
assert memory.budget == "mid"
def test_from_client_with_options(self):
client = _mock_client()
memory = HindsightMemory.from_client(
client=client,
bank_id="test-bank",
mission="Track preferences",
context="my-app",
budget="high",
tags=["source:chat"],
)
assert memory.bank_id == "test-bank"
assert memory.context == "my-app"
assert memory.budget == "high"
assert memory.tags == ["source:chat"]
def test_from_url(self):
with patch("llama_index.memory.hindsight.base.Hindsight") as mock_cls:
mock_cls.return_value = _mock_client()
memory = HindsightMemory.from_url(
hindsight_api_url="http://localhost:8888",
bank_id="test-bank",
)
assert memory.bank_id == "test-bank"
mock_cls.assert_called_once_with(
base_url="http://localhost:8888", timeout=30.0
)
def test_from_defaults_raises(self):
with pytest.raises(NotImplementedError):
HindsightMemory.from_defaults()
def test_class_name(self):
assert HindsightMemory.class_name() == "HindsightMemory"
class TestPut:
def test_put_user_message_retains(self):
client = _mock_client()
memory = HindsightMemory.from_client(client=client, bank_id="test")
msg = ChatMessage(role=MessageRole.USER, content="I like Python")
memory.put(msg)
client.retain.assert_called_once()
kwargs = client.retain.call_args[1]
assert kwargs["bank_id"] == "test"
assert kwargs["content"] == "I like Python"
assert kwargs["context"] == "llamaindex"
assert kwargs["metadata"]["role"] == "user"
def test_put_assistant_message_retains(self):
client = _mock_client()
memory = HindsightMemory.from_client(client=client, bank_id="test")
msg = ChatMessage(role=MessageRole.ASSISTANT, content="Noted!")
memory.put(msg)
client.retain.assert_called_once()
kwargs = client.retain.call_args[1]
assert kwargs["metadata"]["role"] == "assistant"
def test_put_system_message_skipped(self):
client = _mock_client()
memory = HindsightMemory.from_client(client=client, bank_id="test")
msg = ChatMessage(role=MessageRole.SYSTEM, content="You are helpful")
memory.put(msg)
client.retain.assert_not_called()
def test_put_empty_content_skipped(self):
client = _mock_client()
memory = HindsightMemory.from_client(client=client, bank_id="test")
msg = ChatMessage(role=MessageRole.USER, content=" ")
memory.put(msg)
client.retain.assert_not_called()
def test_put_adds_to_local_history(self):
client = _mock_client()
memory = HindsightMemory.from_client(client=client, bank_id="test")
msg = ChatMessage(role=MessageRole.USER, content="hello")
memory.put(msg)
assert len(memory.get_all()) == 1
assert memory.get_all()[0].content == "hello"
def test_put_trims_to_limit(self):
client = _mock_client()
memory = HindsightMemory.from_client(
client=client, bank_id="test", chat_history_limit=3
)
for i in range(5):
memory.put(ChatMessage(role=MessageRole.USER, content=f"msg-{i}"))
history = memory.get_all()
assert len(history) == 3
assert history[0].content == "msg-2"
assert history[2].content == "msg-4"
def test_put_tags_passed(self):
client = _mock_client()
memory = HindsightMemory.from_client(
client=client, bank_id="test", tags=["source:chat"]
)
memory.put(ChatMessage(role=MessageRole.USER, content="hello"))
kwargs = client.retain.call_args[1]
assert kwargs["tags"] == ["source:chat"]
def test_put_retain_failure_is_graceful(self):
client = _mock_client()
client.retain.side_effect = RuntimeError("connection refused")
memory = HindsightMemory.from_client(client=client, bank_id="test")
# Should not raise
memory.put(ChatMessage(role=MessageRole.USER, content="hello"))
# Message still in local history
assert len(memory.get_all()) == 1
def test_put_generates_document_id(self):
client = _mock_client()
memory = HindsightMemory.from_client(client=client, bank_id="test")
memory.put(ChatMessage(role=MessageRole.USER, content="hello"))
kwargs = client.retain.call_args[1]
doc_id = kwargs["document_id"]
parts = doc_id.rsplit("-", 1)
assert len(parts) == 2
assert parts[1].isdigit()
class TestGet:
def test_get_without_input_returns_history(self):
client = _mock_client()
memory = HindsightMemory.from_client(client=client, bank_id="test")
memory.put(ChatMessage(role=MessageRole.USER, content="hello"))
memory.put(ChatMessage(role=MessageRole.ASSISTANT, content="hi there"))
messages = memory.get()
assert len(messages) == 2
client.recall.assert_not_called()
def test_get_with_input_recalls_memories(self):
client = _mock_client()
client.recall.return_value = _mock_recall_response(
["User likes Python", "User prefers dark mode"]
)
memory = HindsightMemory.from_client(client=client, bank_id="test")
memory.put(ChatMessage(role=MessageRole.USER, content="hello"))
messages = memory.get(input="What are my preferences?")
# Should have system message + chat history
assert len(messages) == 2
assert messages[0].role == MessageRole.SYSTEM
assert "User likes Python" in str(messages[0].content)
assert "User prefers dark mode" in str(messages[0].content)
assert messages[1].content == "hello"
def test_get_with_input_no_memories(self):
client = _mock_client()
client.recall.return_value = _mock_recall_response([])
memory = HindsightMemory.from_client(client=client, bank_id="test")
memory.put(ChatMessage(role=MessageRole.USER, content="hello"))
messages = memory.get(input="anything")
# No system message when no memories found
assert len(messages) == 1
assert messages[0].content == "hello"
def test_get_recall_passes_params(self):
client = _mock_client()
client.recall.return_value = _mock_recall_response(["fact"])
memory = HindsightMemory.from_client(
client=client,
bank_id="test",
budget="high",
max_tokens=2048,
recall_tags=["scope:user"],
recall_tags_match="all",
)
memory.get(input="query")
kwargs = client.recall.call_args[1]
assert kwargs["budget"] == "high"
assert kwargs["max_tokens"] == 2048
assert kwargs["tags"] == ["scope:user"]
assert kwargs["tags_match"] == "all"
def test_get_recall_failure_is_graceful(self):
client = _mock_client()
client.recall.side_effect = RuntimeError("timeout")
memory = HindsightMemory.from_client(client=client, bank_id="test")
memory.put(ChatMessage(role=MessageRole.USER, content="hello"))
# Should not raise, returns history without memories
messages = memory.get(input="query")
assert len(messages) == 1
def test_get_custom_system_prompt(self):
client = _mock_client()
client.recall.return_value = _mock_recall_response(["fact1"])
memory = HindsightMemory.from_client(
client=client,
bank_id="test",
system_prompt="MEMORIES: {memories}",
)
messages = memory.get(input="query")
assert str(messages[0].content) == "MEMORIES: - fact1"
class TestSet:
def test_set_replaces_history(self):
client = _mock_client()
memory = HindsightMemory.from_client(client=client, bank_id="test")
memory.put(ChatMessage(role=MessageRole.USER, content="old"))
new_messages = [
ChatMessage(role=MessageRole.USER, content="new1"),
ChatMessage(role=MessageRole.ASSISTANT, content="new2"),
]
memory.set(new_messages)
history = memory.get_all()
assert len(history) == 2
assert history[0].content == "new1"
def test_set_retains_only_new_messages(self):
client = _mock_client()
memory = HindsightMemory.from_client(client=client, bank_id="test")
memory.put(ChatMessage(role=MessageRole.USER, content="existing"))
client.retain.reset_mock()
# Set with 3 messages (1 existing + 2 new)
messages = [
ChatMessage(role=MessageRole.USER, content="existing"),
ChatMessage(role=MessageRole.USER, content="new1"),
ChatMessage(role=MessageRole.ASSISTANT, content="new2"),
]
memory.set(messages)
# Should retain only the 2 new messages
assert client.retain.call_count == 2
class TestReset:
def test_reset_clears_local_history(self):
client = _mock_client()
memory = HindsightMemory.from_client(client=client, bank_id="test")
memory.put(ChatMessage(role=MessageRole.USER, content="hello"))
assert len(memory.get_all()) == 1
memory.reset()
assert len(memory.get_all()) == 0
class TestBankMission:
def test_creates_bank_with_mission_on_put(self):
client = _mock_client()
memory = HindsightMemory.from_client(
client=client, bank_id="test", mission="Track preferences"
)
memory.put(ChatMessage(role=MessageRole.USER, content="hello"))
client.create_bank.assert_called_once_with(
bank_id="test",
name="test",
mission="Track preferences",
)
def test_creates_bank_with_mission_on_get(self):
client = _mock_client()
client.recall.return_value = _mock_recall_response([])
memory = HindsightMemory.from_client(
client=client, bank_id="test", mission="Track preferences"
)
memory.get(input="query")
client.create_bank.assert_called_once()
def test_bank_creation_idempotent(self):
client = _mock_client()
client.recall.return_value = _mock_recall_response([])
memory = HindsightMemory.from_client(
client=client, bank_id="test", mission="mission"
)
memory.put(ChatMessage(role=MessageRole.USER, content="hello"))
memory.get(input="query")
assert client.create_bank.call_count == 1
def test_no_bank_creation_without_mission(self):
client = _mock_client()
memory = HindsightMemory.from_client(client=client, bank_id="test")
memory.put(ChatMessage(role=MessageRole.USER, content="hello"))
client.create_bank.assert_not_called()
def test_bank_creation_failure_is_graceful(self):
client = _mock_client()
client.create_bank.side_effect = RuntimeError("already exists")
memory = HindsightMemory.from_client(
client=client, bank_id="test", mission="mission"
)
# Should not raise
memory.put(ChatMessage(role=MessageRole.USER, content="hello"))
client.retain.assert_called_once()