supermemory-pipecat 0.1.4__tar.gz → 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.
@@ -1,13 +1,13 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: supermemory-pipecat
3
- Version: 0.1.4
3
+ Version: 0.2.0
4
4
  Summary: Supermemory integration for Pipecat - memory-enhanced conversational AI pipelines
5
5
  Project-URL: Homepage, https://supermemory.ai
6
6
  Project-URL: Documentation, https://docs.supermemory.ai
7
7
  Project-URL: Repository, https://github.com/supermemoryai/supermemory
8
8
  Author-email: Supermemory <support@supermemory.ai>
9
9
  License-Expression: MIT
10
- Keywords: conversational-ai,llm,memory,pipecat,supermemory>=3.16.0,<5,voice-ai
10
+ Keywords: conversational-ai,llm,memory,pipecat,supermemory,voice-ai
11
11
  Classifier: Development Status :: 4 - Beta
12
12
  Classifier: Intended Audience :: Developers
13
13
  Classifier: License :: OSI Approved :: MIT License
@@ -20,7 +20,7 @@ Requires-Python: >=3.10
20
20
  Requires-Dist: loguru>=0.7.3
21
21
  Requires-Dist: pipecat-ai<2.0.0,>=0.0.98
22
22
  Requires-Dist: pydantic>=2.10.0
23
- Requires-Dist: supermemory>=3.16.0
23
+ Requires-Dist: supermemory<6,>=5.0.0
24
24
  Provides-Extra: dev
25
25
  Requires-Dist: black>=24.8.0; extra == 'dev'
26
26
  Requires-Dist: isort>=5.13.2; extra == 'dev'
