recallic-adk 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.
@@ -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,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,72 @@
1
+ # recallic-adk: Recallic memory for Google ADK agents
2
+
3
+ *Formerly `recallix-adk` (0.1.x); renamed with the project, nothing else changed.*
4
+
5
+ `RecallicMemoryService` plugs a self-hosted [Recallic](https://github.com/Recallic/Recallic) server into
6
+ [Google's Agent Development Kit](https://google.github.io/adk-docs/) as the agent's memory service.
7
+
8
+ * **No LLM calls for memory.** Storing and searching use Recallic's local models; your agent's model is the
9
+ only one you pay for.
10
+ * **Honest search.** When Recallic finds nothing that answers the query, `search_memory` returns no memories,
11
+ so the agent is not handed near-misses to guess from.
12
+ * **Real dates.** Each event is stored with the time it happened, even when ADK hands over a session later.
13
+ * **Your data stays on your server**, separated per ADK user and per app.
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ pip install recallic-adk # brings google-adk and the recallic SDK
19
+ ```
20
+
21
+ Run Recallic ([quickstart](../../docs/quickstart.md)) and create one key with role `service`, which acts for
22
+ each of your ADK users:
23
+
24
+ ```bash
25
+ python -m backend.tools.keys create --user my-adk-app --role service
26
+ ```
27
+
28
+ ## Use
29
+
30
+ ```python
31
+ import os
32
+
33
+ from google.adk.agents import Agent
34
+ from google.adk.runners import Runner
35
+ from google.adk.sessions import InMemorySessionService
36
+ from google.adk.tools import load_memory
37
+ from recallic_adk import RecallicMemoryService
38
+
39
+ memory = RecallicMemoryService(api_key=os.environ["RECALLIC_SERVICE_KEY"],
40
+ base_url="http://localhost:8000",
41
+ mode="balanced") # or "cautious" / "helpful"
42
+ agent = Agent(name="assistant", model="gemini-2.5-flash", instruction="...", tools=[load_memory])
43
+ runner = Runner(agent=agent, app_name="my_app", session_service=InMemorySessionService(), memory_service=memory)
44
+
45
+ # after a conversation (or after each turn):
46
+ await memory.add_session_to_memory(session)
47
+ ```
48
+
49
+ | Argument | Default | What it does |
50
+ |---|---|---|
51
+ | `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. |
52
+ | `limit` | 10 | Memories per search. |
53
+ | `store_authors` | `("user",)` | Which event authors are stored. The default stores what users said; `None` stores every author, including the agent's replies. |
54
+
55
+ What maps to what:
56
+
57
+ | ADK | Recallic |
58
+ |---|---|
59
+ | `user_id` | user (a service key acts for each user) |
60
+ | `app_name` | agent id, so each app reads back what it wrote |
61
+ | `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 |
62
+ | `search_memory` | `recall`; `MemoryEntry.custom_metadata` carries the relevance, trust and receipt |
63
+ | `delete_memory` | `delete`, with a deletion receipt in Recallic |
64
+
65
+ Needs Recallic server 0.2.5 or newer (for `mode` and original timestamps). A session is stored in one request per
66
+ 100 events on server 0.2.6 or newer, and one request per event before that.
67
+
68
+ ## Tests
69
+
70
+ Against a running Recallic: `RECALLIC_URL=http://127.0.0.1:8000 RECALLIC_SERVICE_KEY=rx_... pytest tests`.
71
+
72
+ Licence: Apache-2.0.
@@ -0,0 +1,18 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "recallic-adk"
7
+ version = "0.2.0"
8
+ description = "Recallic as the memory service of Google ADK 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 = ["google-adk>=2.0", "recallic>=0.3.0"]
13
+
14
+ [project.urls]
15
+ Homepage = "https://github.com/Recallic/Recallic/tree/main/integrations/google-adk"
16
+
17
+ [tool.hatch.build.targets.wheel]
18
+ packages = ["src/recallic_adk"]
@@ -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,71 @@
1
+ """
2
+ Against a running Recallic server (skipped otherwise):
3
+ RECALLIC_URL=http://127.0.0.1:8000 RECALLIC_SERVICE_KEY=rx_... pytest integrations/google-adk/tests
4
+ """
5
+ import asyncio
6
+ import os
7
+ import time
8
+ import uuid
9
+
10
+ import pytest
11
+
12
+ URL, KEY = os.environ.get("RECALLIC_URL"), os.environ.get("RECALLIC_SERVICE_KEY")
13
+ pytestmark = pytest.mark.skipif(not (URL and KEY), reason="needs a running Recallic (RECALLIC_URL, RECALLIC_SERVICE_KEY)")
14
+
15
+
16
+ def run(coro):
17
+ return asyncio.run(coro)
18
+
19
+
20
+ def session_with(app, user, turns):
21
+ from google.adk.events.event import Event
22
+ from google.adk.sessions import InMemorySessionService
23
+ from google.genai import types
24
+ svc = InMemorySessionService()
25
+ s = run(svc.create_session(app_name=app, user_id=user))
26
+ for author, text, ts in turns:
27
+ run(svc.append_event(s, Event(author=author, timestamp=ts, invocation_id="i",
28
+ content=types.Content(role="user" if author == "user" else "model",
29
+ parts=[types.Part(text=text)]))))
30
+ return run(svc.get_session(app_name=app, user_id=user, session_id=s.id))
31
+
32
+
33
+ @pytest.fixture
34
+ def memory():
35
+ from recallic_adk import RecallicMemoryService
36
+ return RecallicMemoryService(api_key=KEY, base_url=URL)
37
+
38
+
39
+ def test_a_session_is_stored_with_its_dates_and_found_again(memory):
40
+ app, user = "adk-test", f"u-{uuid.uuid4().hex[:8]}"
41
+ month_ago = time.time() - 30 * 86400
42
+ s = session_with(app, user, [("user", "I moved to Pune in March for my new job.", month_ago),
43
+ ("assistant_agent", "Congratulations on the move!", month_ago + 5)])
44
+ run(memory.add_session_to_memory(s))
45
+ run(memory.add_session_to_memory(s)) # adding a session again stores nothing twice
46
+ out = run(memory.search_memory(app_name=app, user_id=user, query="Where did I move?"))
47
+ texts = [m.content.parts[0].text for m in out.memories]
48
+ assert any("Pune" in t for t in texts)
49
+ assert sum("Pune" in t for t in texts) == 1
50
+ assert not any("Congratulations" in t for t in texts) # only what the user said is stored by default
51
+ pune = next(m for m in out.memories if "Pune" in m.content.parts[0].text)
52
+ assert pune.timestamp.startswith(time.strftime("%Y-%m-%d", time.gmtime(month_ago)))
53
+
54
+
55
+ def test_no_record_means_no_memories_and_users_and_apps_are_separate(memory):
56
+ app, user = "adk-test", f"u-{uuid.uuid4().hex[:8]}"
57
+ run(memory.add_events_to_memory(app_name=app, user_id=user,
58
+ events=session_with(app, user, [("user", "I moved to Pune in March for my new job.", time.time())]).events))
59
+ assert run(memory.search_memory(app_name=app, user_id=f"other-{user}", query="Where did I move?")).memories == []
60
+ assert run(memory.search_memory(app_name="other-app", user_id=user, query="Where did I move?")).memories == []
61
+ assert run(memory.search_memory(app_name=app, user_id=user, query="What is my sister's name?")).memories == []
62
+
63
+
64
+ def test_delete_a_memory(memory):
65
+ app, user = "adk-test", f"u-{uuid.uuid4().hex[:8]}"
66
+ run(memory.add_events_to_memory(app_name=app, user_id=user,
67
+ events=session_with(app, user, [("user", "My locker code is 4417.", time.time())]).events))
68
+ found = run(memory.search_memory(app_name=app, user_id=user, query="What is my locker code?")).memories
69
+ assert found
70
+ run(memory.delete_memory(app_name=app, user_id=user, memory_id=found[0].id))
71
+ assert run(memory.search_memory(app_name=app, user_id=user, query="What is my locker code?")).memories == []