recallix-haystack 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,5 @@
1
+ """Recallix memory for Haystack agents."""
2
+ from .memory_store import RecallixMemoryStore
3
+
4
+ __all__ = ["RecallixMemoryStore"]
5
+ __version__ = "0.1.0"
@@ -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,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,5 @@
1
+ recallix_haystack/__init__.py,sha256=VCvKwislPCLxTJq0Mf9OyKZV81bd1Pw6P2VRGEL_PyA,146
2
+ recallix_haystack/memory_store.py,sha256=M109rvoV3BkRdLZj6UN-fjRd6vL6OSwAfoNd5fNR0z8,8260
3
+ recallix_haystack-0.1.0.dist-info/METADATA,sha256=MjwHbM8gR_ycdqYiAUadNeVEqQXU0cJPYLLSYPBXjgc,4157
4
+ recallix_haystack-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
5
+ recallix_haystack-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any