@@ -39,6 +39,10 @@ Memory-enhanced conversational AI pipelines with [Supermemory](https://supermemo
39
39
  pip install supermemory-pipecat
40
40
  ```
41
41
 
42
+ Version 0.2.0 requires the Supermemory Python SDK v5. Keep using `user_id=`;
43
+ the service passes that value as the namespace for profile, search, and writes.
44
+ `session_id` is passed as the v5 document `id` (previously `custom_id`).
45
+
42
46
  ## Quick Start
43
47
 
44
48
  ```python
@@ -50,7 +54,7 @@ from supermemory_pipecat import SupermemoryPipecatService
50
54
  # Create memory service
51
55
  memory = SupermemoryPipecatService(
52
56
  api_key=os.getenv("SUPERMEMORY_API_KEY"),
53
- user_id="user-123", # Required: used as container_tag
57
+ user_id="user-123", # Required: scopes all memory calls
54
58
  session_id="conversation-456", # Optional: groups memories by session
55
59
  )
56
60
 
@@ -76,7 +80,7 @@ pipeline = Pipeline([
76
80
 
77
81
  | Parameter | Type | Required | Description |
78
82
  | ------------ | ----------- | -------- | ---------------------------------------------------------- |
79
- | `user_id` | str | **Yes** | User identifier - used as container_tag for memory scoping |
83
+ | `user_id` | str | **Yes** | User identifier passed as the v5 namespace for memory scoping |
80
84
  | `session_id` | str | No | Session/conversation ID for grouping memories |
81
85
  | `api_key` | str | No | Supermemory API key (or set `SUPERMEMORY_API_KEY` env var) |
82
86
  | `params` | InputParams | No | Advanced configuration |
@@ -112,7 +116,7 @@ memory = SupermemoryPipecatService(
112
116
 
113
117
  1. **Intercepts context frames** - Listens for Pipecat's universal `LLMContextFrame` (and legacy 0.x frames)
114
118
  2. **Tracks conversation** - Separates real conversation messages from tagged memory context
115
- 3. **Retrieves memories** - Queries `/v4/profile` API with user's message
119
+ 3. **Retrieves memories** - Reads the v5 profile and, in `query` or `full` mode, searches the same namespace for the user's message
116
120
  4. **Injects memories** - Uses a system message for audio/system mode and a tagged user message otherwise
117
121
  5. **Stores messages** - Serializes newly observed user and assistant messages through a background queue that drains during cleanup
118
122
 
@@ -129,13 +133,12 @@ User: What's the weather like today?
129
133
  Assistant: It's sunny today.
130
134
  ```
131
135
 
132
- is sent to Supermemory as:
136
+ is added to the `user-123` namespace as:
133
137
 
134
138
  ```json
135
139
  {
136
140
  "content": "[{\"role\": \"user\", \"content\": \"What's the weather like today?\"}, {\"role\": \"assistant\", \"content\": \"It's sunny today.\"}]",
137
- "container_tags": ["user-123"],
138
- "custom_id": "conversation-456",
141
+ "id": "conversation-456",
139
142
  "metadata": { "platform": "pipecat" }
140
143
  }
141
144
  ```
@@ -8,6 +8,10 @@ Memory-enhanced conversational AI pipelines with [Supermemory](https://supermemo
8
8
  pip install supermemory-pipecat
9
9
  ```
10
10
 
11
+ Version 0.2.0 requires the Supermemory Python SDK v5. Keep using `user_id=`;
12
+ the service passes that value as the namespace for profile, search, and writes.
13
+ `session_id` is passed as the v5 document `id` (previously `custom_id`).
14
+
11
15
  ## Quick Start
12
16
 
13
17
  ```python
@@ -19,7 +23,7 @@ from supermemory_pipecat import SupermemoryPipecatService
19
23
  # Create memory service
20
24
  memory = SupermemoryPipecatService(
21
25
  api_key=os.getenv("SUPERMEMORY_API_KEY"),
22
- user_id="user-123", # Required: used as container_tag
26
+ user_id="user-123", # Required: scopes all memory calls
23
27
  session_id="conversation-456", # Optional: groups memories by session
24
28
  )
25
29
 
@@ -45,7 +49,7 @@ pipeline = Pipeline([
45
49
 
46
50
  | Parameter | Type | Required | Description |
47
51
  | ------------ | ----------- | -------- | ---------------------------------------------------------- |
48
- | `user_id` | str | **Yes** | User identifier - used as container_tag for memory scoping |
52
+ | `user_id` | str | **Yes** | User identifier passed as the v5 namespace for memory scoping |
49
53
  | `session_id` | str | No | Session/conversation ID for grouping memories |
50
54
  | `api_key` | str | No | Supermemory API key (or set `SUPERMEMORY_API_KEY` env var) |
51
55
  | `params` | InputParams | No | Advanced configuration |
@@ -81,7 +85,7 @@ memory = SupermemoryPipecatService(
81
85
 
82
86
  1. **Intercepts context frames** - Listens for Pipecat's universal `LLMContextFrame` (and legacy 0.x frames)
83
87
  2. **Tracks conversation** - Separates real conversation messages from tagged memory context
84
- 3. **Retrieves memories** - Queries `/v4/profile` API with user's message
88
+ 3. **Retrieves memories** - Reads the v5 profile and, in `query` or `full` mode, searches the same namespace for the user's message
85
89
  4. **Injects memories** - Uses a system message for audio/system mode and a tagged user message otherwise
86
90
  5. **Stores messages** - Serializes newly observed user and assistant messages through a background queue that drains during cleanup
87
91
 
@@ -98,13 +102,12 @@ User: What's the weather like today?
98
102
  Assistant: It's sunny today.
99
103
  ```
100
104
 
101
- is sent to Supermemory as:
105
+ is added to the `user-123` namespace as:
102
106
 
103
107
  ```json
104
108
  {
105
109
  "content": "[{\"role\": \"user\", \"content\": \"What's the weather like today?\"}, {\"role\": \"assistant\", \"content\": \"It's sunny today.\"}]",
106
- "container_tags": ["user-123"],
107
- "custom_id": "conversation-456",
110
+ "id": "conversation-456",
108
111
  "metadata": { "platform": "pipecat" }
109
112
  }
110
113
  ```
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "supermemory-pipecat"
7
- version = "0.1.4"
7
+ version = "0.2.0"
8
8
  description = "Supermemory integration for Pipecat - memory-enhanced conversational AI pipelines"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -13,7 +13,7 @@ authors = [
13
13
  { name = "Supermemory", email = "support@supermemory.ai" }
14
14
  ]
15
15
  keywords = [
16
- "supermemory>=3.16.0,<5",
16
+ "supermemory",
17
17
  "pipecat",
18
18
  "memory",
19
19
  "conversational-ai",
@@ -32,7 +32,7 @@ classifiers = [
32
32
  ]
33
33
  dependencies = [
34
34
  "pipecat-ai>=0.0.98,<2.0.0",
35
- "supermemory>=3.16.0",
35
+ "supermemory>=5.0.0,<6",
36
36
  "pydantic>=2.10.0",
37
37
  "loguru>=0.7.3",
38
38
  ]
@@ -42,15 +42,18 @@ from .utils import (
42
42
  get_last_user_message,
43
43
  )
44
44
 
45
+ InputParams = SupermemoryPipecatService.InputParams
46
+
45
47
  try:
46
48
  __version__ = version("supermemory-pipecat")
47
49
  except PackageNotFoundError:
48
50
  # Source-tree fallback; built wheels always use package metadata above.
49
- __version__ = "0.1.3"
51
+ __version__ = "0.2.0"
50
52
 
51
53
  __all__ = [
52
54
  # Main service
53
55
  "SupermemoryPipecatService",
56
+ "InputParams",
54
57
  # Exceptions
55
58
  "SupermemoryPipecatError",
56
59
  "ConfigurationError",
@@ -23,6 +23,7 @@ from pipecat.processors.frame_processor import FrameDirection, FrameProcessor
23
23
  from .exceptions import ConfigurationError, MemoryRetrievalError, MemoryStorageError
24
24
  from .utils import (
25
25
  _field,
26
+ _memory_text,
26
27
  deduplicate_memories,
27
28
  escape_memory_delimiters,
28
29
  format_memories_to_text,
@@ -167,13 +168,13 @@ class SupermemoryPipecatService(FrameProcessor):
167
168
 
168
169
  Args:
169
170
  api_key: Supermemory API key. Falls back to SUPERMEMORY_API_KEY env var.
170
- user_id: The user ID - used as container_tag for memory scoping.
171
+ user_id: User identifier passed as the v5 namespace for memory scoping.
171
172
  session_id: Session/conversation ID for grouping memories.
172
173
  params: Configuration parameters for memory retrieval.
173
174
  base_url: Optional custom base URL for Supermemory API.
174
175
 
175
176
  Raises:
176
- ConfigurationError: If API key is missing or user_id not provided.
177
+ ConfigurationError: If API key or user_id is missing.
177
178
  """
178
179
  super().__init__()
179
180
 
@@ -226,25 +227,44 @@ class SupermemoryPipecatService(FrameProcessor):
226
227
  )
227
228
 
228
229
  try:
229
- # One profile call: static + dynamic, and (when mode/query allow)
230
- # search_results via `q`. This is the intended profile API shape.
231
- kwargs: Dict[str, Any] = {"container_tag": self.container_tag}
230
+ calls: Dict[str, Any] = {}
231
+ if self.params.mode != "query":
232
+ calls["profile"] = self._supermemory_client.profile(self.user_id)
232
233
  if self.params.mode != "profile" and query:
233
- kwargs["q"] = query
234
- kwargs["threshold"] = self.params.search_threshold
235
-
236
- response = await self._supermemory_client.profile(**kwargs)
237
-
238
- profile = _field(response, "profile")
239
- search_results_response = _field(response, "search_results", "searchResults")
234
+ calls["search"] = self._supermemory_client.search(
235
+ self.user_id,
236
+ query=query,
237
+ search_mode="memories",
238
+ limit=min(self.params.search_limit, 100),
239
+ threshold=self.params.search_threshold,
240
+ )
241
+ results = await asyncio.gather(*calls.values(), return_exceptions=True)
242
+ responses = {}
243
+ for name, result in zip(calls, results):
244
+ if isinstance(result, asyncio.CancelledError):
245
+ raise result
246
+ if isinstance(result, Exception):
247
+ logger.warning(f"Supermemory {name} failed: {result}")
248
+ else:
249
+ responses[name] = result
250
+ if calls and not responses:
251
+ raise results[0]
240
252
 
241
- raw_search_results = _field(search_results_response, "results", default=[]) or []
242
- search_results = list(raw_search_results)[: self.params.search_limit]
253
+ profile = _field(responses.get("profile"), "profile")
254
+ search_results = list(_field(responses.get("search"), "results", default=[]) or [])
243
255
 
244
256
  return {
245
257
  "profile": {
246
- "static": list(_field(profile, "static", default=[]) or []),
247
- "dynamic": list(_field(profile, "dynamic", default=[]) or []),
258
+ "static": [
259
+ text
260
+ for item in _field(profile, "static", default=[]) or []
261
+ if (text := _memory_text(item))
262
+ ],
263
+ "dynamic": [
264
+ text
265
+ for item in _field(profile, "dynamic", default=[]) or []
266
+ if (text := _memory_text(item))
267
+ ],
248
268
  },
249
269
  "search_results": search_results,
250
270
  }
@@ -264,13 +284,12 @@ class SupermemoryPipecatService(FrameProcessor):
264
284
  try:
265
285
  add_params: Dict[str, Any] = {
266
286
  "content": json.dumps(messages),
267
- "container_tags": [self.container_tag],
268
287
  "metadata": {"platform": "pipecat"},
269
288
  }
270
289
  if self.session_id:
271
- add_params["custom_id"] = self.session_id
290
+ add_params["id"] = self.session_id
272
291
 
273
- await self._supermemory_client.add(**add_params)
292
+ await self._supermemory_client.add(self.user_id, **add_params)
274
293
 
275
294
  except Exception as e:
276
295
  raise MemoryStorageError("Failed to store messages", e) from e
@@ -416,7 +435,7 @@ class SupermemoryPipecatService(FrameProcessor):
416
435
  existing_content = messages[system_idx].get("content", "")
417
436
  if MEMORY_TAG_PATTERN.search(existing_content):
418
437
  messages[system_idx]["content"] = MEMORY_TAG_PATTERN.sub(
419
- tagged_memory, existing_content
438
+ lambda _match: tagged_memory, existing_content
420
439
  )
421
440
  else:
422
441
  messages[system_idx]["content"] = f"{existing_content}\n\n{tagged_memory}"
@@ -4,7 +4,6 @@ import re
4
4
  from datetime import datetime, timezone
5
5
  from typing import Any, Dict, List, Union
6
6
 
7
-
8
7
  _DYNAMIC_DATE_PREFIX = re.compile(
9
8
  r"^\s*(?:\[recent\]\s*)?(?:\[\d{4}-\d{2}-\d{2}\]\s*)?",
10
9
  re.IGNORECASE,
@@ -71,11 +70,7 @@ def format_relative_time(iso_timestamp: str) -> str:
71
70
 
72
71
 
73
72
  def _field(item: Any, *names: str, default: Any = None) -> Any:
74
- """Read a field from a dict or pydantic/SDK model.
75
-
76
- Accepts camelCase and snake_case names so helpers work with both raw JSON
77
- dicts and Stainless-generated response models.
78
- """
73
+ """Accept alternative field names across raw JSON and SDK response models."""
79
74
  if item is None:
80
75
  return default
81
76
  if isinstance(item, dict):
@@ -90,6 +85,17 @@ def _field(item: Any, *names: str, default: Any = None) -> Any:
90
85
  return default
91
86
 
92
87
 
88
+ def _memory_text(item: Any) -> str:
89
+ """First non-empty memory field; `_field` alone would stop at an empty `memory`."""
90
+ if isinstance(item, str):
91
+ return item.strip()
92
+ for name in ("memory", "chunk", "content"):
93
+ value = _field(item, name)
94
+ if isinstance(value, str) and value.strip():
95
+ return value.strip()
96
+ return ""
97
+
98
+
93
99
  def deduplicate_memories(
94
100
  static: List[str],
95
101
  dynamic: List[str],
@@ -124,13 +130,7 @@ def deduplicate_memories(
124
130
  def unique_search(results: List[Any]) -> List[Any]:
125
131
  out: List[Any] = []
126
132
  for r in results:
127
- # v4 search.memories/hybrid uses `memory` or `chunk`.
128
- memory = (
129
- r if isinstance(r, str) else _field(r, "memory", "chunk", "content", default="")
130
- )
131
- if not isinstance(memory, str):
132
- memory = ""
133
- memory = memory.strip()
133
+ memory = _memory_text(r)
134
134
  key = comparison_key(memory)
135
135
  if key and key not in seen:
136
136
  seen.add(key)
@@ -177,8 +177,10 @@ def format_memories_to_text(
177
177
  lines.append(f"- {item}")
178
178
  continue
179
179
 
180
- memory = _field(item, "memory", "chunk", "content", default="")
181
- updated_at = _field(item, "updatedAt", "updated_at", default="")
180
+ memory = _memory_text(item)
181
+ updated_at = _field(item, "updatedAt", "updated_at") or _field(
182
+ _field(item, "system"), "updatedAt", "updated_at", default=""
183
+ )
182
184
  time_str = format_relative_time(updated_at) if updated_at else ""
183
185
  if time_str:
184
186
  lines.append(f"- [{time_str}] {memory}")
@@ -0,0 +1,152 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import unittest
5
+ from types import SimpleNamespace
6
+ from unittest.mock import AsyncMock
7
+
8
+ import httpx
9
+ from supermemory import AsyncSupermemory
10
+
11
+ from supermemory_pipecat.service import SupermemoryPipecatService
12
+ from supermemory_pipecat.utils import format_memories_to_text
13
+
14
+
15
+ class _Context:
16
+ def __init__(self, messages):
17
+ self.messages = messages
18
+
19
+ def get_messages(self):
20
+ return self.messages
21
+
22
+ def add_message(self, message):
23
+ self.messages.append(message)
24
+
25
+
26
+ class TestSupermemoryPipecatService(unittest.IsolatedAsyncioTestCase):
27
+ async def test_v5_reads_and_writes_use_user_id_as_namespace(self) -> None:
28
+ requests = {}
29
+ failed = set()
30
+
31
+ def respond(request):
32
+ requests[request.url.path] = json.loads(request.content)
33
+ if request.url.path.rsplit("/", 1)[-1] in failed:
34
+ return httpx.Response(500)
35
+ if request.url.path.endswith("/profile"):
36
+ payload = {"profile": {"static": [{"memory": "Likes tea"}], "dynamic": []}}
37
+ elif request.url.path.endswith("/search"):
38
+ payload = {
39
+ "results": [
40
+ {
41
+ "id": "mem_123",
42
+ "memory": "Plans a trip",
43
+ "metadata": {},
44
+ "similarity": 0.9,
45
+ "isLatest": True,
46
+ "isInference": False,
47
+ "system": {"updatedAt": "2020-01-01T00:00:00Z"},
48
+ }
49
+ ]
50
+ }
51
+ else:
52
+ payload = {"id": "conversation-456"}
53
+ return httpx.Response(200, json=payload)
54
+
55
+ async with AsyncSupermemory(
56
+ api_key="mock_key",
57
+ base_url="https://example.test",
58
+ http_client=httpx.AsyncClient(transport=httpx.MockTransport(respond)),
59
+ ) as client:
60
+ service = SupermemoryPipecatService(
61
+ api_key="mock_key",
62
+ user_id="user-123",
63
+ session_id="conversation-456",
64
+ params=SupermemoryPipecatService.InputParams(search_limit=500),
65
+ )
66
+ service._supermemory_client = client
67
+ result = await service._retrieve_memories("Where am I going?")
68
+ await service._store_messages([{"role": "user", "content": "Hello"}])
69
+ failed.add("search")
70
+ partial_result = await service._retrieve_memories("Where am I going?")
71
+ failed.clear()
72
+ failed.add("profile")
73
+ search_only_result = await service._retrieve_memories("Where am I going?")
74
+
75
+ self.assertEqual(result["profile"]["static"], ["Likes tea"])
76
+ self.assertEqual(result["search_results"][0].memory, "Plans a trip")
77
+ self.assertEqual(
78
+ set(requests), {"/ns/user-123/profile", "/ns/user-123/search", "/ns/user-123/document"}
79
+ )
80
+ self.assertEqual(requests["/ns/user-123/search"]["query"], "Where am I going?")
81
+ self.assertEqual(requests["/ns/user-123/search"]["limit"], 100)
82
+ self.assertEqual(requests["/ns/user-123/document"]["id"], "conversation-456")
83
+ self.assertEqual(partial_result["profile"]["static"], ["Likes tea"])
84
+ self.assertEqual(partial_result["search_results"], [])
85
+ self.assertEqual(search_only_result["profile"]["static"], [])
86
+ self.assertEqual(search_only_result["search_results"][0].memory, "Plans a trip")
87
+ self.assertIn(
88
+ "[1 Jan, 2020] Plans a trip",
89
+ format_memories_to_text(
90
+ {"static": [], "dynamic": [], "search_results": result["search_results"]}
91
+ ),
92
+ )
93
+
94
+ async def test_retrieve_memories_handles_null_profile(self) -> None:
95
+ service = SupermemoryPipecatService(api_key="mock_key", user_id="new_user_123")
96
+ service._supermemory_client = SimpleNamespace(
97
+ profile=AsyncMock(return_value=SimpleNamespace(profile=None)),
98
+ search=AsyncMock(return_value=SimpleNamespace(results=[])),
99
+ )
100
+
101
+ self.assertEqual(
102
+ await service._retrieve_memories("Hello world"),
103
+ {"profile": {"static": [], "dynamic": []}, "search_results": []},
104
+ )
105
+
106
+ def test_query_mode_keeps_search_fact_also_present_in_profile(self) -> None:
107
+ fact = "User likes machine learning projects"
108
+ service = SupermemoryPipecatService(
109
+ api_key="mock_key",
110
+ user_id="user-123",
111
+ session_id="conversation-456",
112
+ params=SupermemoryPipecatService.InputParams(mode="query"),
113
+ )
114
+ context = _Context([{"role": "user", "content": "What do I like?"}])
115
+ service._enhance_context_with_memories(
116
+ context,
117
+ "What do I like?",
118
+ {
119
+ "profile": {"static": [fact], "dynamic": []},
120
+ "search_results": [SimpleNamespace(memory=fact)],
121
+ },
122
+ )
123
+
124
+ self.assertTrue(any(fact in message.get("content", "") for message in context.messages))
125
+
126
+ def test_system_injection_replaces_stale_block_with_backslash_memory(self) -> None:
127
+ backslash = chr(92)
128
+ fact = "User's repo is at C:" + backslash + "Users" + backslash + "alice"
129
+ service = SupermemoryPipecatService(
130
+ api_key="mock_key",
131
+ user_id="user-123",
132
+ session_id="conversation-456",
133
+ params=SupermemoryPipecatService.InputParams(inject_mode="system"),
134
+ )
135
+ stale = "<user_memories>\nStale fact\n</user_memories>"
136
+ context = _Context(
137
+ [
138
+ {"role": "system", "content": "You are helpful.\n\n" + stale},
139
+ {"role": "user", "content": "Where is my repo?"},
140
+ ]
141
+ )
142
+ service._enhance_context_with_memories(
143
+ context,
144
+ "Where is my repo?",
145
+ {"profile": {"static": [fact], "dynamic": []}, "search_results": []},
146
+ )
147
+
148
+ system_content = context.messages[0]["content"]
149
+ self.assertIn(fact, system_content)
150
+ self.assertNotIn("Stale fact", system_content)
151
+ self.assertIn("You are helpful.", system_content)
152
+ self.assertEqual(system_content.count("<user_memories>"), 1)
@@ -0,0 +1,27 @@
1
+ """Documented public names, like `InputParams`, must import from the package root."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import unittest
6
+
7
+ import supermemory_pipecat
8
+ from supermemory_pipecat import InputParams, SupermemoryPipecatService
9
+
10
+
11
+ class TestPublicExports(unittest.TestCase):
12
+ def test_input_params_is_exported_from_the_package_root(self) -> None:
13
+ self.assertIn("InputParams", supermemory_pipecat.__all__)
14
+ self.assertIs(InputParams, SupermemoryPipecatService.InputParams)
15
+
16
+ def test_documented_configuration_example_constructs(self) -> None:
17
+ params = InputParams(
18
+ mode="full",
19
+ search_limit=10,
20
+ search_threshold=0.1,
21
+ system_prompt="Based on previous conversations:\n\n",
22
+ )
23
+
24
+ self.assertEqual(params.mode, "full")
25
+ self.assertEqual(params.search_limit, 10)
26
+ self.assertEqual(params.search_threshold, 0.1)
27
+ self.assertEqual(params.system_prompt, "Based on previous conversations:\n\n")
@@ -0,0 +1,86 @@
1
+ from __future__ import annotations
2
+
3
+ import unittest
4
+ from types import SimpleNamespace
5
+
6
+ from supermemory_pipecat.utils import (
7
+ deduplicate_memories,
8
+ format_memories_to_text,
9
+ )
10
+
11
+
12
+ class TestSearchResultExtraction(unittest.TestCase):
13
+ """Search can return chunk hits whose `memory` field is empty."""
14
+
15
+ def test_falls_through_to_chunk_when_memory_is_empty(self) -> None:
16
+ result = deduplicate_memories(
17
+ static=[],
18
+ dynamic=[],
19
+ search_results=[{"memory": "", "chunk": "The user's dog is called Rex"}],
20
+ )
21
+
22
+ self.assertEqual(len(result["search_results"]), 1)
23
+ self.assertIn("The user's dog is called Rex", format_memories_to_text(result))
24
+
25
+ def test_falls_through_to_chunk_when_memory_is_whitespace(self) -> None:
26
+ result = deduplicate_memories(
27
+ static=[],
28
+ dynamic=[],
29
+ search_results=[{"memory": " ", "chunk": "Chunk body"}],
30
+ )
31
+
32
+ self.assertEqual(len(result["search_results"]), 1)
33
+ self.assertIn("Chunk body", format_memories_to_text(result))
34
+
35
+ def test_falls_through_on_models_too(self) -> None:
36
+ result = deduplicate_memories(
37
+ static=[],
38
+ dynamic=[],
39
+ search_results=[SimpleNamespace(memory="", chunk="Chunk body")],
40
+ )
41
+
42
+ self.assertEqual(len(result["search_results"]), 1)
43
+ self.assertIn("Chunk body", format_memories_to_text(result))
44
+
45
+ def test_never_renders_an_empty_bullet(self) -> None:
46
+ result = deduplicate_memories(
47
+ static=[],
48
+ dynamic=[],
49
+ search_results=[
50
+ {
51
+ "memory": "",
52
+ "chunk": "Chunk body",
53
+ "updatedAt": "2020-01-01T00:00:00Z",
54
+ }
55
+ ],
56
+ )
57
+
58
+ rendered = format_memories_to_text(result)
59
+ self.assertIn("Chunk body", rendered)
60
+ for line in rendered.splitlines():
61
+ if line.startswith("- "):
62
+ self.assertNotRegex(line, r"^- (\[[^\]]*\] )?$")
63
+
64
+ def test_memory_still_wins_over_chunk(self) -> None:
65
+ result = deduplicate_memories(
66
+ static=[],
67
+ dynamic=[],
68
+ search_results=[{"memory": "Memory body", "chunk": "Chunk body"}],
69
+ )
70
+
71
+ rendered = format_memories_to_text(result)
72
+ self.assertIn("Memory body", rendered)
73
+ self.assertNotIn("Chunk body", rendered)
74
+
75
+ def test_entry_with_no_usable_text_is_still_dropped(self) -> None:
76
+ result = deduplicate_memories(
77
+ static=[],
78
+ dynamic=[],
79
+ search_results=[{"memory": "", "chunk": ""}, {}, None],
80
+ )
81
+
82
+ self.assertEqual(result["search_results"], [])
83
+
84
+
85
+ if __name__ == "__main__":
86
+ unittest.main()
@@ -1,156 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import sys
4
- import types
5
- import unittest
6
- from types import SimpleNamespace
7
- from unittest.mock import AsyncMock
8
-
9
-
10
- def _install_test_stubs() -> None:
11
- if "loguru" not in sys.modules:
12
- loguru_module = types.ModuleType("loguru")
13
-
14
- class _Logger:
15
- def warning(self, *_args, **_kwargs):
16
- return None
17
-
18
- def error(self, *_args, **_kwargs):
19
- return None
20
-
21
- loguru_module.logger = _Logger()
22
- sys.modules["loguru"] = loguru_module
23
-
24
- if "pydantic" not in sys.modules:
25
- pydantic_module = types.ModuleType("pydantic")
26
-
27
- class BaseModel:
28
- def __init__(self, **kwargs):
29
- for key, value in kwargs.items():
30
- setattr(self, key, value)
31
-
32
- def Field(*, default=None, **_kwargs):
33
- return default
34
-
35
- pydantic_module.BaseModel = BaseModel
36
- pydantic_module.Field = Field
37
- sys.modules["pydantic"] = pydantic_module
38
-
39
- if "pipecat" not in sys.modules:
40
- pipecat_module = types.ModuleType("pipecat")
41
- sys.modules["pipecat"] = pipecat_module
42
-
43
- frames_module = types.ModuleType("pipecat.frames.frames")
44
-
45
- class Frame: # pragma: no cover - import stub
46
- pass
47
-
48
- class InputAudioRawFrame: # pragma: no cover - import stub
49
- pass
50
-
51
- class LLMContextFrame: # pragma: no cover - import stub
52
- pass
53
-
54
- class LLMMessagesFrame: # pragma: no cover - import stub
55
- pass
56
-
57
- frames_module.Frame = Frame
58
- frames_module.InputAudioRawFrame = InputAudioRawFrame
59
- frames_module.LLMContextFrame = LLMContextFrame
60
- frames_module.LLMMessagesFrame = LLMMessagesFrame
61
-
62
- llm_context_module = types.ModuleType("pipecat.processors.aggregators.llm_context")
63
-
64
- class LLMContext: # pragma: no cover - import stub
65
- pass
66
-
67
- llm_context_module.LLMContext = LLMContext
68
-
69
- openai_context_module = types.ModuleType(
70
- "pipecat.processors.aggregators.openai_llm_context"
71
- )
72
-
73
- class OpenAILLMContextFrame: # pragma: no cover - import stub
74
- pass
75
-
76
- openai_context_module.OpenAILLMContextFrame = OpenAILLMContextFrame
77
-
78
- frame_processor_module = types.ModuleType("pipecat.processors.frame_processor")
79
-
80
- class FrameDirection: # pragma: no cover - import stub
81
- pass
82
-
83
- class FrameProcessor:
84
- def __init__(self, *args, **kwargs):
85
- return None
86
-
87
- frame_processor_module.FrameDirection = FrameDirection
88
- frame_processor_module.FrameProcessor = FrameProcessor
89
-
90
- sys.modules["pipecat.frames.frames"] = frames_module
91
- sys.modules["pipecat.processors.aggregators.llm_context"] = llm_context_module
92
- sys.modules[
93
- "pipecat.processors.aggregators.openai_llm_context"
94
- ] = openai_context_module
95
- sys.modules["pipecat.processors.frame_processor"] = frame_processor_module
96
-
97
-
98
- _install_test_stubs()
99
-
100
- from supermemory_pipecat.service import SupermemoryPipecatService
101
-
102
-
103
- class _MockSupermemoryClient:
104
- def __init__(self, response):
105
- self.profile = AsyncMock(return_value=response)
106
-
107
-
108
- class TestSupermemoryPipecatNullProfile(unittest.IsolatedAsyncioTestCase):
109
- async def test_retrieve_memories_handles_null_profile(self) -> None:
110
- service = SupermemoryPipecatService(api_key="mock_key", user_id="new_user_123")
111
-
112
- response = SimpleNamespace(profile=None, search_results=None)
113
- service._supermemory_client = _MockSupermemoryClient(response)
114
-
115
- result = await service._retrieve_memories("Hello world")
116
-
117
- self.assertEqual(
118
- result,
119
- {
120
- "profile": {"static": [], "dynamic": []},
121
- "search_results": [],
122
- },
123
- )
124
-
125
- def test_query_mode_keeps_search_fact_also_present_in_profile(self) -> None:
126
- fact = "User likes machine learning projects"
127
- service = SupermemoryPipecatService(
128
- api_key="mock_key",
129
- user_id="user-123",
130
- session_id="conversation-456",
131
- params=SupermemoryPipecatService.InputParams(mode="query"),
132
- )
133
-
134
- class Context:
135
- def __init__(self):
136
- self.messages = [{"role": "user", "content": "What do I like?"}]
137
-
138
- def get_messages(self):
139
- return self.messages
140
-
141
- def add_message(self, message):
142
- self.messages.append(message)
143
-
144
- context = Context()
145
- service._enhance_context_with_memories(
146
- context,
147
- "What do I like?",
148
- {
149
- "profile": {"static": [fact], "dynamic": []},
150
- "search_results": [SimpleNamespace(memory=fact)],
151
- },
152
- )
153
-
154
- self.assertTrue(
155
- any(fact in message.get("content", "") for message in context.messages)
156
- )