llama-index-memory-recallic 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.
- llama_index_memory_recallic-0.2.0/.gitignore +69 -0
- llama_index_memory_recallic-0.2.0/PKG-INFO +85 -0
- llama_index_memory_recallic-0.2.0/README.md +74 -0
- llama_index_memory_recallic-0.2.0/pyproject.toml +18 -0
- llama_index_memory_recallic-0.2.0/src/llama_index/memory/recallic/__init__.py +3 -0
- llama_index_memory_recallic-0.2.0/src/llama_index/memory/recallic/base.py +129 -0
- llama_index_memory_recallic-0.2.0/tests/test_memory_block.py +90 -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,85 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: llama-index-memory-recallic
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Recallic as long-term memory of LlamaIndex 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/llama-index
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Requires-Dist: llama-index-core>=0.12.40
|
|
9
|
+
Requires-Dist: recallic>=0.3.0
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
|
|
12
|
+
# llama-index-memory-recallic: Recallic memory for LlamaIndex agents
|
|
13
|
+
|
|
14
|
+
*Formerly `llama-index-memory-recallix` (0.1.x); renamed with the project, nothing else changed.*
|
|
15
|
+
|
|
16
|
+
`RecallicMemoryBlock` plugs a self-hosted [Recallic](https://github.com/Recallic/Recallic) server into
|
|
17
|
+
[LlamaIndex](https://www.llamaindex.ai)'s `Memory` as a long-term memory block.
|
|
18
|
+
|
|
19
|
+
* **No LLM calls for memory.** Storing and searching use Recallic's local models.
|
|
20
|
+
* **Across sessions and agents.** Each turn, the block recalls what this user said before, in any earlier session,
|
|
21
|
+
that bears on their latest message.
|
|
22
|
+
* **Honest.** When nothing answers it, the model is told there is no record instead of being handed near-misses to
|
|
23
|
+
guess from.
|
|
24
|
+
* **Stored right away.** New user messages are stored every turn, not only when LlamaIndex moves them out of
|
|
25
|
+
short-term memory; re-sending one Recallic already holds is skipped.
|
|
26
|
+
* **Your data stays on your server**, separated per user and per agent.
|
|
27
|
+
|
|
28
|
+
## Install
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install llama-index-memory-recallic
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Run Recallic ([quickstart](../../docs/quickstart.md)) and create a key with role `service`, which acts for each of
|
|
35
|
+
your users (or use a user's own key and leave `user_id` out):
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
python -m backend.tools.keys create --user my-llamaindex-app --role service
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Use
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
import os
|
|
45
|
+
|
|
46
|
+
from llama_index.core.agent.workflow import FunctionAgent
|
|
47
|
+
from llama_index.core.memory import Memory
|
|
48
|
+
from llama_index.memory.recallic import RecallicMemoryBlock
|
|
49
|
+
|
|
50
|
+
block = RecallicMemoryBlock(api_key=os.environ["RECALLIC_SERVICE_KEY"], base_url="http://localhost:8000",
|
|
51
|
+
user_id="alice", mode="balanced") # or "cautious" / "helpful"
|
|
52
|
+
memory = Memory.from_defaults(session_id="alice-chat-1", memory_blocks=[block])
|
|
53
|
+
|
|
54
|
+
agent = FunctionAgent(llm=llm, tools=[...])
|
|
55
|
+
await agent.run("I moved to Pune in March.", memory=memory)
|
|
56
|
+
|
|
57
|
+
# days later, a new session: a new Memory, the same user
|
|
58
|
+
later = Memory.from_defaults(session_id="alice-chat-2", memory_blocks=[block])
|
|
59
|
+
await agent.run("Which city did I move to?", memory=later) # "You moved to Pune."
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
| Parameter | Default | What it does |
|
|
63
|
+
|---|---|---|
|
|
64
|
+
| `user_id` | `None` | Whose memory this is. Needed with a `service` key; leave out with a user's own key. |
|
|
65
|
+
| `agent_id` | `llamaindex` | Recallic agent id; each agent reads back what it wrote (and what any agent shared). |
|
|
66
|
+
| `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. |
|
|
67
|
+
| `limit` | 5 | Memories given to the model per turn. |
|
|
68
|
+
| `store_roles` | `("user",)` | Which message roles are stored. The default stores what users said, not the model's replies. |
|
|
69
|
+
| `store_immediately` | `True` | Store new messages every turn (after recalling). `False`: only when LlamaIndex moves them out of short-term memory. |
|
|
70
|
+
| `tell_model_on_decline` | `True` | When nothing answers, tell the model not to guess about the user's past. |
|
|
71
|
+
|
|
72
|
+
Notes:
|
|
73
|
+
|
|
74
|
+
* The block is queried with the user's latest message. A message's original time can be given as
|
|
75
|
+
`additional_kwargs={"timestamp": <unix seconds>}`; the LlamaIndex session id is kept in the memory's metadata.
|
|
76
|
+
* The API key is not included when the block is serialized.
|
|
77
|
+
* Needs Recallic server 0.2.5 or newer; messages go in one request per 100 on server 0.2.6 or newer.
|
|
78
|
+
* Tested with llama-index-core 0.14.
|
|
79
|
+
|
|
80
|
+
## Tests
|
|
81
|
+
|
|
82
|
+
Against a running Recallic: `RECALLIC_URL=http://127.0.0.1:8000 RECALLIC_SERVICE_KEY=rx_... pytest tests`.
|
|
83
|
+
They include a real LlamaIndex chat engine run with a scripted model.
|
|
84
|
+
|
|
85
|
+
Licence: Apache-2.0.
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# llama-index-memory-recallic: Recallic memory for LlamaIndex agents
|
|
2
|
+
|
|
3
|
+
*Formerly `llama-index-memory-recallix` (0.1.x); renamed with the project, nothing else changed.*
|
|
4
|
+
|
|
5
|
+
`RecallicMemoryBlock` plugs a self-hosted [Recallic](https://github.com/Recallic/Recallic) server into
|
|
6
|
+
[LlamaIndex](https://www.llamaindex.ai)'s `Memory` as a long-term memory block.
|
|
7
|
+
|
|
8
|
+
* **No LLM calls for memory.** Storing and searching use Recallic's local models.
|
|
9
|
+
* **Across sessions and agents.** Each turn, the block recalls what this user said before, in any earlier session,
|
|
10
|
+
that bears on their latest message.
|
|
11
|
+
* **Honest.** When nothing answers it, the model is told there is no record instead of being handed near-misses to
|
|
12
|
+
guess from.
|
|
13
|
+
* **Stored right away.** New user messages are stored every turn, not only when LlamaIndex moves them out of
|
|
14
|
+
short-term memory; re-sending one Recallic already holds is skipped.
|
|
15
|
+
* **Your data stays on your server**, separated per user and per agent.
|
|
16
|
+
|
|
17
|
+
## Install
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pip install llama-index-memory-recallic
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Run Recallic ([quickstart](../../docs/quickstart.md)) and create a key with role `service`, which acts for each of
|
|
24
|
+
your users (or use a user's own key and leave `user_id` out):
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
python -m backend.tools.keys create --user my-llamaindex-app --role service
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Use
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
import os
|
|
34
|
+
|
|
35
|
+
from llama_index.core.agent.workflow import FunctionAgent
|
|
36
|
+
from llama_index.core.memory import Memory
|
|
37
|
+
from llama_index.memory.recallic import RecallicMemoryBlock
|
|
38
|
+
|
|
39
|
+
block = RecallicMemoryBlock(api_key=os.environ["RECALLIC_SERVICE_KEY"], base_url="http://localhost:8000",
|
|
40
|
+
user_id="alice", mode="balanced") # or "cautious" / "helpful"
|
|
41
|
+
memory = Memory.from_defaults(session_id="alice-chat-1", memory_blocks=[block])
|
|
42
|
+
|
|
43
|
+
agent = FunctionAgent(llm=llm, tools=[...])
|
|
44
|
+
await agent.run("I moved to Pune in March.", memory=memory)
|
|
45
|
+
|
|
46
|
+
# days later, a new session: a new Memory, the same user
|
|
47
|
+
later = Memory.from_defaults(session_id="alice-chat-2", memory_blocks=[block])
|
|
48
|
+
await agent.run("Which city did I move to?", memory=later) # "You moved to Pune."
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
| Parameter | Default | What it does |
|
|
52
|
+
|---|---|---|
|
|
53
|
+
| `user_id` | `None` | Whose memory this is. Needed with a `service` key; leave out with a user's own key. |
|
|
54
|
+
| `agent_id` | `llamaindex` | Recallic agent id; each agent reads back what it wrote (and what any agent shared). |
|
|
55
|
+
| `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. |
|
|
56
|
+
| `limit` | 5 | Memories given to the model per turn. |
|
|
57
|
+
| `store_roles` | `("user",)` | Which message roles are stored. The default stores what users said, not the model's replies. |
|
|
58
|
+
| `store_immediately` | `True` | Store new messages every turn (after recalling). `False`: only when LlamaIndex moves them out of short-term memory. |
|
|
59
|
+
| `tell_model_on_decline` | `True` | When nothing answers, tell the model not to guess about the user's past. |
|
|
60
|
+
|
|
61
|
+
Notes:
|
|
62
|
+
|
|
63
|
+
* The block is queried with the user's latest message. A message's original time can be given as
|
|
64
|
+
`additional_kwargs={"timestamp": <unix seconds>}`; the LlamaIndex session id is kept in the memory's metadata.
|
|
65
|
+
* The API key is not included when the block is serialized.
|
|
66
|
+
* Needs Recallic server 0.2.5 or newer; messages go in one request per 100 on server 0.2.6 or newer.
|
|
67
|
+
* Tested with llama-index-core 0.14.
|
|
68
|
+
|
|
69
|
+
## Tests
|
|
70
|
+
|
|
71
|
+
Against a running Recallic: `RECALLIC_URL=http://127.0.0.1:8000 RECALLIC_SERVICE_KEY=rx_... pytest tests`.
|
|
72
|
+
They include a real LlamaIndex chat engine run with a scripted model.
|
|
73
|
+
|
|
74
|
+
Licence: Apache-2.0.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "llama-index-memory-recallic"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "Recallic as long-term memory of LlamaIndex 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 = ["llama-index-core>=0.12.40", "recallic>=0.3.0"]
|
|
13
|
+
|
|
14
|
+
[project.urls]
|
|
15
|
+
Homepage = "https://github.com/Recallic/Recallic/tree/main/integrations/llama-index"
|
|
16
|
+
|
|
17
|
+
[tool.hatch.build.targets.wheel]
|
|
18
|
+
packages = ["src/llama_index"]
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""
|
|
2
|
+
RecallicMemoryBlock: Recallic as long-term memory of a LlamaIndex agent.
|
|
3
|
+
|
|
4
|
+
from llama_index.core.memory import Memory
|
|
5
|
+
from llama_index.memory.recallic import RecallicMemoryBlock
|
|
6
|
+
|
|
7
|
+
block = RecallicMemoryBlock(api_key="rx_...", user_id="alice") # a "service" key acts for each user
|
|
8
|
+
memory = Memory.from_defaults(session_id="alice-1", memory_blocks=[block])
|
|
9
|
+
agent.run("Where did I move?", memory=memory)
|
|
10
|
+
|
|
11
|
+
Each turn, the block recalls what this user said before that bears on their latest message (in any earlier
|
|
12
|
+
session or agent) and gives it to the model; when nothing answers it, it says so instead of handing over
|
|
13
|
+
near-misses. Then it stores the user's new messages (re-sending one Recallic already holds is skipped). No LLM is
|
|
14
|
+
called to store or search memory.
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import asyncio
|
|
19
|
+
from datetime import datetime, timezone
|
|
20
|
+
from typing import Any, List, Optional, Tuple
|
|
21
|
+
|
|
22
|
+
from llama_index.core.base.llms.types import ChatMessage, TextBlock
|
|
23
|
+
from llama_index.core.bridge.pydantic import Field, PrivateAttr
|
|
24
|
+
from llama_index.core.memory.memory import BaseMemoryBlock
|
|
25
|
+
from recallic import Memory as RecallicClient
|
|
26
|
+
|
|
27
|
+
DECLINE_NOTE = ("None of this user's earlier messages answers their latest message. If it depends on something "
|
|
28
|
+
"they would have told you before, say you don't have a record of it rather than guess.")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _text(message: ChatMessage) -> str:
|
|
32
|
+
return " ".join(b.text for b in message.blocks if isinstance(b, TextBlock) and b.text).strip()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _when(ts: Any) -> str:
|
|
36
|
+
try:
|
|
37
|
+
return datetime.fromtimestamp(float(ts), tz=timezone.utc).strftime("%d %b %Y")
|
|
38
|
+
except (TypeError, ValueError):
|
|
39
|
+
return ""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class RecallicMemoryBlock(BaseMemoryBlock[str]):
|
|
43
|
+
"""
|
|
44
|
+
A LlamaIndex memory block backed by a self-hosted Recallic server.
|
|
45
|
+
|
|
46
|
+
api_key: a Recallic key. Role "service" acts for `user_id`; a "user" key acts for itself (leave user_id None).
|
|
47
|
+
user_id: whose memory this is (Recallic keeps each user's memories apart).
|
|
48
|
+
agent_id: Recallic agent id; each agent reads back what it wrote (and what any agent shared).
|
|
49
|
+
mode: "cautious" | "balanced" | "helpful" (None: the server's recall.mode).
|
|
50
|
+
store_roles: which message roles are stored ("user" by default: memories are what the user said).
|
|
51
|
+
store_immediately: store new messages every turn (after recalling), not only when LlamaIndex moves them out of
|
|
52
|
+
short-term memory, so other sessions and agents see them at once.
|
|
53
|
+
tell_model_on_decline: when Recallic has no answering memory, tell the model not to guess about the user's past.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
name: str = Field(default="recallic_memory", description="The name of the memory block.")
|
|
57
|
+
description: Optional[str] = Field(default="What this user told you in earlier conversations (Recallic).")
|
|
58
|
+
api_key: str = Field(exclude=True, repr=False, description="Recallic API key.")
|
|
59
|
+
base_url: str = Field(default="http://localhost:8000")
|
|
60
|
+
user_id: Optional[str] = Field(default=None)
|
|
61
|
+
agent_id: str = Field(default="llamaindex")
|
|
62
|
+
mode: Optional[str] = Field(default=None)
|
|
63
|
+
limit: int = Field(default=5, ge=1, le=20)
|
|
64
|
+
store_roles: Tuple[str, ...] = Field(default=("user",))
|
|
65
|
+
store_immediately: bool = Field(default=True)
|
|
66
|
+
tell_model_on_decline: bool = Field(default=True)
|
|
67
|
+
timeout: float = Field(default=30.0)
|
|
68
|
+
|
|
69
|
+
_client: RecallicClient = PrivateAttr()
|
|
70
|
+
_sent: set = PrivateAttr(default_factory=set)
|
|
71
|
+
|
|
72
|
+
def __init__(self, **data: Any) -> None:
|
|
73
|
+
client = data.pop("client", None)
|
|
74
|
+
super().__init__(**data)
|
|
75
|
+
self._client = client or RecallicClient(api_key=self.api_key, base_url=self.base_url, timeout=self.timeout)
|
|
76
|
+
|
|
77
|
+
# ---------------------------------------------------------------- reading
|
|
78
|
+
|
|
79
|
+
def _recall(self, query: str) -> str:
|
|
80
|
+
out = self._client.recall(query[:2000], limit=self.limit, agent_id=self.agent_id, user_id=self.user_id,
|
|
81
|
+
mode=self.mode)
|
|
82
|
+
memories = out.get("memories") or []
|
|
83
|
+
if out.get("status") != "CONSISTENT" or not memories:
|
|
84
|
+
return DECLINE_NOTE if self.tell_model_on_decline else ""
|
|
85
|
+
lines = ["Things this user told you before (newest facts win; use only what bears on their message):"]
|
|
86
|
+
for m in memories[: self.limit]:
|
|
87
|
+
when = _when(m.get("timestamp"))
|
|
88
|
+
lines.append(f"- {('[' + when + '] ') if when else ''}{m.get('content_resolved') or m.get('content', '')}")
|
|
89
|
+
computed = out.get("computed_answer")
|
|
90
|
+
if computed and computed.get("text"):
|
|
91
|
+
lines.append(f"Worked out from these memories: {computed['text']} "
|
|
92
|
+
f"({(out.get('receipt') or {}).get('computed', '')}).")
|
|
93
|
+
return "\n".join(lines)
|
|
94
|
+
|
|
95
|
+
async def _aget(self, messages: Optional[List[ChatMessage]] = None, **block_kwargs: Any) -> str:
|
|
96
|
+
messages = messages or []
|
|
97
|
+
last_user = next((m for m in reversed(messages) if m.role.value == "user" and _text(m)), None)
|
|
98
|
+
content = await asyncio.to_thread(self._recall, _text(last_user)) if last_user else ""
|
|
99
|
+
if self.store_immediately: # after recalling, so the question does not recall itself
|
|
100
|
+
await self._store(messages)
|
|
101
|
+
return content
|
|
102
|
+
|
|
103
|
+
# ---------------------------------------------------------------- writing
|
|
104
|
+
|
|
105
|
+
def _new_items(self, messages: List[ChatMessage]) -> List[dict]:
|
|
106
|
+
items = []
|
|
107
|
+
for m in messages:
|
|
108
|
+
role, text = m.role.value, _text(m)
|
|
109
|
+
if role not in self.store_roles or not text:
|
|
110
|
+
continue
|
|
111
|
+
key = (role, text)
|
|
112
|
+
if key in self._sent:
|
|
113
|
+
continue
|
|
114
|
+
self._sent.add(key)
|
|
115
|
+
ts = m.additional_kwargs.get("timestamp")
|
|
116
|
+
items.append({"content": text[:20000], "timestamp": ts if isinstance(ts, (int, float)) else None,
|
|
117
|
+
"metadata": {"speaker": "User" if role == "user" else role,
|
|
118
|
+
**({"session_id": m.additional_kwargs["session_id"]}
|
|
119
|
+
if m.additional_kwargs.get("session_id") else {})}})
|
|
120
|
+
return items
|
|
121
|
+
|
|
122
|
+
async def _store(self, messages: List[ChatMessage]) -> None:
|
|
123
|
+
items = self._new_items(messages)
|
|
124
|
+
if items:
|
|
125
|
+
await asyncio.to_thread(self._client.store_many, items, agent_id=self.agent_id, user_id=self.user_id)
|
|
126
|
+
|
|
127
|
+
async def _aput(self, messages: List[ChatMessage]) -> None:
|
|
128
|
+
"""Messages LlamaIndex moves out of short-term memory (already stored when store_immediately is on)."""
|
|
129
|
+
await self._store(messages)
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Live tests against a running Recallic:
|
|
3
|
+
RECALLIC_URL=http://127.0.0.1:8000 RECALLIC_SERVICE_KEY=rx_... pytest tests
|
|
4
|
+
"""
|
|
5
|
+
import asyncio
|
|
6
|
+
import os
|
|
7
|
+
import uuid
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import pytest
|
|
11
|
+
from llama_index.core.base.llms.types import ChatMessage, CompletionResponse, LLMMetadata
|
|
12
|
+
from llama_index.core.llms.custom import CustomLLM
|
|
13
|
+
from llama_index.core.memory import Memory
|
|
14
|
+
from llama_index.memory.recallic import RecallicMemoryBlock
|
|
15
|
+
|
|
16
|
+
URL, KEY = os.environ.get("RECALLIC_URL"), os.environ.get("RECALLIC_SERVICE_KEY")
|
|
17
|
+
pytestmark = pytest.mark.skipif(not (URL and KEY), reason="needs RECALLIC_URL and RECALLIC_SERVICE_KEY")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _block(user, **kw):
|
|
21
|
+
return RecallicMemoryBlock(api_key=KEY, base_url=URL, user_id=user, agent_id="li-test", timeout=120, **kw)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _memory(user, **kw):
|
|
25
|
+
return Memory.from_defaults(session_id=f"{user}-{uuid.uuid4().hex[:6]}", memory_blocks=[_block(user, **kw)])
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _system_text(messages):
|
|
29
|
+
return "\n".join(m.content or "" for m in messages if m.role.value == "system")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_recalls_across_sessions_and_declines_honestly():
|
|
33
|
+
user = f"li-{uuid.uuid4().hex[:8]}"
|
|
34
|
+
|
|
35
|
+
async def run():
|
|
36
|
+
first = _memory(user)
|
|
37
|
+
await first.aput(ChatMessage(role="user", content="I moved to Pune in March, and my sister Mira is a pediatrician in Goa."))
|
|
38
|
+
await first.aget(input="Thanks!") # a turn: recall, then store the new user message
|
|
39
|
+
second = _memory(user) # a brand-new session: nothing in its short-term memory
|
|
40
|
+
found = await second.aget(input="Which city did I move to?")
|
|
41
|
+
never = await second.aget(input="What is my brother's name?")
|
|
42
|
+
return found, never
|
|
43
|
+
|
|
44
|
+
found, never = asyncio.run(run())
|
|
45
|
+
assert "Pune" in _system_text(found)
|
|
46
|
+
text = _system_text(never)
|
|
47
|
+
assert "don't have a record" in text and "Pune" not in text
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def test_the_question_is_not_recalled_as_its_own_answer():
|
|
51
|
+
user = f"li-{uuid.uuid4().hex[:8]}"
|
|
52
|
+
|
|
53
|
+
async def run():
|
|
54
|
+
mem = _memory(user)
|
|
55
|
+
await mem.aput(ChatMessage(role="user", content="What is my brother's name?"))
|
|
56
|
+
await mem.aget() # stores the question (after recalling)
|
|
57
|
+
return await _memory(user).aget(input="What is my brother's name?")
|
|
58
|
+
|
|
59
|
+
assert "don't have a record" in _system_text(asyncio.run(run()))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_no_decline_note_when_turned_off():
|
|
63
|
+
user = f"li-{uuid.uuid4().hex[:8]}"
|
|
64
|
+
out = asyncio.run(_memory(user, tell_model_on_decline=False).aget(input="What is my brother's name?"))
|
|
65
|
+
assert "Recallic" not in _system_text(out) and "record" not in _system_text(out)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class RecordingLLM(CustomLLM):
|
|
69
|
+
"""A scripted model that records the prompt it is given."""
|
|
70
|
+
seen: list = []
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def metadata(self) -> LLMMetadata:
|
|
74
|
+
return LLMMetadata(is_chat_model=False)
|
|
75
|
+
|
|
76
|
+
def complete(self, prompt: str, formatted: bool = False, **kwargs: Any) -> CompletionResponse:
|
|
77
|
+
self.seen.append(prompt)
|
|
78
|
+
return CompletionResponse(text="Noted.")
|
|
79
|
+
|
|
80
|
+
def stream_complete(self, prompt: str, formatted: bool = False, **kwargs: Any):
|
|
81
|
+
yield self.complete(prompt)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def test_inside_a_llamaindex_chat_engine():
|
|
85
|
+
from llama_index.core.chat_engine import SimpleChatEngine
|
|
86
|
+
user = f"li-{uuid.uuid4().hex[:8]}"
|
|
87
|
+
llm = RecordingLLM()
|
|
88
|
+
SimpleChatEngine.from_defaults(llm=llm, memory=_memory(user)).chat("My cat is called Biscuit.")
|
|
89
|
+
SimpleChatEngine.from_defaults(llm=llm, memory=_memory(user)).chat("What is my cat called?")
|
|
90
|
+
assert "Biscuit" in llm.seen[-1] and "Things this user told you before" in llm.seen[-1]
|