pipecat-ormem 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.
- ormem_pipecat/__init__.py +5 -0
- ormem_pipecat/memory.py +391 -0
- pipecat_ormem-0.1.0.dist-info/METADATA +116 -0
- pipecat_ormem-0.1.0.dist-info/RECORD +7 -0
- pipecat_ormem-0.1.0.dist-info/WHEEL +5 -0
- pipecat_ormem-0.1.0.dist-info/licenses/LICENSE +202 -0
- pipecat_ormem-0.1.0.dist-info/top_level.txt +1 -0
ormem_pipecat/memory.py
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
"""Ormem long-term memory for Pipecat voice agents.
|
|
2
|
+
|
|
3
|
+
Drop OrmemMemoryService between the user context aggregator and the LLM.
|
|
4
|
+
On every user turn it:
|
|
5
|
+
|
|
6
|
+
1. looks up what Ormem remembers about this user (``POST /v1/context``) and
|
|
7
|
+
puts it into the LLM context, but gives up after ``recall_timeout``
|
|
8
|
+
seconds so the caller never waits on memory;
|
|
9
|
+
2. saves the new user and assistant messages (``POST /v1/memories``) in the
|
|
10
|
+
background, so saving never delays the reply.
|
|
11
|
+
|
|
12
|
+
Retries are safe: every message carries an idempotency key, so Ormem
|
|
13
|
+
skips anything it has already stored.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import asyncio
|
|
17
|
+
import json
|
|
18
|
+
from datetime import datetime, timezone
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
import aiohttp
|
|
22
|
+
from loguru import logger
|
|
23
|
+
from pydantic import BaseModel, Field
|
|
24
|
+
|
|
25
|
+
from pipecat.frames.frames import Frame, LLMContextFrame
|
|
26
|
+
from pipecat.processors.aggregators.llm_context import LLMContext, LLMSpecificMessage
|
|
27
|
+
from pipecat.processors.frame_processor import FrameDirection, FrameProcessor
|
|
28
|
+
|
|
29
|
+
DEFAULT_BASE_URL = "https://app.ormem.app"
|
|
30
|
+
_MEMORY_TAG = "[ormem]"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class OrmemMemoryService(FrameProcessor):
|
|
34
|
+
"""Gives a Pipecat agent memory of each user across calls, via Ormem."""
|
|
35
|
+
|
|
36
|
+
class InputParams(BaseModel):
|
|
37
|
+
"""Settings for OrmemMemoryService.
|
|
38
|
+
|
|
39
|
+
Parameters:
|
|
40
|
+
recall_timeout: Seconds to wait for memories before replying
|
|
41
|
+
without them. Keep this low for voice.
|
|
42
|
+
evidence_budget: Upper bound on memory tokens per turn (Ormem's
|
|
43
|
+
``evidence_budget``; 500 or more).
|
|
44
|
+
store_timeout: Seconds allowed for a background save.
|
|
45
|
+
memory_prefix: Text placed before the memories in the context.
|
|
46
|
+
add_as_system_message: Insert memories as a "developer" message
|
|
47
|
+
(default) instead of a "user" message.
|
|
48
|
+
position: Index to insert the memory message at. Default (None):
|
|
49
|
+
just before the latest user message, so memories sit next to
|
|
50
|
+
the question and the earlier conversation is left unchanged.
|
|
51
|
+
agent_name: Speaker name stored for assistant messages.
|
|
52
|
+
max_memories: Optionally trim to N memories per turn, keeping
|
|
53
|
+
``"match": true`` hits first. Off by default: Ormem's list is
|
|
54
|
+
grouped by conversation, so cutting by position can drop a
|
|
55
|
+
correction (which always comes after what it corrects).
|
|
56
|
+
conflict_note: Told to the LLM so corrections win over the
|
|
57
|
+
memories they replace.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
recall_timeout: float = Field(default=1.5, gt=0)
|
|
61
|
+
evidence_budget: int = Field(default=800, ge=500)
|
|
62
|
+
store_timeout: float = Field(default=30.0, gt=0)
|
|
63
|
+
memory_prefix: str = Field(
|
|
64
|
+
default="What you remember about this user from earlier conversations:\n"
|
|
65
|
+
)
|
|
66
|
+
add_as_system_message: bool = True
|
|
67
|
+
position: int | None = Field(default=None, ge=0)
|
|
68
|
+
agent_name: str = "assistant"
|
|
69
|
+
max_memories: int | None = Field(default=None, ge=1)
|
|
70
|
+
conflict_note: str = Field(
|
|
71
|
+
default="If two memories disagree, the more recent one (later date) is the current truth."
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
def __init__(
|
|
75
|
+
self,
|
|
76
|
+
*,
|
|
77
|
+
api_key: str,
|
|
78
|
+
owner: str,
|
|
79
|
+
session_id: str,
|
|
80
|
+
user_name: str | None = None,
|
|
81
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
82
|
+
params: InputParams | None = None,
|
|
83
|
+
session: aiohttp.ClientSession | None = None,
|
|
84
|
+
):
|
|
85
|
+
"""Create the service.
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
api_key: Ormem API key (keep it on your server).
|
|
89
|
+
owner: Stable ID of the user whose memories these are, e.g. the
|
|
90
|
+
caller's phone number or your user ID.
|
|
91
|
+
session_id: ID of this call or conversation.
|
|
92
|
+
user_name: Speaker name stored for the user's messages.
|
|
93
|
+
base_url: Ormem API base URL.
|
|
94
|
+
params: Tuning options.
|
|
95
|
+
session: Optional shared aiohttp session.
|
|
96
|
+
"""
|
|
97
|
+
super().__init__()
|
|
98
|
+
if not api_key:
|
|
99
|
+
raise ValueError("api_key is required")
|
|
100
|
+
if not owner or "~" in owner or len(owner) > 200:
|
|
101
|
+
raise ValueError("owner must be 1-200 characters and must not contain '~'")
|
|
102
|
+
self._api_key = api_key
|
|
103
|
+
self._owner = owner
|
|
104
|
+
self._session_id = session_id
|
|
105
|
+
self._user_name = user_name or owner
|
|
106
|
+
self._base_url = base_url.rstrip("/")
|
|
107
|
+
self._params = params or OrmemMemoryService.InputParams()
|
|
108
|
+
self._session = session
|
|
109
|
+
self._owns_session = session is None
|
|
110
|
+
self._stored_count = 0
|
|
111
|
+
self._last_query: str | None = None
|
|
112
|
+
self._pending: set[asyncio.Task] = set()
|
|
113
|
+
|
|
114
|
+
# ---- HTTP -----------------------------------------------------------
|
|
115
|
+
|
|
116
|
+
async def _http(self) -> aiohttp.ClientSession:
|
|
117
|
+
if self._session is None or self._session.closed:
|
|
118
|
+
self._session = aiohttp.ClientSession(trust_env=True)
|
|
119
|
+
self._owns_session = True
|
|
120
|
+
return self._session
|
|
121
|
+
|
|
122
|
+
async def _post(self, path: str, body: dict[str, Any], timeout: float) -> dict[str, Any]:
|
|
123
|
+
http = await self._http()
|
|
124
|
+
async with http.post(
|
|
125
|
+
f"{self._base_url}{path}",
|
|
126
|
+
json=body,
|
|
127
|
+
headers={"Authorization": f"Bearer {self._api_key}"},
|
|
128
|
+
timeout=aiohttp.ClientTimeout(total=timeout),
|
|
129
|
+
) as resp:
|
|
130
|
+
data = await resp.json(content_type=None)
|
|
131
|
+
if resp.status >= 400:
|
|
132
|
+
detail = data.get("detail") if isinstance(data, dict) else data
|
|
133
|
+
raise RuntimeError(f"Ormem {path} returned {resp.status}: {detail}")
|
|
134
|
+
return data
|
|
135
|
+
|
|
136
|
+
async def cleanup(self):
|
|
137
|
+
"""Finish pending saves (so the end of a call isn't lost), then close."""
|
|
138
|
+
await super().cleanup()
|
|
139
|
+
if self._pending:
|
|
140
|
+
done, pending = await asyncio.wait(self._pending, timeout=self._params.store_timeout)
|
|
141
|
+
for task in pending:
|
|
142
|
+
task.cancel()
|
|
143
|
+
if pending:
|
|
144
|
+
logger.warning(f"Ormem: {len(pending)} save(s) still running at shutdown were cancelled")
|
|
145
|
+
if self._owns_session and self._session and not self._session.closed:
|
|
146
|
+
await self._session.close()
|
|
147
|
+
|
|
148
|
+
# ---- Recall ---------------------------------------------------------
|
|
149
|
+
|
|
150
|
+
async def fetch_context(self, question: str) -> dict[str, Any] | None:
|
|
151
|
+
"""Ask Ormem for memories relevant to ``question``.
|
|
152
|
+
|
|
153
|
+
Returns None if Ormem is slow (beyond ``recall_timeout``) or fails,
|
|
154
|
+
so the agent can always reply without memory.
|
|
155
|
+
"""
|
|
156
|
+
try:
|
|
157
|
+
return await asyncio.wait_for(
|
|
158
|
+
self._post(
|
|
159
|
+
"/v1/context",
|
|
160
|
+
{
|
|
161
|
+
"owner": self._owner,
|
|
162
|
+
"question": question,
|
|
163
|
+
"evidence_budget": self._params.evidence_budget,
|
|
164
|
+
},
|
|
165
|
+
timeout=self._params.recall_timeout + 1,
|
|
166
|
+
),
|
|
167
|
+
timeout=self._params.recall_timeout,
|
|
168
|
+
)
|
|
169
|
+
except asyncio.TimeoutError:
|
|
170
|
+
logger.warning(
|
|
171
|
+
f"Ormem recall took over {self._params.recall_timeout}s; replying without memory"
|
|
172
|
+
)
|
|
173
|
+
except Exception as e:
|
|
174
|
+
logger.error(f"Ormem recall failed: {e}")
|
|
175
|
+
return None
|
|
176
|
+
|
|
177
|
+
# Evidence lists in a /v1/context response, most distilled first.
|
|
178
|
+
_EVIDENCE_KEYS = (
|
|
179
|
+
"facts",
|
|
180
|
+
"entity_memories",
|
|
181
|
+
"raw_memories",
|
|
182
|
+
"expanded_episodes",
|
|
183
|
+
"episode_candidates",
|
|
184
|
+
"notes",
|
|
185
|
+
)
|
|
186
|
+
_TEXT_KEYS = ("text", "fact", "summary", "body", "content", "note", "memory")
|
|
187
|
+
_WHEN_KEYS = ("timestamp", "happened_at", "when", "date")
|
|
188
|
+
|
|
189
|
+
@classmethod
|
|
190
|
+
def _format_item(cls, item: Any, exclude: str | None = None) -> str | None:
|
|
191
|
+
if isinstance(item, str):
|
|
192
|
+
if exclude and item.strip() == exclude.strip():
|
|
193
|
+
return None
|
|
194
|
+
return f"- {item.strip()}" if item.strip() else None
|
|
195
|
+
if not isinstance(item, dict):
|
|
196
|
+
return f"- {json.dumps(item, ensure_ascii=False)}"
|
|
197
|
+
text = next((item[k] for k in cls._TEXT_KEYS if isinstance(item.get(k), str) and item[k].strip()), None)
|
|
198
|
+
if text is None:
|
|
199
|
+
return f"- {json.dumps(item, ensure_ascii=False)[:500]}"
|
|
200
|
+
if exclude and text.strip() == exclude.strip():
|
|
201
|
+
return None
|
|
202
|
+
meta = []
|
|
203
|
+
if item.get("speaker"):
|
|
204
|
+
meta.append(str(item["speaker"]))
|
|
205
|
+
when = next((item[k] for k in cls._WHEN_KEYS if item.get(k)), None)
|
|
206
|
+
if when:
|
|
207
|
+
meta.append(str(when))
|
|
208
|
+
if item.get("received_from"):
|
|
209
|
+
meta.append(f"received from {item['received_from']}")
|
|
210
|
+
if item.get("fidelity") in ("gist", "trace"):
|
|
211
|
+
meta.append(f"{item['fidelity']}, not a quote")
|
|
212
|
+
return f"- {text.strip()}" + (f" ({', '.join(meta)})" if meta else "")
|
|
213
|
+
|
|
214
|
+
@classmethod
|
|
215
|
+
def format_evidence(
|
|
216
|
+
cls,
|
|
217
|
+
data: dict[str, Any],
|
|
218
|
+
exclude: str | None = None,
|
|
219
|
+
max_memories: int | None = None,
|
|
220
|
+
conflict_note: str | None = None,
|
|
221
|
+
) -> str:
|
|
222
|
+
"""Turn a /v1/context response into plain text for the LLM.
|
|
223
|
+
|
|
224
|
+
Lists memories oldest to newest with dates, so a correction reads
|
|
225
|
+
after the memory it corrects. If ``max_memories`` is set, real hits
|
|
226
|
+
(``"match": true``) are kept before context lines. ``exclude`` drops the user's current message if
|
|
227
|
+
it was already stored.
|
|
228
|
+
"""
|
|
229
|
+
picked: list[tuple[int, str, str]] = [] # (position, when, line)
|
|
230
|
+
hit_ranks: set[int] = set()
|
|
231
|
+
seen: set[str] = set()
|
|
232
|
+
|
|
233
|
+
def add(item: Any):
|
|
234
|
+
line = cls._format_item(item, exclude)
|
|
235
|
+
if not line or line in seen:
|
|
236
|
+
return
|
|
237
|
+
seen.add(line)
|
|
238
|
+
when = ""
|
|
239
|
+
if isinstance(item, dict):
|
|
240
|
+
when = str(next((item[k] for k in cls._WHEN_KEYS if item.get(k)), ""))
|
|
241
|
+
if item.get("match"):
|
|
242
|
+
hit_ranks.add(len(picked))
|
|
243
|
+
picked.append((len(picked), when, line))
|
|
244
|
+
|
|
245
|
+
evidence = data.get("evidence")
|
|
246
|
+
if isinstance(evidence, str) and evidence.strip():
|
|
247
|
+
picked.append((0, "", evidence.strip()))
|
|
248
|
+
elif isinstance(evidence, dict):
|
|
249
|
+
keys = list(cls._EVIDENCE_KEYS) + [
|
|
250
|
+
k for k, v in evidence.items() if k not in cls._EVIDENCE_KEYS and isinstance(v, list)
|
|
251
|
+
]
|
|
252
|
+
for key in keys:
|
|
253
|
+
for item in evidence.get(key) or []:
|
|
254
|
+
add(item)
|
|
255
|
+
elif isinstance(evidence, list):
|
|
256
|
+
for item in evidence:
|
|
257
|
+
add(item)
|
|
258
|
+
|
|
259
|
+
if not picked:
|
|
260
|
+
return ""
|
|
261
|
+
if max_memories and len(picked) > max_memories:
|
|
262
|
+
# Keep real hits ("match": true) first, then context lines, in
|
|
263
|
+
# Ormem's order. Never cut by list position alone: the list is
|
|
264
|
+
# grouped by conversation, not ranked.
|
|
265
|
+
hits = [p for p in picked if p[0] in hit_ranks]
|
|
266
|
+
rest = [p for p in picked if p[0] not in hit_ranks]
|
|
267
|
+
picked = (hits + rest)[:max_memories]
|
|
268
|
+
# Oldest first; undated items keep Ormem's order at the end.
|
|
269
|
+
picked.sort(key=lambda p: (p[1] == "", p[1], p[0]))
|
|
270
|
+
|
|
271
|
+
lines: list[str] = []
|
|
272
|
+
instructions = data.get("instructions")
|
|
273
|
+
if isinstance(instructions, str) and instructions.strip():
|
|
274
|
+
lines.append(instructions.strip())
|
|
275
|
+
if conflict_note:
|
|
276
|
+
lines.append(conflict_note)
|
|
277
|
+
lines.append("Memories, oldest first:")
|
|
278
|
+
lines.extend(p[2] for p in picked)
|
|
279
|
+
hints = data.get("tone_hints")
|
|
280
|
+
if isinstance(hints, list) and hints:
|
|
281
|
+
lines.append("Tone hints: " + "; ".join(str(h) for h in hints))
|
|
282
|
+
return "\n".join(lines)
|
|
283
|
+
|
|
284
|
+
def _insert_memories(self, context: LLMContext, text: str):
|
|
285
|
+
messages = [
|
|
286
|
+
m
|
|
287
|
+
for m in context.get_messages()
|
|
288
|
+
if isinstance(m, LLMSpecificMessage)
|
|
289
|
+
or not (isinstance(m.get("content"), str) and m["content"].startswith(_MEMORY_TAG))
|
|
290
|
+
]
|
|
291
|
+
role = "developer" if self._params.add_as_system_message else "user"
|
|
292
|
+
message = {"role": role, "content": f"{_MEMORY_TAG} {self._params.memory_prefix}{text}"}
|
|
293
|
+
if self._params.position is None:
|
|
294
|
+
# Just before the latest user message: close to the question, and the
|
|
295
|
+
# earlier conversation stays an unchanged prefix (good for prompt caching).
|
|
296
|
+
pos = len(messages)
|
|
297
|
+
for i in range(len(messages) - 1, -1, -1):
|
|
298
|
+
m = messages[i]
|
|
299
|
+
if not isinstance(m, LLMSpecificMessage) and m.get("role") == "user":
|
|
300
|
+
pos = i
|
|
301
|
+
break
|
|
302
|
+
else:
|
|
303
|
+
pos = max(0, min(self._params.position, len(messages)))
|
|
304
|
+
messages.insert(pos, message)
|
|
305
|
+
context.set_messages(messages)
|
|
306
|
+
|
|
307
|
+
# ---- Store ----------------------------------------------------------
|
|
308
|
+
|
|
309
|
+
def _new_messages(self, context: LLMContext) -> list[dict[str, Any]]:
|
|
310
|
+
convo = [
|
|
311
|
+
m
|
|
312
|
+
for m in context.get_messages()
|
|
313
|
+
if not isinstance(m, LLMSpecificMessage)
|
|
314
|
+
and m.get("role") in ("user", "assistant")
|
|
315
|
+
and isinstance(m.get("content"), str)
|
|
316
|
+
and not m["content"].startswith(_MEMORY_TAG)
|
|
317
|
+
and m["content"].strip()
|
|
318
|
+
]
|
|
319
|
+
now = datetime.now(timezone.utc).isoformat()
|
|
320
|
+
out = []
|
|
321
|
+
for i, m in enumerate(convo[self._stored_count :], start=self._stored_count):
|
|
322
|
+
out.append(
|
|
323
|
+
{
|
|
324
|
+
"body": m["content"],
|
|
325
|
+
"speaker": self._user_name if m["role"] == "user" else self._params.agent_name,
|
|
326
|
+
"happened_at": now,
|
|
327
|
+
"session_id": self._session_id,
|
|
328
|
+
"idempotency_key": f"{self._session_id}:{i}",
|
|
329
|
+
}
|
|
330
|
+
)
|
|
331
|
+
self._stored_count = len(convo)
|
|
332
|
+
return out
|
|
333
|
+
|
|
334
|
+
async def _store(self, memories: list[dict[str, Any]]):
|
|
335
|
+
try:
|
|
336
|
+
for start in range(0, len(memories), 50):
|
|
337
|
+
result = await self._post(
|
|
338
|
+
"/v1/memories",
|
|
339
|
+
{"owner": self._owner, "memories": memories[start : start + 50]},
|
|
340
|
+
timeout=self._params.store_timeout,
|
|
341
|
+
)
|
|
342
|
+
logger.debug(f"Ormem stored {result.get('stored')} messages")
|
|
343
|
+
except Exception as e:
|
|
344
|
+
logger.error(f"Ormem store failed: {e}")
|
|
345
|
+
|
|
346
|
+
# ---- Pipeline -------------------------------------------------------
|
|
347
|
+
|
|
348
|
+
async def process_frame(self, frame: Frame, direction: FrameDirection):
|
|
349
|
+
"""Add memories to each LLM context frame and save new messages."""
|
|
350
|
+
await super().process_frame(frame, direction)
|
|
351
|
+
|
|
352
|
+
if not isinstance(frame, LLMContextFrame):
|
|
353
|
+
await self.push_frame(frame, direction)
|
|
354
|
+
return
|
|
355
|
+
|
|
356
|
+
context = frame.context
|
|
357
|
+
try:
|
|
358
|
+
latest = None
|
|
359
|
+
for m in reversed(context.get_messages()):
|
|
360
|
+
if isinstance(m, LLMSpecificMessage):
|
|
361
|
+
continue
|
|
362
|
+
if m.get("role") == "user" and isinstance(m.get("content"), str):
|
|
363
|
+
if not m["content"].startswith(_MEMORY_TAG):
|
|
364
|
+
latest = m["content"]
|
|
365
|
+
break
|
|
366
|
+
|
|
367
|
+
# Recall first, then save: if the save landed first, the user's
|
|
368
|
+
# current question would come back as one of its own "memories".
|
|
369
|
+
to_store = self._new_messages(context)
|
|
370
|
+
|
|
371
|
+
if latest and latest != self._last_query:
|
|
372
|
+
self._last_query = latest
|
|
373
|
+
data = await self.fetch_context(latest)
|
|
374
|
+
if data:
|
|
375
|
+
text = self.format_evidence(
|
|
376
|
+
data,
|
|
377
|
+
exclude=latest,
|
|
378
|
+
max_memories=self._params.max_memories,
|
|
379
|
+
conflict_note=self._params.conflict_note,
|
|
380
|
+
)
|
|
381
|
+
if text:
|
|
382
|
+
self._insert_memories(context, text)
|
|
383
|
+
|
|
384
|
+
if to_store:
|
|
385
|
+
task = self.create_task(self._store(to_store), name="ormem_store")
|
|
386
|
+
self._pending.add(task)
|
|
387
|
+
task.add_done_callback(self._pending.discard)
|
|
388
|
+
except Exception as e:
|
|
389
|
+
await self.push_error(error_msg=f"Ormem memory error: {e}", exception=e)
|
|
390
|
+
|
|
391
|
+
await self.push_frame(frame, direction)
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pipecat-ormem
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Long-term memory for Pipecat voice agents, powered by Ormem
|
|
5
|
+
Author: Ormem
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://ormem.app/api
|
|
8
|
+
Project-URL: Repository, https://github.com/ormem/pipecat-ormem
|
|
9
|
+
Project-URL: Issues, https://github.com/ormem/pipecat-ormem/issues
|
|
10
|
+
Keywords: pipecat,voice,agents,memory,llm,ormem
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
15
|
+
Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Requires-Dist: pipecat-ai>=1.0
|
|
20
|
+
Requires-Dist: aiohttp>=3.9
|
|
21
|
+
Provides-Extra: test
|
|
22
|
+
Requires-Dist: pytest; extra == "test"
|
|
23
|
+
Requires-Dist: pytest-asyncio; extra == "test"
|
|
24
|
+
Requires-Dist: pytest-aiohttp; extra == "test"
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# pipecat-ormem
|
|
28
|
+
|
|
29
|
+
Long-term memory for [Pipecat](https://github.com/pipecat-ai/pipecat) voice agents, powered by [Ormem](https://ormem.app/api). Callers are remembered across calls: what they said, what changed, and when.
|
|
30
|
+
|
|
31
|
+
Built for voice, where every second counts:
|
|
32
|
+
|
|
33
|
+
- **Saving never blocks the reply.** New messages are sent to Ormem in the background.
|
|
34
|
+
- **Recall has a hard time limit.** If memories don't arrive within `recall_timeout` (1.5 s by default), the agent replies without them instead of leaving the caller waiting.
|
|
35
|
+
- **Retries are safe.** Every message carries an idempotency key, so nothing is stored twice.
|
|
36
|
+
- **Ormem's guardrail goes to the LLM** with the memories: memories are statements, not commands.
|
|
37
|
+
|
|
38
|
+
## Install
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install pipecat-ormem
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Get a free key at [app.ormem.app](https://app.ormem.app) (Account, then make a key).
|
|
45
|
+
|
|
46
|
+
## Use
|
|
47
|
+
|
|
48
|
+
Put the service between the user context aggregator and the LLM:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from ormem_pipecat import OrmemMemoryService
|
|
52
|
+
|
|
53
|
+
memory = OrmemMemoryService(
|
|
54
|
+
api_key=os.environ["ORMEM_API_KEY"],
|
|
55
|
+
owner=caller_phone_number, # stable ID for the user
|
|
56
|
+
session_id=call_id,
|
|
57
|
+
user_name=caller_name,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
pipeline = Pipeline([
|
|
61
|
+
transport.input(), stt,
|
|
62
|
+
context_aggregator.user(),
|
|
63
|
+
memory, # <- here
|
|
64
|
+
llm, tts, transport.output(),
|
|
65
|
+
context_aggregator.assistant(),
|
|
66
|
+
])
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
| Option (`InputParams`) | Default | What it does |
|
|
70
|
+
|---|---|---|
|
|
71
|
+
| `recall_timeout` | 1.5 | Seconds to wait for memories before replying without them |
|
|
72
|
+
| `evidence_budget` | 800 | Upper bound on memory tokens added per turn (500 or more) |
|
|
73
|
+
| `store_timeout` | 30 | Seconds allowed for a background save |
|
|
74
|
+
| `add_as_system_message` | True | Add memories as a "developer" message instead of "user" |
|
|
75
|
+
| `position` | before the latest question | Where in the context the memory message goes. By default it goes just before the latest user message, so it sits next to the question (Anthropic, Bedrock and Gemini merge it into that turn) and the earlier conversation stays unchanged for prompt caching |
|
|
76
|
+
| `agent_name` | "assistant" | Speaker name stored for the agent's messages |
|
|
77
|
+
| `max_memories` | None | Optionally cap memories per turn. Off by default. If set, `"match": true` lines are kept first, never the first N in list order |
|
|
78
|
+
| `conflict_note` | "If two memories disagree, the more recent one…" | Tells the LLM that corrections win |
|
|
79
|
+
|
|
80
|
+
## How it works
|
|
81
|
+
|
|
82
|
+
On each user turn the service:
|
|
83
|
+
1. finds the newest user message and calls `POST /v1/context` (an evidence lookup) with it;
|
|
84
|
+
2. lists the memories Ormem returns oldest to newest with dates (so a correction reads after the memory it corrects), and replaces last turn's memory message with it, so memories don't pile up in the context;
|
|
85
|
+
3. then sends any user or assistant messages not yet saved to `POST /v1/memories`, in the background. Saving after the lookup means the user's current question never comes back as one of its own memories. Pending saves are finished when the call ends.
|
|
86
|
+
|
|
87
|
+
It uses `/v1/context`, not `/v1/recall`, so your own LLM writes the reply and no second model call is added to the voice loop.
|
|
88
|
+
|
|
89
|
+
## Notes
|
|
90
|
+
|
|
91
|
+
- Messages are numbered within a `session_id` for idempotency. Use a new `session_id` for each call.
|
|
92
|
+
- If your pipeline trims or summarizes the context mid-call, create the service per call (the usual pattern) so numbering starts fresh.
|
|
93
|
+
|
|
94
|
+
## Measured on the live API (27 Nov 2026)
|
|
95
|
+
|
|
96
|
+
Same 20 questions at 60 and at 120 stored memories, spread over a month in dated sessions, with look-alike distractors and 4 corrections. Measured after Ormem's background notes had been built, with the default lookup size:
|
|
97
|
+
- right memory returned as a hit: 20/20 at both sizes; every correction came back alongside the memory it replaces;
|
|
98
|
+
- `/v1/context` time: median about 0.85 s, slowest 1.07 s, at both sizes (about 0.3 s on a near-empty store);
|
|
99
|
+
- reply size: about 1,600 tokens of memory per lookup.
|
|
100
|
+
|
|
101
|
+
Each lookup returns at most the 10 best hits plus the lines around them, and up to 30 notes, within a size limit, so its size doesn't grow with the store.
|
|
102
|
+
|
|
103
|
+
Run the scale test yourself: `ORMEM_API_KEY=... RUN=60 python tests/eval_scale.py` (and `RUN=120`).
|
|
104
|
+
|
|
105
|
+
## Tests
|
|
106
|
+
|
|
107
|
+
```bash
|
|
108
|
+
pip install -e ".[test]"
|
|
109
|
+
pytest
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
The tests run against a fake Ormem server and cover: memories added to the context (just before the latest question), background saving, slow-recall fallback, error pass-through, no duplicate memory messages, and idempotency keys.
|
|
113
|
+
|
|
114
|
+
## Licence
|
|
115
|
+
|
|
116
|
+
Apache-2.0
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
ormem_pipecat/__init__.py,sha256=AWOR9camPWQOYikcD3RAYhU9nfP-dX3eajq8y4dnOs0,116
|
|
2
|
+
ormem_pipecat/memory.py,sha256=eDWz1vpRZZIB52IpUOra6LoR1rj2nvkstuGnwgSkbPU,16487
|
|
3
|
+
pipecat_ormem-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
4
|
+
pipecat_ormem-0.1.0.dist-info/METADATA,sha256=8ONUwgh4i_MKEuvo0s_PwqkmeoBQ4Q87w_Uxs5L5wJM,5491
|
|
5
|
+
pipecat_ormem-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
6
|
+
pipecat_ormem-0.1.0.dist-info/top_level.txt,sha256=8j9SHZccL-qsgLTXhAPgjDWPf5tpmV3qEv-9xG6JLjc,14
|
|
7
|
+
pipecat_ormem-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ormem_pipecat
|