recallic-adk 0.2.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
+ """Recallic memory for Google ADK agents."""
2
+ from .memory_service import RecallicMemoryService
3
+
4
+ __all__ = ["RecallicMemoryService"]
5
+ __version__ = "0.2.0"
@@ -0,0 +1,142 @@
1
+ """
2
+ RecallicMemoryService: Recallic as the memory of a Google ADK agent.
3
+
4
+ from recallic_adk import RecallicMemoryService
5
+ memory = RecallicMemoryService(api_key="rx_...") # a Recallic key with role "service"
6
+ runner = Runner(agent=agent, app_name="my_app", session_service=..., memory_service=memory)
7
+
8
+ ADK hands over sessions (add_session_to_memory) or the latest turn (add_events_to_memory); this stores each text
9
+ event in Recallic with its original time. search_memory recalls with Recallic and returns ADK MemoryEntry items.
10
+ When Recallic finds nothing that answers the query it returns no memories, so the agent is not handed
11
+ near-misses to guess from. No LLM is called to store or search memory.
12
+
13
+ Scope: Recallic user = the ADK user_id; Recallic agent = the ADK app_name, so each app reads back what it wrote.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import asyncio
18
+ from collections.abc import Mapping, Sequence
19
+ from datetime import datetime, timezone
20
+ from typing import TYPE_CHECKING, Any, Optional
21
+
22
+ from google.adk.memory.base_memory_service import BaseMemoryService, SearchMemoryResponse
23
+ from google.adk.memory.memory_entry import MemoryEntry
24
+ from google.genai import types
25
+ from recallic import Memory
26
+
27
+ if TYPE_CHECKING:
28
+ from google.adk.events.event import Event
29
+ from google.adk.sessions.session import Session
30
+
31
+
32
+ def _event_text(event: "Event") -> str:
33
+ content = getattr(event, "content", None)
34
+ parts = getattr(content, "parts", None) or []
35
+ return "\n".join(p.text for p in parts if getattr(p, "text", None) and not getattr(p, "thought", False)).strip()
36
+
37
+
38
+ def _iso(ts: Any) -> Optional[str]:
39
+ try:
40
+ return datetime.fromtimestamp(float(ts), tz=timezone.utc).isoformat()
41
+ except (TypeError, ValueError):
42
+ return None
43
+
44
+
45
+ class RecallicMemoryService(BaseMemoryService):
46
+ """
47
+ api_key: a Recallic key with role "service" (it acts for each ADK user_id).
48
+ base_url: the Recallic API.
49
+ mode: "cautious" | "balanced" | "helpful" for every search (None: the server's recall.mode).
50
+ limit: memories per search.
51
+ store_authors: which event authors to store: ("user",) by default, so memories are what users said. Pass None
52
+ to store every author, including the agent's own replies.
53
+ """
54
+
55
+ def __init__(self, api_key: str, base_url: str = "http://localhost:8000", *, mode: Optional[str] = None,
56
+ limit: int = 10, store_authors: Optional[Sequence[str]] = ("user",), timeout: float = 30.0,
57
+ client: Optional[Memory] = None):
58
+ self.memory = client or Memory(api_key=api_key, base_url=base_url, timeout=timeout)
59
+ self.mode = mode
60
+ self.limit = limit
61
+ self.store_authors = tuple(store_authors) if store_authors is not None else None
62
+
63
+ # ---------------------------------------------------------------- writing
64
+
65
+ def _store_events(self, app_name: str, user_id: str, events: Sequence["Event"],
66
+ custom_metadata: Optional[Mapping[str, object]] = None) -> None:
67
+ items = []
68
+ for event in events:
69
+ author = getattr(event, "author", None) or "user"
70
+ if self.store_authors is not None and author not in self.store_authors:
71
+ continue
72
+ text = _event_text(event)
73
+ if not text:
74
+ continue
75
+ metadata = {"speaker": "User" if author == "user" else author}
76
+ if custom_metadata:
77
+ metadata["adk"] = dict(custom_metadata)
78
+ items.append({"content": text[:20000], "metadata": metadata, "timestamp": getattr(event, "timestamp", None)})
79
+ # one request per 100 events; Recallic skips a message it already holds for this user and agent, so
80
+ # re-adding a session is safe
81
+ if items:
82
+ self.memory.store_many(items, agent_id=app_name, user_id=user_id)
83
+
84
+ async def add_session_to_memory(self, session: "Session") -> None:
85
+ await asyncio.to_thread(self._store_events, session.app_name, session.user_id, list(session.events or []))
86
+
87
+ async def add_events_to_memory(self, *, app_name: str, user_id: str, events: Sequence["Event"],
88
+ session_id: Optional[str] = None,
89
+ custom_metadata: Optional[Mapping[str, object]] = None) -> None:
90
+ await asyncio.to_thread(self._store_events, app_name, user_id, list(events), custom_metadata)
91
+
92
+ async def add_memory(self, *, app_name: str, user_id: str, memories: Sequence[MemoryEntry],
93
+ custom_metadata: Optional[Mapping[str, object]] = None) -> None:
94
+ def write():
95
+ items = []
96
+ for entry in memories:
97
+ text = "\n".join(p.text for p in (entry.content.parts or []) if getattr(p, "text", None)).strip()
98
+ if not text:
99
+ continue
100
+ ts = None
101
+ if entry.timestamp:
102
+ try:
103
+ ts = datetime.fromisoformat(entry.timestamp).timestamp()
104
+ except ValueError:
105
+ ts = None
106
+ items.append({"content": text[:20000], "timestamp": ts,
107
+ "metadata": {"speaker": entry.author or "User",
108
+ **({"adk": dict(custom_metadata)} if custom_metadata else {})}})
109
+ if items:
110
+ self.memory.store_many(items, agent_id=app_name, user_id=user_id)
111
+ await asyncio.to_thread(write)
112
+
113
+ # ---------------------------------------------------------------- reading
114
+
115
+ async def search_memory(self, *, app_name: str, user_id: str, query: str) -> SearchMemoryResponse:
116
+ out = await asyncio.to_thread(lambda: self.memory.recall(query[:2000], limit=self.limit, agent_id=app_name,
117
+ user_id=user_id, mode=self.mode))
118
+ if out.get("status") != "CONSISTENT":
119
+ return SearchMemoryResponse(memories=[]) # Recallic found nothing that answers it: no near-misses
120
+ entries = []
121
+ computed = out.get("computed_answer")
122
+ if computed and computed.get("text"):
123
+ entries.append(MemoryEntry(
124
+ id="recallic-computed", author="recallic", timestamp=None,
125
+ content=types.Content(role="user", parts=[types.Part(text=f"Worked out from the memories below: {computed['text']}"
126
+ f" ({out.get('receipt', {}).get('computed', '')})")]),
127
+ custom_metadata={"computed_answer": computed}))
128
+ for m in (out.get("memories") or [])[: self.limit]:
129
+ speaker = ((m.get("metadata") or {}).get("client") or {}).get("speaker") if isinstance(m.get("metadata"), dict) else None
130
+ entries.append(MemoryEntry(
131
+ id=str(m.get("id")),
132
+ author="user" if speaker in (None, "User") else speaker,
133
+ timestamp=_iso(m.get("timestamp")),
134
+ content=types.Content(role="user", parts=[types.Part(text=m.get("content_resolved") or m.get("content", ""))]),
135
+ custom_metadata={"relevance": m.get("relevance"), "trust": m.get("trust"),
136
+ "receipt": m.get("receipt"), "recallic_recall_id": out.get("recall_id")}))
137
+ return SearchMemoryResponse(memories=entries)
138
+
139
+ async def delete_memory(self, *, app_name: str, user_id: str, memory_id: Optional[str] = None) -> None:
140
+ if memory_id is None or memory_id == "recallic-computed":
141
+ return
142
+ await asyncio.to_thread(self.memory.delete, int(memory_id), user_id)
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.5
2
+ Name: recallic-adk
3
+ Version: 0.2.0
4
+ Summary: Recallic as the memory service of Google ADK 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/google-adk
6
+ License-Expression: Apache-2.0
7
+ Requires-Python: >=3.10
8
+ Requires-Dist: google-adk>=2.0
9
+ Requires-Dist: recallic>=0.3.0
10
+ Description-Content-Type: text/markdown
11
+
12
+ # recallic-adk: Recallic memory for Google ADK agents
13
+
14
+ *Formerly `recallix-adk` (0.1.x); renamed with the project, nothing else changed.*
15
+
16
+ `RecallicMemoryService` plugs a self-hosted [Recallic](https://github.com/Recallic/Recallic) server into
17
+ [Google's Agent Development Kit](https://google.github.io/adk-docs/) as the agent's memory service.
18
+
19
+ * **No LLM calls for memory.** Storing and searching use Recallic's local models; your agent's model is the
20
+ only one you pay for.
21
+ * **Honest search.** When Recallic finds nothing that answers the query, `search_memory` returns no memories,
22
+ so the agent is not handed near-misses to guess from.
23
+ * **Real dates.** Each event is stored with the time it happened, even when ADK hands over a session later.
24
+ * **Your data stays on your server**, separated per ADK user and per app.
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ pip install recallic-adk # brings google-adk and the recallic SDK
30
+ ```
31
+
32
+ Run Recallic ([quickstart](../../docs/quickstart.md)) and create one key with role `service`, which acts for
33
+ each of your ADK users:
34
+
35
+ ```bash
36
+ python -m backend.tools.keys create --user my-adk-app --role service
37
+ ```
38
+
39
+ ## Use
40
+
41
+ ```python
42
+ import os
43
+
44
+ from google.adk.agents import Agent
45
+ from google.adk.runners import Runner
46
+ from google.adk.sessions import InMemorySessionService
47
+ from google.adk.tools import load_memory
48
+ from recallic_adk import RecallicMemoryService
49
+
50
+ memory = RecallicMemoryService(api_key=os.environ["RECALLIC_SERVICE_KEY"],
51
+ base_url="http://localhost:8000",
52
+ mode="balanced") # or "cautious" / "helpful"
53
+ agent = Agent(name="assistant", model="gemini-2.5-flash", instruction="...", tools=[load_memory])
54
+ runner = Runner(agent=agent, app_name="my_app", session_service=InMemorySessionService(), memory_service=memory)
55
+
56
+ # after a conversation (or after each turn):
57
+ await memory.add_session_to_memory(session)
58
+ ```
59
+
60
+ | Argument | Default | What it does |
61
+ |---|---|---|
62
+ | `mode` | server's `recall.mode` | How readily search answers: `cautious` checks every answer twice; `helpful` answers more counting, ordering and "how long between" questions and adds a worked-out result as the first memory. |
63
+ | `limit` | 10 | Memories per search. |
64
+ | `store_authors` | `("user",)` | Which event authors are stored. The default stores what users said; `None` stores every author, including the agent's replies. |
65
+
66
+ What maps to what:
67
+
68
+ | ADK | Recallic |
69
+ |---|---|
70
+ | `user_id` | user (a service key acts for each user) |
71
+ | `app_name` | agent id, so each app reads back what it wrote |
72
+ | `add_session_to_memory` / `add_events_to_memory` / `add_memory` | `store`, one memory per text event, with its original time; storing a session again stores nothing twice |
73
+ | `search_memory` | `recall`; `MemoryEntry.custom_metadata` carries the relevance, trust and receipt |
74
+ | `delete_memory` | `delete`, with a deletion receipt in Recallic |
75
+
76
+ Needs Recallic server 0.2.5 or newer (for `mode` and original timestamps). A session is stored in one request per
77
+ 100 events on server 0.2.6 or newer, and one request per event before that.
78
+
79
+ ## Tests
80
+
81
+ Against a running Recallic: `RECALLIC_URL=http://127.0.0.1:8000 RECALLIC_SERVICE_KEY=rx_... pytest tests`.
82
+
83
+ Licence: Apache-2.0.
@@ -0,0 +1,5 @@
1
+ recallic_adk/__init__.py,sha256=LArCNxdSM3Q1j3iorM8cK_0O0CPLzYqhlDh2S47J4Bk,154
2
+ recallic_adk/memory_service.py,sha256=SKgvrXN8hA2k39jjd3hj2WD8yvcN2fZlYzUFAs5w-C8,7652
3
+ recallic_adk-0.2.0.dist-info/METADATA,sha256=2iaPMNHYS6zNIvT1VBMlvJK3H_n6NydfYJcz9Ramu8s,3689
4
+ recallic_adk-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
5
+ recallic_adk-0.2.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