recallic-haystack 0.2.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.
- recallic_haystack-0.2.0/.gitignore +69 -0
- recallic_haystack-0.2.0/PKG-INFO +86 -0
- recallic_haystack-0.2.0/README.md +72 -0
- recallic_haystack-0.2.0/pyproject.toml +21 -0
- recallic_haystack-0.2.0/src/recallic_haystack/__init__.py +5 -0
- recallic_haystack-0.2.0/src/recallic_haystack/memory_store.py +146 -0
- recallic_haystack-0.2.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,86 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: recallic-haystack
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Recallic 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/Recallic/Recallic/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: recallic>=0.3.0
|
|
10
|
+
Provides-Extra: agent
|
|
11
|
+
Requires-Dist: haystack-ai<2.24; extra == 'agent'
|
|
12
|
+
Requires-Dist: haystack-experimental>=0.15; extra == 'agent'
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# recallic-haystack: Recallic memory for Haystack agents
|
|
16
|
+
|
|
17
|
+
*Formerly `recallix-haystack` (0.1.x); renamed with the project, nothing else changed.*
|
|
18
|
+
|
|
19
|
+
`RecallicMemoryStore` plugs a self-hosted [Recallic](https://github.com/Recallic/Recallic) server into
|
|
20
|
+
[Haystack](https://haystack.deepset.ai) agents as their memory store. It follows Haystack's `MemoryStore`
|
|
21
|
+
protocol (`haystack_experimental.memory_stores`), so it drops in where the Mem0 store goes.
|
|
22
|
+
|
|
23
|
+
* **No LLM calls for memory.** Storing and searching use Recallic's local models.
|
|
24
|
+
* **Honest search.** When nothing answers the query, `search_memories` returns no memories instead of
|
|
25
|
+
near-misses for the model to guess from.
|
|
26
|
+
* **Re-adding is safe.** The agent hands over the whole conversation after each run; Recallic stores each
|
|
27
|
+
message once.
|
|
28
|
+
* **Your data stays on your server**, separated per user and per agent.
|
|
29
|
+
|
|
30
|
+
## Install
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install "recallic-haystack[agent]" # haystack-ai, haystack-experimental (for Agent) and the recallic SDK
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Run Recallic ([quickstart](../../docs/quickstart.md)) and create a key with role `service` (it acts for each user):
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
python -m backend.tools.keys create --user my-haystack-app --role service
|
|
40
|
+
export RECALLIC_API_KEY=rx_...
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Use with a Haystack agent
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from haystack.components.generators.chat import OpenAIChatGenerator
|
|
47
|
+
from haystack.dataclasses import ChatMessage
|
|
48
|
+
from haystack_experimental.components.agents import Agent
|
|
49
|
+
from recallic_haystack import RecallicMemoryStore
|
|
50
|
+
|
|
51
|
+
store = RecallicMemoryStore(base_url="http://localhost:8000", mode="balanced") # or "cautious" / "helpful"
|
|
52
|
+
agent = Agent(chat_generator=OpenAIChatGenerator(), memory_store=store, system_prompt="You are a helpful assistant.")
|
|
53
|
+
|
|
54
|
+
agent.run(messages=[ChatMessage.from_user("I moved to Pune in March.")], memory_store_kwargs={"user_id": "alice"})
|
|
55
|
+
agent.run(messages=[ChatMessage.from_user("Where did I move?")], memory_store_kwargs={"user_id": "alice"})
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Or on its own: `store.add_memories(messages=[...], user_id="alice")`,
|
|
59
|
+
`store.search_memories(query="Where did I move?", user_id="alice", top_k=5)`.
|
|
60
|
+
|
|
61
|
+
| Parameter | Default | What it does |
|
|
62
|
+
|---|---|---|
|
|
63
|
+
| `api_key` | `RECALLIC_API_KEY` | A Haystack `Secret`. Role `service`; `delete_all_memories` needs role `admin`. |
|
|
64
|
+
| `agent_id` | `haystack` | Recallic agent id; each agent reads back what it wrote. Can also be passed per call. |
|
|
65
|
+
| `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. |
|
|
66
|
+
| `store_roles` | `("user",)` | Which message roles are stored. The default stores what users said, not the model's replies. |
|
|
67
|
+
|
|
68
|
+
Notes:
|
|
69
|
+
|
|
70
|
+
* `search_memories` returns system `ChatMessage`s, like the Mem0 store; with `include_memory_metadata=True`
|
|
71
|
+
each carries Recallic's relevance, trust and receipt. Without a `query` it returns the user's most recent
|
|
72
|
+
memories.
|
|
73
|
+
* Haystack `filters` are not supported (Recallic scopes by user and agent) and are ignored with a warning.
|
|
74
|
+
* A message's original time can be given as `meta={"timestamp": <unix seconds>}`.
|
|
75
|
+
* Needs Recallic server 0.2.5 or newer. `add_memories` sends the messages in one request per 100 on server 0.2.6
|
|
76
|
+
or newer, and one request per message before that.
|
|
77
|
+
* Tested with haystack-ai 2.23 + haystack-experimental 0.19 (store and Agent), and with haystack-ai 3.5 (store; the
|
|
78
|
+
experimental Agent does not yet run on Haystack 3.x, which is a Haystack-side pairing, not this package). If the
|
|
79
|
+
Agent import fails, pin `haystack-ai` to the release matching your `haystack-experimental`.
|
|
80
|
+
|
|
81
|
+
## Tests
|
|
82
|
+
|
|
83
|
+
Against a running Recallic: `RECALLIC_URL=... RECALLIC_SERVICE_KEY=rx_... [RECALLIC_ADMIN_KEY=rx_...] pytest tests`.
|
|
84
|
+
They include a real `haystack_experimental` Agent run with a scripted model.
|
|
85
|
+
|
|
86
|
+
Licence: Apache-2.0.
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# recallic-haystack: Recallic memory for Haystack agents
|
|
2
|
+
|
|
3
|
+
*Formerly `recallix-haystack` (0.1.x); renamed with the project, nothing else changed.*
|
|
4
|
+
|
|
5
|
+
`RecallicMemoryStore` plugs a self-hosted [Recallic](https://github.com/Recallic/Recallic) server into
|
|
6
|
+
[Haystack](https://haystack.deepset.ai) agents as their memory store. It follows Haystack's `MemoryStore`
|
|
7
|
+
protocol (`haystack_experimental.memory_stores`), so it drops in where the Mem0 store goes.
|
|
8
|
+
|
|
9
|
+
* **No LLM calls for memory.** Storing and searching use Recallic's local models.
|
|
10
|
+
* **Honest search.** When nothing answers the query, `search_memories` returns no memories instead of
|
|
11
|
+
near-misses for the model to guess from.
|
|
12
|
+
* **Re-adding is safe.** The agent hands over the whole conversation after each run; Recallic stores each
|
|
13
|
+
message once.
|
|
14
|
+
* **Your data stays on your server**, separated per user and per agent.
|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pip install "recallic-haystack[agent]" # haystack-ai, haystack-experimental (for Agent) and the recallic SDK
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Run Recallic ([quickstart](../../docs/quickstart.md)) and create a key with role `service` (it acts for each user):
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
python -m backend.tools.keys create --user my-haystack-app --role service
|
|
26
|
+
export RECALLIC_API_KEY=rx_...
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Use with a Haystack agent
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from haystack.components.generators.chat import OpenAIChatGenerator
|
|
33
|
+
from haystack.dataclasses import ChatMessage
|
|
34
|
+
from haystack_experimental.components.agents import Agent
|
|
35
|
+
from recallic_haystack import RecallicMemoryStore
|
|
36
|
+
|
|
37
|
+
store = RecallicMemoryStore(base_url="http://localhost:8000", mode="balanced") # or "cautious" / "helpful"
|
|
38
|
+
agent = Agent(chat_generator=OpenAIChatGenerator(), memory_store=store, system_prompt="You are a helpful assistant.")
|
|
39
|
+
|
|
40
|
+
agent.run(messages=[ChatMessage.from_user("I moved to Pune in March.")], memory_store_kwargs={"user_id": "alice"})
|
|
41
|
+
agent.run(messages=[ChatMessage.from_user("Where did I move?")], memory_store_kwargs={"user_id": "alice"})
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Or on its own: `store.add_memories(messages=[...], user_id="alice")`,
|
|
45
|
+
`store.search_memories(query="Where did I move?", user_id="alice", top_k=5)`.
|
|
46
|
+
|
|
47
|
+
| Parameter | Default | What it does |
|
|
48
|
+
|---|---|---|
|
|
49
|
+
| `api_key` | `RECALLIC_API_KEY` | A Haystack `Secret`. Role `service`; `delete_all_memories` needs role `admin`. |
|
|
50
|
+
| `agent_id` | `haystack` | Recallic agent id; each agent reads back what it wrote. Can also be passed per call. |
|
|
51
|
+
| `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. |
|
|
52
|
+
| `store_roles` | `("user",)` | Which message roles are stored. The default stores what users said, not the model's replies. |
|
|
53
|
+
|
|
54
|
+
Notes:
|
|
55
|
+
|
|
56
|
+
* `search_memories` returns system `ChatMessage`s, like the Mem0 store; with `include_memory_metadata=True`
|
|
57
|
+
each carries Recallic's relevance, trust and receipt. Without a `query` it returns the user's most recent
|
|
58
|
+
memories.
|
|
59
|
+
* Haystack `filters` are not supported (Recallic scopes by user and agent) and are ignored with a warning.
|
|
60
|
+
* A message's original time can be given as `meta={"timestamp": <unix seconds>}`.
|
|
61
|
+
* Needs Recallic server 0.2.5 or newer. `add_memories` sends the messages in one request per 100 on server 0.2.6
|
|
62
|
+
or newer, and one request per message before that.
|
|
63
|
+
* Tested with haystack-ai 2.23 + haystack-experimental 0.19 (store and Agent), and with haystack-ai 3.5 (store; the
|
|
64
|
+
experimental Agent does not yet run on Haystack 3.x, which is a Haystack-side pairing, not this package). If the
|
|
65
|
+
Agent import fails, pin `haystack-ai` to the release matching your `haystack-experimental`.
|
|
66
|
+
|
|
67
|
+
## Tests
|
|
68
|
+
|
|
69
|
+
Against a running Recallic: `RECALLIC_URL=... RECALLIC_SERVICE_KEY=rx_... [RECALLIC_ADMIN_KEY=rx_...] pytest tests`.
|
|
70
|
+
They include a real `haystack_experimental` Agent run with a scripted model.
|
|
71
|
+
|
|
72
|
+
Licence: Apache-2.0.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "recallic-haystack"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "Recallic 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", "recallic>=0.3.0"]
|
|
13
|
+
|
|
14
|
+
[project.optional-dependencies]
|
|
15
|
+
agent = ["haystack-experimental>=0.15", "haystack-ai<2.24"] # the experimental Agent does not run on newer haystack-ai yet
|
|
16
|
+
|
|
17
|
+
[project.urls]
|
|
18
|
+
Homepage = "https://github.com/Recallic/Recallic/tree/main/integrations/haystack"
|
|
19
|
+
|
|
20
|
+
[tool.hatch.build.targets.wheel]
|
|
21
|
+
packages = ["src/recallic_haystack"]
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""
|
|
2
|
+
RecallicMemoryStore: Recallic as the memory store of a Haystack agent.
|
|
3
|
+
|
|
4
|
+
from haystack_experimental.components.agents import Agent
|
|
5
|
+
from recallic_haystack import RecallicMemoryStore
|
|
6
|
+
|
|
7
|
+
store = RecallicMemoryStore() # RECALLIC_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; Recallic 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 recallic import Memory
|
|
26
|
+
|
|
27
|
+
logger = logging.getLogger(__name__)
|
|
28
|
+
|
|
29
|
+
_COMPUTED_ID = "recallic-computed"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class RecallicMemoryStore:
|
|
33
|
+
"""
|
|
34
|
+
:param api_key: a Recallic key. Role "service" acts for each `user_id`; role "admin" is needed only for
|
|
35
|
+
`delete_all_memories`.
|
|
36
|
+
:param base_url: the Recallic API.
|
|
37
|
+
:param agent_id: Recallic 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(["RECALLIC_API_KEY", "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]) -> "RecallicMemoryStore":
|
|
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 Recallic already holds). Other keyword arguments (run_id,
|
|
71
|
+
...) are accepted and ignored.
|
|
72
|
+
"""
|
|
73
|
+
kept = []
|
|
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
|
+
kept.append((message.text, {"content": message.text[:20000], "timestamp": ts,
|
|
81
|
+
"metadata": {"speaker": "User" if role == "user" else role}}))
|
|
82
|
+
if not kept:
|
|
83
|
+
return []
|
|
84
|
+
out = self.memory.store_many([item for _, item in kept], agent_id=agent_id or self.agent_id, user_id=user_id)
|
|
85
|
+
return [{"memory_id": r.get("memory_id"), "memory": text, "status": r.get("status")}
|
|
86
|
+
for (text, _), r in zip(kept, out["results"])]
|
|
87
|
+
|
|
88
|
+
# ---------------------------------------------------------------- reading
|
|
89
|
+
|
|
90
|
+
def search_memories(self, *, query: Optional[str] = None, filters: Optional[dict[str, Any]] = None, top_k: int = 5,
|
|
91
|
+
user_id: Optional[str] = None, agent_id: Optional[str] = None,
|
|
92
|
+
include_memory_metadata: bool = False, **kwargs: Any) -> list[ChatMessage]:
|
|
93
|
+
"""
|
|
94
|
+
With a query: Recallic recall. Returns system ChatMessages (like the Mem0 store); none when Recallic finds
|
|
95
|
+
nothing that answers the query. In "helpful" mode a worked-out answer (days between, or the order of
|
|
96
|
+
events) comes first. Without a query: the user's most recent memories. Haystack `filters` are not
|
|
97
|
+
supported by Recallic and are ignored (logged).
|
|
98
|
+
"""
|
|
99
|
+
if filters:
|
|
100
|
+
logger.warning("RecallicMemoryStore ignores Haystack filters; scope searches with user_id and agent_id")
|
|
101
|
+
if not query:
|
|
102
|
+
rows = self.memory.timeline(limit=top_k, user_id=user_id) or [] # the most recent, oldest first
|
|
103
|
+
return [ChatMessage.from_system(text=r.get("content", ""), meta={"memory_id": str(r.get("memory_id")),
|
|
104
|
+
"timestamp": r.get("timestamp")})
|
|
105
|
+
for r in rows if r.get("content")]
|
|
106
|
+
out = self.memory.recall(query[:2000], limit=top_k, agent_id=agent_id or self.agent_id, user_id=user_id, mode=self.mode)
|
|
107
|
+
if out.get("status") != "CONSISTENT":
|
|
108
|
+
return []
|
|
109
|
+
messages = []
|
|
110
|
+
computed = out.get("computed_answer")
|
|
111
|
+
if computed and computed.get("text"):
|
|
112
|
+
meta = {"recallic_computed_answer": computed} if include_memory_metadata else {}
|
|
113
|
+
messages.append(ChatMessage.from_system(
|
|
114
|
+
text=f"Worked out from these memories: {computed['text']} ({out.get('receipt', {}).get('computed', '')})",
|
|
115
|
+
meta={"memory_id": _COMPUTED_ID, **meta}))
|
|
116
|
+
for m in (out.get("memories") or [])[:top_k]:
|
|
117
|
+
meta = {"memory_id": str(m.get("id")), "timestamp": m.get("timestamp")}
|
|
118
|
+
if include_memory_metadata:
|
|
119
|
+
meta["retrieved_memory_metadata"] = {"relevance": m.get("relevance"), "trust": m.get("trust"),
|
|
120
|
+
"receipt": m.get("receipt"), "recall_id": out.get("recall_id")}
|
|
121
|
+
messages.append(ChatMessage.from_system(text=m.get("content_resolved") or m.get("content", ""), meta=meta))
|
|
122
|
+
return messages
|
|
123
|
+
|
|
124
|
+
def search_memories_as_single_message(self, *, query: Optional[str] = None, filters: Optional[dict[str, Any]] = None,
|
|
125
|
+
top_k: int = 5, user_id: Optional[str] = None, agent_id: Optional[str] = None,
|
|
126
|
+
**kwargs: Any) -> ChatMessage:
|
|
127
|
+
found = self.search_memories(query=query, filters=filters, top_k=top_k, user_id=user_id, agent_id=agent_id)
|
|
128
|
+
if not found:
|
|
129
|
+
return ChatMessage.from_system(text="No earlier memory answers this.")
|
|
130
|
+
return ChatMessage.from_system(text="\n".join(f"- MEMORY #{i + 1}: {m.text}" for i, m in enumerate(found)))
|
|
131
|
+
|
|
132
|
+
# ---------------------------------------------------------------- deleting
|
|
133
|
+
|
|
134
|
+
def delete_memory(self, memory_id: str, user_id: Optional[str] = None, **kwargs: Any) -> None:
|
|
135
|
+
if memory_id == _COMPUTED_ID:
|
|
136
|
+
return
|
|
137
|
+
self.memory.delete(int(memory_id), user_id=user_id)
|
|
138
|
+
|
|
139
|
+
def delete_all_memories(self, *, user_id: Optional[str] = None, **kwargs: Any) -> None:
|
|
140
|
+
"""Deletes every memory of `user_id` in Recallic (all agents). Needs an admin key."""
|
|
141
|
+
if not user_id:
|
|
142
|
+
raise ValueError("delete_all_memories needs a user_id")
|
|
143
|
+
try:
|
|
144
|
+
self.memory.client.request("POST", "/internal/clear", data={"user_id": user_id})
|
|
145
|
+
except Exception as e:
|
|
146
|
+
raise RuntimeError(f"Recallic 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 Recallic server (skipped otherwise):
|
|
3
|
+
RECALLIC_URL=http://127.0.0.1:8000 RECALLIC_SERVICE_KEY=rx_... [RECALLIC_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("RECALLIC_URL"), os.environ.get("RECALLIC_SERVICE_KEY"), os.environ.get("RECALLIC_ADMIN_KEY")
|
|
12
|
+
pytestmark = pytest.mark.skipif(not (URL and KEY), reason="needs a running Recallic (RECALLIC_URL, RECALLIC_SERVICE_KEY)")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@pytest.fixture
|
|
16
|
+
def store():
|
|
17
|
+
from haystack.utils import Secret
|
|
18
|
+
from recallic_haystack import RecallicMemoryStore
|
|
19
|
+
return RecallicMemoryStore(api_key=Secret.from_env_var("RECALLIC_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 recallic_haystack import RecallicMemoryStore
|
|
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"] == ["RECALLIC_SERVICE_KEY"] # the key itself is never written out
|
|
34
|
+
again = RecallicMemoryStore.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 recallic_haystack import RecallicMemoryStore
|
|
75
|
+
RecallicMemoryStore(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
|