recallix-haystack 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- recallix_haystack-0.1.0/.gitignore +69 -0
- recallix_haystack-0.1.0/PKG-INFO +82 -0
- recallix_haystack-0.1.0/README.md +69 -0
- recallix_haystack-0.1.0/pyproject.toml +21 -0
- recallix_haystack-0.1.0/src/recallix_haystack/__init__.py +5 -0
- recallix_haystack-0.1.0/src/recallix_haystack/memory_store.py +143 -0
- recallix_haystack-0.1.0/tests/test_memory_store.py +102 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
|
2
|
+
|
|
3
|
+
# dependencies
|
|
4
|
+
/node_modules
|
|
5
|
+
/.pnp
|
|
6
|
+
.pnp.*
|
|
7
|
+
.yarn/*
|
|
8
|
+
!.yarn/patches
|
|
9
|
+
!.yarn/plugins
|
|
10
|
+
!.yarn/releases
|
|
11
|
+
!.yarn/versions
|
|
12
|
+
|
|
13
|
+
# testing
|
|
14
|
+
/coverage
|
|
15
|
+
|
|
16
|
+
# next.js
|
|
17
|
+
/.next/
|
|
18
|
+
/out/
|
|
19
|
+
|
|
20
|
+
# production
|
|
21
|
+
/build
|
|
22
|
+
|
|
23
|
+
# misc
|
|
24
|
+
.DS_Store
|
|
25
|
+
*.pem
|
|
26
|
+
|
|
27
|
+
# debug
|
|
28
|
+
npm-debug.log*
|
|
29
|
+
yarn-debug.log*
|
|
30
|
+
yarn-error.log*
|
|
31
|
+
.pnpm-debug.log*
|
|
32
|
+
|
|
33
|
+
# env files (can opt-in for committing if needed)
|
|
34
|
+
.env*
|
|
35
|
+
|
|
36
|
+
# vercel
|
|
37
|
+
.vercel
|
|
38
|
+
|
|
39
|
+
# typescript
|
|
40
|
+
*.tsbuildinfo
|
|
41
|
+
next-env.d.ts
|
|
42
|
+
|
|
43
|
+
# python
|
|
44
|
+
venv/
|
|
45
|
+
.venv/
|
|
46
|
+
__pycache__/
|
|
47
|
+
*.pyc
|
|
48
|
+
*.pyo
|
|
49
|
+
*.pyd
|
|
50
|
+
.Python
|
|
51
|
+
env/
|
|
52
|
+
pip-log.txt
|
|
53
|
+
pip-delete-this-directory.txt
|
|
54
|
+
|
|
55
|
+
# Databases and Local Models
|
|
56
|
+
*.db
|
|
57
|
+
*.sqlite
|
|
58
|
+
*.sqlite3
|
|
59
|
+
backend/models/
|
|
60
|
+
storage/
|
|
61
|
+
|
|
62
|
+
# Build and IDE
|
|
63
|
+
**/build/
|
|
64
|
+
.vscode/
|
|
65
|
+
.idea/
|
|
66
|
+
*.log
|
|
67
|
+
|
|
68
|
+
# Phase 6 training data (some sources are CC BY-SA; never committed)
|
|
69
|
+
.phase6_data/
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: recallix-haystack
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Recallix as the memory store of Haystack agents: self-hosted, no LLM calls for memory, says when it has no record.
|
|
5
|
+
Project-URL: Homepage, https://github.com/AyishikD/Recallix/tree/main/integrations/haystack
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Requires-Dist: haystack-ai>=2.18
|
|
9
|
+
Requires-Dist: recallix>=0.2.5
|
|
10
|
+
Provides-Extra: agent
|
|
11
|
+
Requires-Dist: haystack-experimental>=0.15; extra == 'agent'
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# recallix-haystack: Recallix memory for Haystack agents
|
|
15
|
+
|
|
16
|
+
`RecallixMemoryStore` plugs a self-hosted [Recallix](https://github.com/AyishikD/Recallix) server into
|
|
17
|
+
[Haystack](https://haystack.deepset.ai) agents as their memory store. It follows Haystack's `MemoryStore`
|
|
18
|
+
protocol (`haystack_experimental.memory_stores`), so it drops in where the Mem0 store goes.
|
|
19
|
+
|
|
20
|
+
* **No LLM calls for memory.** Storing and searching use Recallix's local models.
|
|
21
|
+
* **Honest search.** When nothing answers the query, `search_memories` returns no memories instead of
|
|
22
|
+
near-misses for the model to guess from.
|
|
23
|
+
* **Re-adding is safe.** The agent hands over the whole conversation after each run; Recallix stores each
|
|
24
|
+
message once.
|
|
25
|
+
* **Your data stays on your server**, separated per user and per agent.
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install "recallix-haystack[agent]" # haystack-ai, haystack-experimental (for Agent) and the recallix SDK
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Run Recallix ([quickstart](../../docs/quickstart.md)) and create a key with role `service` (it acts for each user):
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
python -m backend.tools.keys create --user my-haystack-app --role service
|
|
37
|
+
export RECALLIX_API_KEY=rx_...
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Use with a Haystack agent
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from haystack.components.generators.chat import OpenAIChatGenerator
|
|
44
|
+
from haystack.dataclasses import ChatMessage
|
|
45
|
+
from haystack_experimental.components.agents import Agent
|
|
46
|
+
from recallix_haystack import RecallixMemoryStore
|
|
47
|
+
|
|
48
|
+
store = RecallixMemoryStore(base_url="http://localhost:8000", mode="balanced") # or "cautious" / "helpful"
|
|
49
|
+
agent = Agent(chat_generator=OpenAIChatGenerator(), memory_store=store, system_prompt="You are a helpful assistant.")
|
|
50
|
+
|
|
51
|
+
agent.run(messages=[ChatMessage.from_user("I moved to Pune in March.")], memory_store_kwargs={"user_id": "alice"})
|
|
52
|
+
agent.run(messages=[ChatMessage.from_user("Where did I move?")], memory_store_kwargs={"user_id": "alice"})
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Or on its own: `store.add_memories(messages=[...], user_id="alice")`,
|
|
56
|
+
`store.search_memories(query="Where did I move?", user_id="alice", top_k=5)`.
|
|
57
|
+
|
|
58
|
+
| Parameter | Default | What it does |
|
|
59
|
+
|---|---|---|
|
|
60
|
+
| `api_key` | `RECALLIX_API_KEY` | A Haystack `Secret`. Role `service`; `delete_all_memories` needs role `admin`. |
|
|
61
|
+
| `agent_id` | `haystack` | Recallix agent id; each agent reads back what it wrote. Can also be passed per call. |
|
|
62
|
+
| `mode` | server's `recall.mode` | `cautious` checks every answer twice; `helpful` answers more counting, ordering and "how long between" questions and adds a worked-out result first. |
|
|
63
|
+
| `store_roles` | `("user",)` | Which message roles are stored. The default stores what users said, not the model's replies. |
|
|
64
|
+
|
|
65
|
+
Notes:
|
|
66
|
+
|
|
67
|
+
* `search_memories` returns system `ChatMessage`s, like the Mem0 store; with `include_memory_metadata=True`
|
|
68
|
+
each carries Recallix's relevance, trust and receipt. Without a `query` it returns the user's most recent
|
|
69
|
+
memories.
|
|
70
|
+
* Haystack `filters` are not supported (Recallix scopes by user and agent) and are ignored with a warning.
|
|
71
|
+
* A message's original time can be given as `meta={"timestamp": <unix seconds>}`.
|
|
72
|
+
* Needs Recallix server 0.2.5 or newer.
|
|
73
|
+
* Tested with haystack-ai 2.23 + haystack-experimental 0.19 (store and Agent), and with haystack-ai 3.5 (store; the
|
|
74
|
+
experimental Agent does not yet run on Haystack 3.x, which is a Haystack-side pairing, not this package). If the
|
|
75
|
+
Agent import fails, pin `haystack-ai` to the release matching your `haystack-experimental`.
|
|
76
|
+
|
|
77
|
+
## Tests
|
|
78
|
+
|
|
79
|
+
Against a running Recallix: `RECALLIX_URL=... RECALLIX_SERVICE_KEY=rx_... [RECALLIX_ADMIN_KEY=rx_...] pytest tests`.
|
|
80
|
+
They include a real `haystack_experimental` Agent run with a scripted model.
|
|
81
|
+
|
|
82
|
+
Licence: Apache-2.0.
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# recallix-haystack: Recallix memory for Haystack agents
|
|
2
|
+
|
|
3
|
+
`RecallixMemoryStore` plugs a self-hosted [Recallix](https://github.com/AyishikD/Recallix) server into
|
|
4
|
+
[Haystack](https://haystack.deepset.ai) agents as their memory store. It follows Haystack's `MemoryStore`
|
|
5
|
+
protocol (`haystack_experimental.memory_stores`), so it drops in where the Mem0 store goes.
|
|
6
|
+
|
|
7
|
+
* **No LLM calls for memory.** Storing and searching use Recallix's local models.
|
|
8
|
+
* **Honest search.** When nothing answers the query, `search_memories` returns no memories instead of
|
|
9
|
+
near-misses for the model to guess from.
|
|
10
|
+
* **Re-adding is safe.** The agent hands over the whole conversation after each run; Recallix stores each
|
|
11
|
+
message once.
|
|
12
|
+
* **Your data stays on your server**, separated per user and per agent.
|
|
13
|
+
|
|
14
|
+
## Install
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pip install "recallix-haystack[agent]" # haystack-ai, haystack-experimental (for Agent) and the recallix SDK
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Run Recallix ([quickstart](../../docs/quickstart.md)) and create a key with role `service` (it acts for each user):
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
python -m backend.tools.keys create --user my-haystack-app --role service
|
|
24
|
+
export RECALLIX_API_KEY=rx_...
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Use with a Haystack agent
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from haystack.components.generators.chat import OpenAIChatGenerator
|
|
31
|
+
from haystack.dataclasses import ChatMessage
|
|
32
|
+
from haystack_experimental.components.agents import Agent
|
|
33
|
+
from recallix_haystack import RecallixMemoryStore
|
|
34
|
+
|
|
35
|
+
store = RecallixMemoryStore(base_url="http://localhost:8000", mode="balanced") # or "cautious" / "helpful"
|
|
36
|
+
agent = Agent(chat_generator=OpenAIChatGenerator(), memory_store=store, system_prompt="You are a helpful assistant.")
|
|
37
|
+
|
|
38
|
+
agent.run(messages=[ChatMessage.from_user("I moved to Pune in March.")], memory_store_kwargs={"user_id": "alice"})
|
|
39
|
+
agent.run(messages=[ChatMessage.from_user("Where did I move?")], memory_store_kwargs={"user_id": "alice"})
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Or on its own: `store.add_memories(messages=[...], user_id="alice")`,
|
|
43
|
+
`store.search_memories(query="Where did I move?", user_id="alice", top_k=5)`.
|
|
44
|
+
|
|
45
|
+
| Parameter | Default | What it does |
|
|
46
|
+
|---|---|---|
|
|
47
|
+
| `api_key` | `RECALLIX_API_KEY` | A Haystack `Secret`. Role `service`; `delete_all_memories` needs role `admin`. |
|
|
48
|
+
| `agent_id` | `haystack` | Recallix agent id; each agent reads back what it wrote. Can also be passed per call. |
|
|
49
|
+
| `mode` | server's `recall.mode` | `cautious` checks every answer twice; `helpful` answers more counting, ordering and "how long between" questions and adds a worked-out result first. |
|
|
50
|
+
| `store_roles` | `("user",)` | Which message roles are stored. The default stores what users said, not the model's replies. |
|
|
51
|
+
|
|
52
|
+
Notes:
|
|
53
|
+
|
|
54
|
+
* `search_memories` returns system `ChatMessage`s, like the Mem0 store; with `include_memory_metadata=True`
|
|
55
|
+
each carries Recallix's relevance, trust and receipt. Without a `query` it returns the user's most recent
|
|
56
|
+
memories.
|
|
57
|
+
* Haystack `filters` are not supported (Recallix scopes by user and agent) and are ignored with a warning.
|
|
58
|
+
* A message's original time can be given as `meta={"timestamp": <unix seconds>}`.
|
|
59
|
+
* Needs Recallix server 0.2.5 or newer.
|
|
60
|
+
* Tested with haystack-ai 2.23 + haystack-experimental 0.19 (store and Agent), and with haystack-ai 3.5 (store; the
|
|
61
|
+
experimental Agent does not yet run on Haystack 3.x, which is a Haystack-side pairing, not this package). If the
|
|
62
|
+
Agent import fails, pin `haystack-ai` to the release matching your `haystack-experimental`.
|
|
63
|
+
|
|
64
|
+
## Tests
|
|
65
|
+
|
|
66
|
+
Against a running Recallix: `RECALLIX_URL=... RECALLIX_SERVICE_KEY=rx_... [RECALLIX_ADMIN_KEY=rx_...] pytest tests`.
|
|
67
|
+
They include a real `haystack_experimental` Agent run with a scripted model.
|
|
68
|
+
|
|
69
|
+
Licence: Apache-2.0.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "recallix-haystack"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Recallix as the memory store of Haystack agents: self-hosted, no LLM calls for memory, says when it has no record."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
dependencies = ["haystack-ai>=2.18", "recallix>=0.2.5"]
|
|
13
|
+
|
|
14
|
+
[project.optional-dependencies]
|
|
15
|
+
agent = ["haystack-experimental>=0.15"]
|
|
16
|
+
|
|
17
|
+
[project.urls]
|
|
18
|
+
Homepage = "https://github.com/AyishikD/Recallix/tree/main/integrations/haystack"
|
|
19
|
+
|
|
20
|
+
[tool.hatch.build.targets.wheel]
|
|
21
|
+
packages = ["src/recallix_haystack"]
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""
|
|
2
|
+
RecallixMemoryStore: Recallix as the memory store of a Haystack agent.
|
|
3
|
+
|
|
4
|
+
from haystack_experimental.components.agents import Agent
|
|
5
|
+
from recallix_haystack import RecallixMemoryStore
|
|
6
|
+
|
|
7
|
+
store = RecallixMemoryStore() # RECALLIX_API_KEY from the environment (a "service" key)
|
|
8
|
+
agent = Agent(chat_generator=..., memory_store=store)
|
|
9
|
+
agent.run(messages=[ChatMessage.from_user("Where did I move?")], memory_store_kwargs={"user_id": "alice"})
|
|
10
|
+
|
|
11
|
+
It follows Haystack's MemoryStore protocol (haystack_experimental.memory_stores.types.MemoryStore), like the
|
|
12
|
+
Mem0 store it can replace. The agent searches before it answers and adds the conversation after; Recallix stores
|
|
13
|
+
each user message once (a message it already holds is skipped, so the agent re-adding the whole conversation is
|
|
14
|
+
safe) and, when nothing answers the query, returns no memories rather than near-misses. No LLM is called to store
|
|
15
|
+
or search memory.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import logging
|
|
20
|
+
from typing import Any, Optional, Sequence
|
|
21
|
+
|
|
22
|
+
from haystack import default_from_dict, default_to_dict
|
|
23
|
+
from haystack.dataclasses import ChatMessage
|
|
24
|
+
from haystack.utils import Secret, deserialize_secrets_inplace
|
|
25
|
+
from recallix import Memory
|
|
26
|
+
|
|
27
|
+
logger = logging.getLogger(__name__)
|
|
28
|
+
|
|
29
|
+
_COMPUTED_ID = "recallix-computed"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class RecallixMemoryStore:
|
|
33
|
+
"""
|
|
34
|
+
:param api_key: a Recallix key. Role "service" acts for each `user_id`; role "admin" is needed only for
|
|
35
|
+
`delete_all_memories`.
|
|
36
|
+
:param base_url: the Recallix API.
|
|
37
|
+
:param agent_id: Recallix agent id for memories written and read here (each agent reads back what it wrote).
|
|
38
|
+
:param mode: "cautious" | "balanced" | "helpful" for every search (None: the server's recall.mode).
|
|
39
|
+
:param store_roles: roles of the messages to store; ("user",) by default, so memories are what users said.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
def __init__(self, *, api_key: Secret = Secret.from_env_var("RECALLIX_API_KEY"),
|
|
43
|
+
base_url: str = "http://localhost:8000", agent_id: str = "haystack", mode: Optional[str] = None,
|
|
44
|
+
store_roles: Sequence[str] = ("user",), timeout: float = 30.0):
|
|
45
|
+
self.api_key = api_key
|
|
46
|
+
self.base_url = base_url
|
|
47
|
+
self.agent_id = agent_id
|
|
48
|
+
self.mode = mode
|
|
49
|
+
self.store_roles = tuple(store_roles)
|
|
50
|
+
self.timeout = timeout
|
|
51
|
+
self.memory = Memory(api_key=api_key.resolve_value(), base_url=base_url, timeout=timeout)
|
|
52
|
+
|
|
53
|
+
# ---------------------------------------------------------------- serialization
|
|
54
|
+
|
|
55
|
+
def to_dict(self) -> dict[str, Any]:
|
|
56
|
+
return default_to_dict(self, api_key=self.api_key.to_dict(), base_url=self.base_url, agent_id=self.agent_id,
|
|
57
|
+
mode=self.mode, store_roles=list(self.store_roles), timeout=self.timeout)
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def from_dict(cls, data: dict[str, Any]) -> "RecallixMemoryStore":
|
|
61
|
+
deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"])
|
|
62
|
+
return default_from_dict(cls, data)
|
|
63
|
+
|
|
64
|
+
# ---------------------------------------------------------------- writing
|
|
65
|
+
|
|
66
|
+
def add_memories(self, *, messages: list[ChatMessage], user_id: Optional[str] = None,
|
|
67
|
+
agent_id: Optional[str] = None, **kwargs: Any) -> list[dict[str, Any]]:
|
|
68
|
+
"""
|
|
69
|
+
Stores the text of each message whose role is in `store_roles`. Returns [{"memory_id", "memory", "status"}]
|
|
70
|
+
("stored", or "skipped_duplicate" for a message Recallix already holds). Other keyword arguments (run_id,
|
|
71
|
+
...) are accepted and ignored.
|
|
72
|
+
"""
|
|
73
|
+
added = []
|
|
74
|
+
for message in messages:
|
|
75
|
+
role = message.role.value
|
|
76
|
+
if role not in self.store_roles or not message.text:
|
|
77
|
+
continue
|
|
78
|
+
meta = message.meta or {}
|
|
79
|
+
ts = meta.get("timestamp") if isinstance(meta.get("timestamp"), (int, float)) else None
|
|
80
|
+
out = self.memory.store(message.text[:20000], agent_id=agent_id or self.agent_id, user_id=user_id,
|
|
81
|
+
metadata={"speaker": "User" if role == "user" else role}, timestamp=ts)
|
|
82
|
+
added.append({"memory_id": out.get("memory_id"), "memory": message.text, "status": out.get("status")})
|
|
83
|
+
return added
|
|
84
|
+
|
|
85
|
+
# ---------------------------------------------------------------- reading
|
|
86
|
+
|
|
87
|
+
def search_memories(self, *, query: Optional[str] = None, filters: Optional[dict[str, Any]] = None, top_k: int = 5,
|
|
88
|
+
user_id: Optional[str] = None, agent_id: Optional[str] = None,
|
|
89
|
+
include_memory_metadata: bool = False, **kwargs: Any) -> list[ChatMessage]:
|
|
90
|
+
"""
|
|
91
|
+
With a query: Recallix recall. Returns system ChatMessages (like the Mem0 store); none when Recallix finds
|
|
92
|
+
nothing that answers the query. In "helpful" mode a worked-out answer (days between, or the order of
|
|
93
|
+
events) comes first. Without a query: the user's most recent memories. Haystack `filters` are not
|
|
94
|
+
supported by Recallix and are ignored (logged).
|
|
95
|
+
"""
|
|
96
|
+
if filters:
|
|
97
|
+
logger.warning("RecallixMemoryStore ignores Haystack filters; scope searches with user_id and agent_id")
|
|
98
|
+
if not query:
|
|
99
|
+
rows = self.memory.timeline(limit=top_k, user_id=user_id) or [] # the most recent, oldest first
|
|
100
|
+
return [ChatMessage.from_system(text=r.get("content", ""), meta={"memory_id": str(r.get("memory_id")),
|
|
101
|
+
"timestamp": r.get("timestamp")})
|
|
102
|
+
for r in rows if r.get("content")]
|
|
103
|
+
out = self.memory.recall(query[:2000], limit=top_k, agent_id=agent_id or self.agent_id, user_id=user_id, mode=self.mode)
|
|
104
|
+
if out.get("status") != "CONSISTENT":
|
|
105
|
+
return []
|
|
106
|
+
messages = []
|
|
107
|
+
computed = out.get("computed_answer")
|
|
108
|
+
if computed and computed.get("text"):
|
|
109
|
+
meta = {"recallix_computed_answer": computed} if include_memory_metadata else {}
|
|
110
|
+
messages.append(ChatMessage.from_system(
|
|
111
|
+
text=f"Worked out from these memories: {computed['text']} ({out.get('receipt', {}).get('computed', '')})",
|
|
112
|
+
meta={"memory_id": _COMPUTED_ID, **meta}))
|
|
113
|
+
for m in (out.get("memories") or [])[:top_k]:
|
|
114
|
+
meta = {"memory_id": str(m.get("id")), "timestamp": m.get("timestamp")}
|
|
115
|
+
if include_memory_metadata:
|
|
116
|
+
meta["retrieved_memory_metadata"] = {"relevance": m.get("relevance"), "trust": m.get("trust"),
|
|
117
|
+
"receipt": m.get("receipt"), "recall_id": out.get("recall_id")}
|
|
118
|
+
messages.append(ChatMessage.from_system(text=m.get("content_resolved") or m.get("content", ""), meta=meta))
|
|
119
|
+
return messages
|
|
120
|
+
|
|
121
|
+
def search_memories_as_single_message(self, *, query: Optional[str] = None, filters: Optional[dict[str, Any]] = None,
|
|
122
|
+
top_k: int = 5, user_id: Optional[str] = None, agent_id: Optional[str] = None,
|
|
123
|
+
**kwargs: Any) -> ChatMessage:
|
|
124
|
+
found = self.search_memories(query=query, filters=filters, top_k=top_k, user_id=user_id, agent_id=agent_id)
|
|
125
|
+
if not found:
|
|
126
|
+
return ChatMessage.from_system(text="No earlier memory answers this.")
|
|
127
|
+
return ChatMessage.from_system(text="\n".join(f"- MEMORY #{i + 1}: {m.text}" for i, m in enumerate(found)))
|
|
128
|
+
|
|
129
|
+
# ---------------------------------------------------------------- deleting
|
|
130
|
+
|
|
131
|
+
def delete_memory(self, memory_id: str, user_id: Optional[str] = None, **kwargs: Any) -> None:
|
|
132
|
+
if memory_id == _COMPUTED_ID:
|
|
133
|
+
return
|
|
134
|
+
self.memory.delete(int(memory_id), user_id=user_id)
|
|
135
|
+
|
|
136
|
+
def delete_all_memories(self, *, user_id: Optional[str] = None, **kwargs: Any) -> None:
|
|
137
|
+
"""Deletes every memory of `user_id` in Recallix (all agents). Needs an admin key."""
|
|
138
|
+
if not user_id:
|
|
139
|
+
raise ValueError("delete_all_memories needs a user_id")
|
|
140
|
+
try:
|
|
141
|
+
self.memory.client.request("POST", "/internal/clear", data={"user_id": user_id})
|
|
142
|
+
except Exception as e:
|
|
143
|
+
raise RuntimeError(f"Recallix refused to delete all memories of {user_id!r} (an admin key is needed): {e}") from e
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Against a running Recallix server (skipped otherwise):
|
|
3
|
+
RECALLIX_URL=http://127.0.0.1:8000 RECALLIX_SERVICE_KEY=rx_... [RECALLIX_ADMIN_KEY=rx_...] pytest integrations/haystack/tests
|
|
4
|
+
"""
|
|
5
|
+
import os
|
|
6
|
+
import time
|
|
7
|
+
import uuid
|
|
8
|
+
|
|
9
|
+
import pytest
|
|
10
|
+
|
|
11
|
+
URL, KEY, ADMIN = os.environ.get("RECALLIX_URL"), os.environ.get("RECALLIX_SERVICE_KEY"), os.environ.get("RECALLIX_ADMIN_KEY")
|
|
12
|
+
pytestmark = pytest.mark.skipif(not (URL and KEY), reason="needs a running Recallix (RECALLIX_URL, RECALLIX_SERVICE_KEY)")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@pytest.fixture
|
|
16
|
+
def store():
|
|
17
|
+
from haystack.utils import Secret
|
|
18
|
+
from recallix_haystack import RecallixMemoryStore
|
|
19
|
+
return RecallixMemoryStore(api_key=Secret.from_env_var("RECALLIX_SERVICE_KEY"), base_url=URL)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def conversation():
|
|
23
|
+
from haystack.dataclasses import ChatMessage
|
|
24
|
+
return [ChatMessage.from_user("I moved to Pune in March for my new job.", meta={"timestamp": time.time() - 20 * 86400}),
|
|
25
|
+
ChatMessage.from_assistant("Congratulations on the move!")]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def test_follows_the_haystack_protocol_and_serializes(store):
|
|
29
|
+
from recallix_haystack import RecallixMemoryStore
|
|
30
|
+
for name in ("to_dict", "from_dict", "add_memories", "search_memories", "delete_all_memories", "delete_memory"):
|
|
31
|
+
assert callable(getattr(store, name)), name
|
|
32
|
+
d = store.to_dict()
|
|
33
|
+
assert d["init_parameters"]["api_key"]["env_vars"] == ["RECALLIX_SERVICE_KEY"] # the key itself is never written out
|
|
34
|
+
again = RecallixMemoryStore.from_dict(d)
|
|
35
|
+
assert again.base_url == store.base_url and again.agent_id == "haystack" and again.store_roles == ("user",)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_add_twice_store_once_search_finds_it(store):
|
|
39
|
+
user = f"u-{uuid.uuid4().hex[:8]}"
|
|
40
|
+
first = store.add_memories(messages=conversation(), user_id=user)
|
|
41
|
+
again = store.add_memories(messages=conversation(), user_id=user) # the agent re-adds the whole conversation
|
|
42
|
+
assert [a["status"] for a in first] == ["stored"] and [a["status"] for a in again] == ["skipped_duplicate"]
|
|
43
|
+
found = store.search_memories(query="Where did I move?", user_id=user, include_memory_metadata=True)
|
|
44
|
+
assert any("Pune" in m.text for m in found) and not any("Congratulations" in m.text for m in found)
|
|
45
|
+
assert all(m.role.value == "system" for m in found)
|
|
46
|
+
assert "receipt" in found[0].meta["retrieved_memory_metadata"]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def test_no_record_and_separation(store):
|
|
50
|
+
user = f"u-{uuid.uuid4().hex[:8]}"
|
|
51
|
+
store.add_memories(messages=conversation(), user_id=user)
|
|
52
|
+
assert store.search_memories(query="What is my sister's name?", user_id=user) == []
|
|
53
|
+
assert store.search_memories(query="Where did I move?", user_id=f"other-{user}") == []
|
|
54
|
+
assert store.search_memories(query="Where did I move?", user_id=user, agent_id="another-agent") == []
|
|
55
|
+
assert "No earlier memory" in store.search_memories_as_single_message(query="What is my sister's name?", user_id=user).text
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def test_recent_memories_without_a_query_and_delete_one(store):
|
|
59
|
+
user = f"u-{uuid.uuid4().hex[:8]}"
|
|
60
|
+
store.add_memories(messages=conversation(), user_id=user)
|
|
61
|
+
recent = store.search_memories(user_id=user)
|
|
62
|
+
assert any("Pune" in m.text for m in recent)
|
|
63
|
+
store.delete_memory(recent[-1].meta["memory_id"], user_id=user)
|
|
64
|
+
assert store.search_memories(query="Where did I move?", user_id=user) == []
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def test_delete_all_needs_an_admin_key(store):
|
|
68
|
+
user = f"u-{uuid.uuid4().hex[:8]}"
|
|
69
|
+
store.add_memories(messages=conversation(), user_id=user)
|
|
70
|
+
with pytest.raises(RuntimeError, match="admin key"):
|
|
71
|
+
store.delete_all_memories(user_id=user)
|
|
72
|
+
if ADMIN:
|
|
73
|
+
from haystack.utils import Secret
|
|
74
|
+
from recallix_haystack import RecallixMemoryStore
|
|
75
|
+
RecallixMemoryStore(api_key=Secret.from_token(ADMIN), base_url=URL).delete_all_memories(user_id=user)
|
|
76
|
+
assert store.search_memories(query="Where did I move?", user_id=user) == []
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def test_works_inside_a_haystack_agent(store):
|
|
80
|
+
"""A real haystack_experimental Agent with a scripted chat generator: memories reach the model, the turn is stored."""
|
|
81
|
+
from haystack import component
|
|
82
|
+
from haystack.dataclasses import ChatMessage
|
|
83
|
+
from haystack_experimental.components.agents import Agent
|
|
84
|
+
|
|
85
|
+
seen = {}
|
|
86
|
+
|
|
87
|
+
@component
|
|
88
|
+
class ScriptedGenerator:
|
|
89
|
+
@component.output_types(replies=list[ChatMessage])
|
|
90
|
+
def run(self, messages: list[ChatMessage], tools=None, **kwargs):
|
|
91
|
+
seen["messages"] = messages
|
|
92
|
+
return {"replies": [ChatMessage.from_assistant("You moved to Pune.")]}
|
|
93
|
+
|
|
94
|
+
user = f"u-{uuid.uuid4().hex[:8]}"
|
|
95
|
+
store.add_memories(messages=conversation(), user_id=user)
|
|
96
|
+
agent = Agent(chat_generator=ScriptedGenerator(), memory_store=store, system_prompt="You are helpful.")
|
|
97
|
+
agent.warm_up()
|
|
98
|
+
out = agent.run(messages=[ChatMessage.from_user("Where did I move?")], memory_store_kwargs={"user_id": user})
|
|
99
|
+
assert out["last_message"].text == "You moved to Pune."
|
|
100
|
+
assert any("Pune" in (m.text or "") for m in seen["messages"] if m.role.value == "system")
|
|
101
|
+
recent = store.search_memories(user_id=user)
|
|
102
|
+
assert any(m.text == "Where did I move?" for m in recent) # the agent stored the user's new message
|