supermemory-cartesia 0.1.1__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.
- supermemory_cartesia-0.1.1/.gitignore +45 -0
- supermemory_cartesia-0.1.1/PKG-INFO +263 -0
- supermemory_cartesia-0.1.1/README.md +232 -0
- supermemory_cartesia-0.1.1/pyproject.toml +78 -0
- supermemory_cartesia-0.1.1/src/supermemory_cartesia/__init__.py +67 -0
- supermemory_cartesia-0.1.1/src/supermemory_cartesia/agent.py +446 -0
- supermemory_cartesia-0.1.1/src/supermemory_cartesia/exceptions.py +58 -0
- supermemory_cartesia-0.1.1/src/supermemory_cartesia/utils.py +134 -0
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
|
2
|
+
.open-next/
|
|
3
|
+
.sentryclirc
|
|
4
|
+
drizzle.config.ts
|
|
5
|
+
|
|
6
|
+
# Dependencies
|
|
7
|
+
node_modules
|
|
8
|
+
.pnp
|
|
9
|
+
.pnp.js
|
|
10
|
+
|
|
11
|
+
# Local env files
|
|
12
|
+
.env
|
|
13
|
+
.env.local
|
|
14
|
+
.env.development.local
|
|
15
|
+
.env.test.local
|
|
16
|
+
.env.production.local
|
|
17
|
+
|
|
18
|
+
# Testing
|
|
19
|
+
coverage
|
|
20
|
+
|
|
21
|
+
# Turbo
|
|
22
|
+
.turbo
|
|
23
|
+
|
|
24
|
+
# Vercel
|
|
25
|
+
.vercel
|
|
26
|
+
|
|
27
|
+
# Build Outputs
|
|
28
|
+
.next/
|
|
29
|
+
out/
|
|
30
|
+
build
|
|
31
|
+
dist
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# Debug
|
|
35
|
+
npm-debug.log*
|
|
36
|
+
yarn-debug.log*
|
|
37
|
+
yarn-error.log*
|
|
38
|
+
|
|
39
|
+
# Misc
|
|
40
|
+
.DS_Store
|
|
41
|
+
*.pem
|
|
42
|
+
.claude
|
|
43
|
+
.venv
|
|
44
|
+
.arch
|
|
45
|
+
__pycache__
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: supermemory-cartesia
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Supermemory integration for Cartesia Line - memory-enhanced voice agents
|
|
5
|
+
Project-URL: Homepage, https://supermemory.ai
|
|
6
|
+
Project-URL: Documentation, https://docs.supermemory.ai
|
|
7
|
+
Project-URL: Repository, https://github.com/supermemoryai/supermemory
|
|
8
|
+
Author-email: Supermemory <support@supermemory.ai>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
Keywords: cartesia,conversational-ai,line,llm,memory,supermemory,voice-ai
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Requires-Dist: cartesia-line>=0.2.0
|
|
21
|
+
Requires-Dist: loguru>=0.7.3
|
|
22
|
+
Requires-Dist: pydantic>=2.10.0
|
|
23
|
+
Requires-Dist: supermemory>=3.16.0
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: black>=24.8.0; extra == 'dev'
|
|
26
|
+
Requires-Dist: isort>=5.13.2; extra == 'dev'
|
|
27
|
+
Requires-Dist: mypy>=1.14.1; extra == 'dev'
|
|
28
|
+
Requires-Dist: pytest-asyncio>=0.24.0; extra == 'dev'
|
|
29
|
+
Requires-Dist: pytest>=8.3.5; extra == 'dev'
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+
# Supermemory Cartesia SDK
|
|
33
|
+
|
|
34
|
+
Memory-enhanced voice agents with [Supermemory](https://supermemory.ai) and [Cartesia Line](https://cartesia.ai/agents).
|
|
35
|
+
|
|
36
|
+
## Installation
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install supermemory-cartesia
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Quick Start
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
import os
|
|
46
|
+
from line.llm_agent import LlmAgent, LlmConfig
|
|
47
|
+
from line.voice_agent_app import VoiceAgentApp
|
|
48
|
+
from supermemory_cartesia import SupermemoryCartesiaAgent
|
|
49
|
+
|
|
50
|
+
async def get_agent(env, call_request):
|
|
51
|
+
# Extract container_tag from call metadata (typically user ID)
|
|
52
|
+
container_tag = call_request.metadata.get("user_id", "default-user")
|
|
53
|
+
|
|
54
|
+
# Create base LLM agent
|
|
55
|
+
base_agent = LlmAgent(
|
|
56
|
+
model="gemini/gemini-2.5-flash-preview-09-2025",
|
|
57
|
+
config=LlmConfig(
|
|
58
|
+
system_prompt="You are a helpful voice assistant with memory.",
|
|
59
|
+
introduction="Hello! Great to talk with you again!"
|
|
60
|
+
)
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
# Wrap with Supermemory
|
|
64
|
+
memory_agent = SupermemoryCartesiaAgent(
|
|
65
|
+
agent=base_agent,
|
|
66
|
+
api_key=os.getenv("SUPERMEMORY_API_KEY"),
|
|
67
|
+
container_tag=container_tag,
|
|
68
|
+
custom_id=call_request.call_id,
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
return memory_agent
|
|
72
|
+
|
|
73
|
+
# Create voice agent app
|
|
74
|
+
app = VoiceAgentApp(get_agent=get_agent)
|
|
75
|
+
|
|
76
|
+
if __name__ == "__main__":
|
|
77
|
+
app.run(host="0.0.0.0", port=8000)
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Configuration
|
|
81
|
+
|
|
82
|
+
### Parameters
|
|
83
|
+
|
|
84
|
+
| Parameter | Type | Required | Description |
|
|
85
|
+
| --------------- | ------------ | -------- | ------------------------------------------------------------------ |
|
|
86
|
+
| `agent` | LlmAgent | **Yes** | The Cartesia Line agent to wrap |
|
|
87
|
+
| `container_tag` | str | **Yes** | Primary container tag for memory scoping (e.g., user ID) |
|
|
88
|
+
| `custom_id` | str | **Yes** | Custom ID for grouping conversation messages into a single document|
|
|
89
|
+
| `add_memory` | Literal | No | Memory persistence mode: "always" (default) or "never" |
|
|
90
|
+
| `container_tags`| List[str] | No | Additional container tags for organization (e.g., ["org", "prod"]) |
|
|
91
|
+
| `api_key` | str | No | Supermemory API key (or set `SUPERMEMORY_API_KEY` env var) |
|
|
92
|
+
| `config` | MemoryConfig | No | Advanced configuration |
|
|
93
|
+
| `base_url` | str | No | Custom API endpoint |
|
|
94
|
+
|
|
95
|
+
### Advanced Configuration
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
from supermemory_cartesia import SupermemoryCartesiaAgent
|
|
99
|
+
|
|
100
|
+
memory_agent = SupermemoryCartesiaAgent(
|
|
101
|
+
agent=base_agent,
|
|
102
|
+
container_tag="user-123",
|
|
103
|
+
custom_id="conversation-456",
|
|
104
|
+
add_memory="always", # "always" (default) or "never"
|
|
105
|
+
container_tags=["org-acme", "prod"], # Optional: additional tags
|
|
106
|
+
config=SupermemoryCartesiaAgent.MemoryConfig(
|
|
107
|
+
search_limit=10, # Max memories to retrieve
|
|
108
|
+
search_threshold=0.1, # Similarity threshold
|
|
109
|
+
mode="full", # "profile", "query", or "full"
|
|
110
|
+
system_prompt="Based on previous conversations, I recall:\n\n",
|
|
111
|
+
),
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
# Read-only mode - retrieve memories but don't save new ones
|
|
115
|
+
read_only_agent = SupermemoryCartesiaAgent(
|
|
116
|
+
agent=base_agent,
|
|
117
|
+
container_tag="user-123",
|
|
118
|
+
custom_id="conversation-456",
|
|
119
|
+
add_memory="never", # Only retrieve, don't save
|
|
120
|
+
)
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
### Memory Modes
|
|
124
|
+
|
|
125
|
+
| Mode | Static Profile | Dynamic Profile | Search Results |
|
|
126
|
+
| ----------- | -------------- | --------------- | -------------- |
|
|
127
|
+
| `"profile"` | Yes | Yes | No |
|
|
128
|
+
| `"query"` | No | No | Yes |
|
|
129
|
+
| `"full"` | Yes | Yes | Yes |
|
|
130
|
+
|
|
131
|
+
## How It Works
|
|
132
|
+
|
|
133
|
+
1. **Intercepts events** - Listens for `UserTurnEnded` events from Cartesia Line
|
|
134
|
+
2. **Retrieves memories** - Queries Supermemory `/v4/profile` API with user's message
|
|
135
|
+
3. **Enriches context** - Adds memories to event history as system message
|
|
136
|
+
4. **Stores messages** - Sends conversation to Supermemory (background, non-blocking)
|
|
137
|
+
5. **Passes to agent** - Forwards enriched event to wrapped LlmAgent
|
|
138
|
+
|
|
139
|
+
### What Gets Stored
|
|
140
|
+
|
|
141
|
+
User and assistant messages are sent to Supermemory:
|
|
142
|
+
|
|
143
|
+
```json
|
|
144
|
+
{
|
|
145
|
+
"content": "User: What's the weather?\nAssistant: It's sunny today!",
|
|
146
|
+
"container_tags": ["user-123", "org-acme", "prod"],
|
|
147
|
+
"metadata": { "platform": "cartesia" }
|
|
148
|
+
}
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
## Architecture
|
|
152
|
+
|
|
153
|
+
Cartesia Line uses an event-driven architecture:
|
|
154
|
+
|
|
155
|
+
```
|
|
156
|
+
User Speaks (Audio)
|
|
157
|
+
↓
|
|
158
|
+
[Ink STT] → Automatic speech recognition
|
|
159
|
+
↓
|
|
160
|
+
UserTurnEnded Event {content: "user message", history: [...]}
|
|
161
|
+
↓
|
|
162
|
+
┌──────────────────────────────────────────────┐
|
|
163
|
+
│ SUPERMEMORY CARTESIA AGENT (Wrapper) │
|
|
164
|
+
│ │
|
|
165
|
+
│ process(env, event): │
|
|
166
|
+
│ 1. Intercept UserTurnEnded │
|
|
167
|
+
│ 2. Extract user message │
|
|
168
|
+
│ 3. Query Supermemory API │
|
|
169
|
+
│ 4. Enrich event.history with memories │
|
|
170
|
+
│ 5. Pass to wrapped LlmAgent │
|
|
171
|
+
│ 6. Store conversation (async background) │
|
|
172
|
+
└──────────────────────────────────────────────┘
|
|
173
|
+
↓
|
|
174
|
+
AgentSendText Event {text: "response"}
|
|
175
|
+
↓
|
|
176
|
+
[Sonic TTS] → Ultra-fast speech synthesis
|
|
177
|
+
↓
|
|
178
|
+
Audio Output
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
## Comparison with Pipecat SDK
|
|
182
|
+
|
|
183
|
+
| Aspect | Pipecat | Cartesia Line |
|
|
184
|
+
| ----------------------- | ------------------------------ | ---------------------------- |
|
|
185
|
+
| **Integration Pattern** | Extends `FrameProcessor` | Wrapper around `LlmAgent` |
|
|
186
|
+
| **Event Handling** | `process_frame()` method | `process()` method |
|
|
187
|
+
| **Events** | `LLMContextFrame`, `LLMMessagesFrame` | `UserTurnEnded`, `CallStarted` |
|
|
188
|
+
| **Context Object** | `LLMContext.get_messages()` | `event.history` |
|
|
189
|
+
| **Memory Injection** | Modify `context.add_message()` | Modify `event.history` |
|
|
190
|
+
|
|
191
|
+
## Full Example with Tools
|
|
192
|
+
|
|
193
|
+
```python
|
|
194
|
+
import os
|
|
195
|
+
from line.llm_agent import LlmAgent, LlmConfig
|
|
196
|
+
from line.tools import LoopbackTool
|
|
197
|
+
from line.voice_agent_app import VoiceAgentApp
|
|
198
|
+
from supermemory_cartesia import SupermemoryCartesiaAgent
|
|
199
|
+
|
|
200
|
+
# Define custom tools
|
|
201
|
+
async def get_weather(location: str) -> str:
|
|
202
|
+
return f"The weather in {location} is sunny, 72°F"
|
|
203
|
+
|
|
204
|
+
weather_tool = LoopbackTool(
|
|
205
|
+
name="get_weather",
|
|
206
|
+
description="Get current weather for a location",
|
|
207
|
+
function=get_weather
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
async def get_agent(env, call_request):
|
|
211
|
+
container_tag = call_request.metadata.get("user_id", "default-user")
|
|
212
|
+
org_id = call_request.metadata.get("org_id")
|
|
213
|
+
|
|
214
|
+
# Create LLM agent with tools
|
|
215
|
+
base_agent = LlmAgent(
|
|
216
|
+
model="gemini/gemini-2.5-flash-preview-09-2025",
|
|
217
|
+
tools=[weather_tool],
|
|
218
|
+
config=LlmConfig(
|
|
219
|
+
system_prompt="You are a personal assistant with memory and tools.",
|
|
220
|
+
introduction="Hi! How can I help you today?"
|
|
221
|
+
)
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
# Wrap with Supermemory
|
|
225
|
+
memory_agent = SupermemoryCartesiaAgent(
|
|
226
|
+
agent=base_agent,
|
|
227
|
+
api_key=os.getenv("SUPERMEMORY_API_KEY"),
|
|
228
|
+
container_tag=container_tag,
|
|
229
|
+
custom_id=call_request.call_id,
|
|
230
|
+
container_tags=[org_id] if org_id else None,
|
|
231
|
+
config=SupermemoryCartesiaAgent.MemoryConfig(
|
|
232
|
+
mode="full",
|
|
233
|
+
search_limit=15,
|
|
234
|
+
search_threshold=0.15,
|
|
235
|
+
)
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
return memory_agent
|
|
239
|
+
|
|
240
|
+
app = VoiceAgentApp(get_agent=get_agent)
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
## Development
|
|
244
|
+
|
|
245
|
+
```bash
|
|
246
|
+
# Clone repository
|
|
247
|
+
git clone https://github.com/supermemoryai/supermemory
|
|
248
|
+
cd supermemory/packages/cartesia-sdk-python
|
|
249
|
+
|
|
250
|
+
# Install in development mode
|
|
251
|
+
pip install -e ".[dev]"
|
|
252
|
+
|
|
253
|
+
# Run tests
|
|
254
|
+
pytest
|
|
255
|
+
|
|
256
|
+
# Format code
|
|
257
|
+
black .
|
|
258
|
+
isort .
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
## License
|
|
262
|
+
|
|
263
|
+
MIT
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
# Supermemory Cartesia SDK
|
|
2
|
+
|
|
3
|
+
Memory-enhanced voice agents with [Supermemory](https://supermemory.ai) and [Cartesia Line](https://cartesia.ai/agents).
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install supermemory-cartesia
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick Start
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
import os
|
|
15
|
+
from line.llm_agent import LlmAgent, LlmConfig
|
|
16
|
+
from line.voice_agent_app import VoiceAgentApp
|
|
17
|
+
from supermemory_cartesia import SupermemoryCartesiaAgent
|
|
18
|
+
|
|
19
|
+
async def get_agent(env, call_request):
|
|
20
|
+
# Extract container_tag from call metadata (typically user ID)
|
|
21
|
+
container_tag = call_request.metadata.get("user_id", "default-user")
|
|
22
|
+
|
|
23
|
+
# Create base LLM agent
|
|
24
|
+
base_agent = LlmAgent(
|
|
25
|
+
model="gemini/gemini-2.5-flash-preview-09-2025",
|
|
26
|
+
config=LlmConfig(
|
|
27
|
+
system_prompt="You are a helpful voice assistant with memory.",
|
|
28
|
+
introduction="Hello! Great to talk with you again!"
|
|
29
|
+
)
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
# Wrap with Supermemory
|
|
33
|
+
memory_agent = SupermemoryCartesiaAgent(
|
|
34
|
+
agent=base_agent,
|
|
35
|
+
api_key=os.getenv("SUPERMEMORY_API_KEY"),
|
|
36
|
+
container_tag=container_tag,
|
|
37
|
+
custom_id=call_request.call_id,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
return memory_agent
|
|
41
|
+
|
|
42
|
+
# Create voice agent app
|
|
43
|
+
app = VoiceAgentApp(get_agent=get_agent)
|
|
44
|
+
|
|
45
|
+
if __name__ == "__main__":
|
|
46
|
+
app.run(host="0.0.0.0", port=8000)
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Configuration
|
|
50
|
+
|
|
51
|
+
### Parameters
|
|
52
|
+
|
|
53
|
+
| Parameter | Type | Required | Description |
|
|
54
|
+
| --------------- | ------------ | -------- | ------------------------------------------------------------------ |
|
|
55
|
+
| `agent` | LlmAgent | **Yes** | The Cartesia Line agent to wrap |
|
|
56
|
+
| `container_tag` | str | **Yes** | Primary container tag for memory scoping (e.g., user ID) |
|
|
57
|
+
| `custom_id` | str | **Yes** | Custom ID for grouping conversation messages into a single document|
|
|
58
|
+
| `add_memory` | Literal | No | Memory persistence mode: "always" (default) or "never" |
|
|
59
|
+
| `container_tags`| List[str] | No | Additional container tags for organization (e.g., ["org", "prod"]) |
|
|
60
|
+
| `api_key` | str | No | Supermemory API key (or set `SUPERMEMORY_API_KEY` env var) |
|
|
61
|
+
| `config` | MemoryConfig | No | Advanced configuration |
|
|
62
|
+
| `base_url` | str | No | Custom API endpoint |
|
|
63
|
+
|
|
64
|
+
### Advanced Configuration
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from supermemory_cartesia import SupermemoryCartesiaAgent
|
|
68
|
+
|
|
69
|
+
memory_agent = SupermemoryCartesiaAgent(
|
|
70
|
+
agent=base_agent,
|
|
71
|
+
container_tag="user-123",
|
|
72
|
+
custom_id="conversation-456",
|
|
73
|
+
add_memory="always", # "always" (default) or "never"
|
|
74
|
+
container_tags=["org-acme", "prod"], # Optional: additional tags
|
|
75
|
+
config=SupermemoryCartesiaAgent.MemoryConfig(
|
|
76
|
+
search_limit=10, # Max memories to retrieve
|
|
77
|
+
search_threshold=0.1, # Similarity threshold
|
|
78
|
+
mode="full", # "profile", "query", or "full"
|
|
79
|
+
system_prompt="Based on previous conversations, I recall:\n\n",
|
|
80
|
+
),
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
# Read-only mode - retrieve memories but don't save new ones
|
|
84
|
+
read_only_agent = SupermemoryCartesiaAgent(
|
|
85
|
+
agent=base_agent,
|
|
86
|
+
container_tag="user-123",
|
|
87
|
+
custom_id="conversation-456",
|
|
88
|
+
add_memory="never", # Only retrieve, don't save
|
|
89
|
+
)
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
### Memory Modes
|
|
93
|
+
|
|
94
|
+
| Mode | Static Profile | Dynamic Profile | Search Results |
|
|
95
|
+
| ----------- | -------------- | --------------- | -------------- |
|
|
96
|
+
| `"profile"` | Yes | Yes | No |
|
|
97
|
+
| `"query"` | No | No | Yes |
|
|
98
|
+
| `"full"` | Yes | Yes | Yes |
|
|
99
|
+
|
|
100
|
+
## How It Works
|
|
101
|
+
|
|
102
|
+
1. **Intercepts events** - Listens for `UserTurnEnded` events from Cartesia Line
|
|
103
|
+
2. **Retrieves memories** - Queries Supermemory `/v4/profile` API with user's message
|
|
104
|
+
3. **Enriches context** - Adds memories to event history as system message
|
|
105
|
+
4. **Stores messages** - Sends conversation to Supermemory (background, non-blocking)
|
|
106
|
+
5. **Passes to agent** - Forwards enriched event to wrapped LlmAgent
|
|
107
|
+
|
|
108
|
+
### What Gets Stored
|
|
109
|
+
|
|
110
|
+
User and assistant messages are sent to Supermemory:
|
|
111
|
+
|
|
112
|
+
```json
|
|
113
|
+
{
|
|
114
|
+
"content": "User: What's the weather?\nAssistant: It's sunny today!",
|
|
115
|
+
"container_tags": ["user-123", "org-acme", "prod"],
|
|
116
|
+
"metadata": { "platform": "cartesia" }
|
|
117
|
+
}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## Architecture
|
|
121
|
+
|
|
122
|
+
Cartesia Line uses an event-driven architecture:
|
|
123
|
+
|
|
124
|
+
```
|
|
125
|
+
User Speaks (Audio)
|
|
126
|
+
↓
|
|
127
|
+
[Ink STT] → Automatic speech recognition
|
|
128
|
+
↓
|
|
129
|
+
UserTurnEnded Event {content: "user message", history: [...]}
|
|
130
|
+
↓
|
|
131
|
+
┌──────────────────────────────────────────────┐
|
|
132
|
+
│ SUPERMEMORY CARTESIA AGENT (Wrapper) │
|
|
133
|
+
│ │
|
|
134
|
+
│ process(env, event): │
|
|
135
|
+
│ 1. Intercept UserTurnEnded │
|
|
136
|
+
│ 2. Extract user message │
|
|
137
|
+
│ 3. Query Supermemory API │
|
|
138
|
+
│ 4. Enrich event.history with memories │
|
|
139
|
+
│ 5. Pass to wrapped LlmAgent │
|
|
140
|
+
│ 6. Store conversation (async background) │
|
|
141
|
+
└──────────────────────────────────────────────┘
|
|
142
|
+
↓
|
|
143
|
+
AgentSendText Event {text: "response"}
|
|
144
|
+
↓
|
|
145
|
+
[Sonic TTS] → Ultra-fast speech synthesis
|
|
146
|
+
↓
|
|
147
|
+
Audio Output
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
## Comparison with Pipecat SDK
|
|
151
|
+
|
|
152
|
+
| Aspect | Pipecat | Cartesia Line |
|
|
153
|
+
| ----------------------- | ------------------------------ | ---------------------------- |
|
|
154
|
+
| **Integration Pattern** | Extends `FrameProcessor` | Wrapper around `LlmAgent` |
|
|
155
|
+
| **Event Handling** | `process_frame()` method | `process()` method |
|
|
156
|
+
| **Events** | `LLMContextFrame`, `LLMMessagesFrame` | `UserTurnEnded`, `CallStarted` |
|
|
157
|
+
| **Context Object** | `LLMContext.get_messages()` | `event.history` |
|
|
158
|
+
| **Memory Injection** | Modify `context.add_message()` | Modify `event.history` |
|
|
159
|
+
|
|
160
|
+
## Full Example with Tools
|
|
161
|
+
|
|
162
|
+
```python
|
|
163
|
+
import os
|
|
164
|
+
from line.llm_agent import LlmAgent, LlmConfig
|
|
165
|
+
from line.tools import LoopbackTool
|
|
166
|
+
from line.voice_agent_app import VoiceAgentApp
|
|
167
|
+
from supermemory_cartesia import SupermemoryCartesiaAgent
|
|
168
|
+
|
|
169
|
+
# Define custom tools
|
|
170
|
+
async def get_weather(location: str) -> str:
|
|
171
|
+
return f"The weather in {location} is sunny, 72°F"
|
|
172
|
+
|
|
173
|
+
weather_tool = LoopbackTool(
|
|
174
|
+
name="get_weather",
|
|
175
|
+
description="Get current weather for a location",
|
|
176
|
+
function=get_weather
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
async def get_agent(env, call_request):
|
|
180
|
+
container_tag = call_request.metadata.get("user_id", "default-user")
|
|
181
|
+
org_id = call_request.metadata.get("org_id")
|
|
182
|
+
|
|
183
|
+
# Create LLM agent with tools
|
|
184
|
+
base_agent = LlmAgent(
|
|
185
|
+
model="gemini/gemini-2.5-flash-preview-09-2025",
|
|
186
|
+
tools=[weather_tool],
|
|
187
|
+
config=LlmConfig(
|
|
188
|
+
system_prompt="You are a personal assistant with memory and tools.",
|
|
189
|
+
introduction="Hi! How can I help you today?"
|
|
190
|
+
)
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
# Wrap with Supermemory
|
|
194
|
+
memory_agent = SupermemoryCartesiaAgent(
|
|
195
|
+
agent=base_agent,
|
|
196
|
+
api_key=os.getenv("SUPERMEMORY_API_KEY"),
|
|
197
|
+
container_tag=container_tag,
|
|
198
|
+
custom_id=call_request.call_id,
|
|
199
|
+
container_tags=[org_id] if org_id else None,
|
|
200
|
+
config=SupermemoryCartesiaAgent.MemoryConfig(
|
|
201
|
+
mode="full",
|
|
202
|
+
search_limit=15,
|
|
203
|
+
search_threshold=0.15,
|
|
204
|
+
)
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
return memory_agent
|
|
208
|
+
|
|
209
|
+
app = VoiceAgentApp(get_agent=get_agent)
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
## Development
|
|
213
|
+
|
|
214
|
+
```bash
|
|
215
|
+
# Clone repository
|
|
216
|
+
git clone https://github.com/supermemoryai/supermemory
|
|
217
|
+
cd supermemory/packages/cartesia-sdk-python
|
|
218
|
+
|
|
219
|
+
# Install in development mode
|
|
220
|
+
pip install -e ".[dev]"
|
|
221
|
+
|
|
222
|
+
# Run tests
|
|
223
|
+
pytest
|
|
224
|
+
|
|
225
|
+
# Format code
|
|
226
|
+
black .
|
|
227
|
+
isort .
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
## License
|
|
231
|
+
|
|
232
|
+
MIT
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "supermemory-cartesia"
|
|
7
|
+
version = "0.1.1"
|
|
8
|
+
description = "Supermemory integration for Cartesia Line - memory-enhanced voice agents"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "Supermemory", email = "support@supermemory.ai" }
|
|
14
|
+
]
|
|
15
|
+
keywords = [
|
|
16
|
+
"supermemory",
|
|
17
|
+
"cartesia",
|
|
18
|
+
"line",
|
|
19
|
+
"memory",
|
|
20
|
+
"conversational-ai",
|
|
21
|
+
"llm",
|
|
22
|
+
"voice-ai",
|
|
23
|
+
]
|
|
24
|
+
classifiers = [
|
|
25
|
+
"Development Status :: 4 - Beta",
|
|
26
|
+
"Intended Audience :: Developers",
|
|
27
|
+
"License :: OSI Approved :: MIT License",
|
|
28
|
+
"Programming Language :: Python :: 3",
|
|
29
|
+
"Programming Language :: Python :: 3.10",
|
|
30
|
+
"Programming Language :: Python :: 3.11",
|
|
31
|
+
"Programming Language :: Python :: 3.12",
|
|
32
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
33
|
+
]
|
|
34
|
+
dependencies = [
|
|
35
|
+
"supermemory>=3.16.0",
|
|
36
|
+
"cartesia-line>=0.2.0",
|
|
37
|
+
"pydantic>=2.10.0",
|
|
38
|
+
"loguru>=0.7.3",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
[project.optional-dependencies]
|
|
42
|
+
dev = [
|
|
43
|
+
"pytest>=8.3.5",
|
|
44
|
+
"pytest-asyncio>=0.24.0",
|
|
45
|
+
"mypy>=1.14.1",
|
|
46
|
+
"black>=24.8.0",
|
|
47
|
+
"isort>=5.13.2",
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
[project.urls]
|
|
51
|
+
Homepage = "https://supermemory.ai"
|
|
52
|
+
Documentation = "https://docs.supermemory.ai"
|
|
53
|
+
Repository = "https://github.com/supermemoryai/supermemory"
|
|
54
|
+
|
|
55
|
+
[tool.hatch.build.targets.wheel]
|
|
56
|
+
packages = ["src/supermemory_cartesia"]
|
|
57
|
+
|
|
58
|
+
[tool.hatch.build.targets.sdist]
|
|
59
|
+
include = [
|
|
60
|
+
"/src",
|
|
61
|
+
"/tests",
|
|
62
|
+
"/README.md",
|
|
63
|
+
"/LICENSE",
|
|
64
|
+
]
|
|
65
|
+
|
|
66
|
+
[tool.black]
|
|
67
|
+
line-length = 100
|
|
68
|
+
target-version = ["py310"]
|
|
69
|
+
|
|
70
|
+
[tool.isort]
|
|
71
|
+
profile = "black"
|
|
72
|
+
line_length = 100
|
|
73
|
+
|
|
74
|
+
[tool.mypy]
|
|
75
|
+
python_version = "3.10"
|
|
76
|
+
warn_return_any = true
|
|
77
|
+
warn_unused_configs = true
|
|
78
|
+
disallow_untyped_defs = true
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Supermemory Cartesia SDK - Memory-enhanced voice agents with Cartesia Line.
|
|
2
|
+
|
|
3
|
+
This package provides seamless integration between Supermemory and Cartesia Line,
|
|
4
|
+
enabling persistent memory and context enhancement for voice AI applications.
|
|
5
|
+
|
|
6
|
+
Example:
|
|
7
|
+
```python
|
|
8
|
+
from supermemory_cartesia import SupermemoryCartesiaAgent, MemoryConfig
|
|
9
|
+
from line.llm_agent import LlmAgent, LlmConfig
|
|
10
|
+
|
|
11
|
+
# Create base LLM agent
|
|
12
|
+
base_agent = LlmAgent(
|
|
13
|
+
model="gemini/gemini-2.5-flash-preview-09-2025",
|
|
14
|
+
config=LlmConfig(
|
|
15
|
+
system_prompt="You are a helpful assistant.",
|
|
16
|
+
introduction="Hello!"
|
|
17
|
+
)
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
# Wrap with Supermemory
|
|
21
|
+
memory_agent = SupermemoryCartesiaAgent(
|
|
22
|
+
agent=base_agent,
|
|
23
|
+
api_key=os.getenv("SUPERMEMORY_API_KEY"),
|
|
24
|
+
container_tag="user-123",
|
|
25
|
+
)
|
|
26
|
+
```
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from .agent import SupermemoryCartesiaAgent
|
|
30
|
+
|
|
31
|
+
# Export MemoryConfig as a top-level class for convenience
|
|
32
|
+
MemoryConfig = SupermemoryCartesiaAgent.MemoryConfig
|
|
33
|
+
|
|
34
|
+
from .exceptions import (
|
|
35
|
+
APIError,
|
|
36
|
+
ConfigurationError,
|
|
37
|
+
MemoryRetrievalError,
|
|
38
|
+
MemoryStorageError,
|
|
39
|
+
NetworkError,
|
|
40
|
+
SupermemoryCartesiaError,
|
|
41
|
+
)
|
|
42
|
+
from .utils import (
|
|
43
|
+
deduplicate_memories,
|
|
44
|
+
format_memories_to_text,
|
|
45
|
+
format_relative_time,
|
|
46
|
+
get_last_user_message,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
__version__ = "0.1.0"
|
|
50
|
+
|
|
51
|
+
__all__ = [
|
|
52
|
+
# Main agent
|
|
53
|
+
"SupermemoryCartesiaAgent",
|
|
54
|
+
"MemoryConfig",
|
|
55
|
+
# Exceptions
|
|
56
|
+
"SupermemoryCartesiaError",
|
|
57
|
+
"ConfigurationError",
|
|
58
|
+
"MemoryRetrievalError",
|
|
59
|
+
"MemoryStorageError",
|
|
60
|
+
"APIError",
|
|
61
|
+
"NetworkError",
|
|
62
|
+
# Utilities
|
|
63
|
+
"get_last_user_message",
|
|
64
|
+
"deduplicate_memories",
|
|
65
|
+
"format_memories_to_text",
|
|
66
|
+
"format_relative_time",
|
|
67
|
+
]
|
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
"""Supermemory Cartesia Line agent integration.
|
|
2
|
+
|
|
3
|
+
This module provides a memory-enhanced agent wrapper that integrates with
|
|
4
|
+
Cartesia Line voice agents, adding persistent memory and context enrichment.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import asyncio
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
from typing import Any, AsyncGenerator, Dict, List, Literal, Optional
|
|
11
|
+
|
|
12
|
+
from loguru import logger
|
|
13
|
+
from pydantic import BaseModel, Field
|
|
14
|
+
|
|
15
|
+
from .exceptions import ConfigurationError, MemoryRetrievalError
|
|
16
|
+
from .utils import deduplicate_memories, format_memories_to_text
|
|
17
|
+
|
|
18
|
+
try:
|
|
19
|
+
import supermemory
|
|
20
|
+
except ImportError:
|
|
21
|
+
supermemory = None # type: ignore
|
|
22
|
+
|
|
23
|
+
try:
|
|
24
|
+
from line.events import Event
|
|
25
|
+
except ImportError:
|
|
26
|
+
Event = Any # type: ignore
|
|
27
|
+
|
|
28
|
+
# XML tags for memory injection
|
|
29
|
+
MEMORY_TAG_START = "<user_memories>"
|
|
30
|
+
MEMORY_TAG_END = "</user_memories>"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class SupermemoryCartesiaAgent:
|
|
34
|
+
"""Memory-enhanced wrapper for Cartesia Line agents.
|
|
35
|
+
|
|
36
|
+
This wrapper intercepts UserTurnEnded events, retrieves relevant memories
|
|
37
|
+
from Supermemory, and enriches the conversation history before passing to
|
|
38
|
+
the wrapped agent.
|
|
39
|
+
|
|
40
|
+
Example:
|
|
41
|
+
```python
|
|
42
|
+
from line.llm_agent import LlmAgent, LlmConfig
|
|
43
|
+
from supermemory_cartesia import SupermemoryCartesiaAgent
|
|
44
|
+
|
|
45
|
+
base_agent = LlmAgent(
|
|
46
|
+
model="anthropic/claude-haiku-4-5-20251001",
|
|
47
|
+
config=LlmConfig(
|
|
48
|
+
system_prompt="You are a helpful assistant.",
|
|
49
|
+
introduction="Hello! How can I help you today?"
|
|
50
|
+
)
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
memory_agent = SupermemoryCartesiaAgent(
|
|
54
|
+
agent=base_agent,
|
|
55
|
+
api_key=os.getenv("SUPERMEMORY_API_KEY"),
|
|
56
|
+
container_tag="user-123",
|
|
57
|
+
custom_id="conversation-456",
|
|
58
|
+
)
|
|
59
|
+
```
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
class MemoryConfig(BaseModel):
|
|
63
|
+
"""Configuration for memory retrieval.
|
|
64
|
+
|
|
65
|
+
Attributes:
|
|
66
|
+
search_limit: Maximum memories to retrieve per query.
|
|
67
|
+
search_threshold: Minimum similarity threshold (0.0-1.0).
|
|
68
|
+
system_prompt: Prefix text for memory context.
|
|
69
|
+
mode: "profile", "query", or "full".
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
search_limit: int = Field(default=10, ge=1)
|
|
73
|
+
search_threshold: float = Field(default=0.1, ge=0.0, le=1.0)
|
|
74
|
+
system_prompt: str = Field(default="Based on previous conversations:\n\n")
|
|
75
|
+
mode: Literal["profile", "query", "full"] = Field(default="full")
|
|
76
|
+
|
|
77
|
+
def __init__(
|
|
78
|
+
self,
|
|
79
|
+
*,
|
|
80
|
+
agent: Any,
|
|
81
|
+
api_key: Optional[str] = None,
|
|
82
|
+
container_tag: str,
|
|
83
|
+
custom_id: str,
|
|
84
|
+
add_memory: Literal["always", "never"] = "always",
|
|
85
|
+
container_tags: Optional[List[str]] = None,
|
|
86
|
+
config: Optional[MemoryConfig] = None,
|
|
87
|
+
base_url: Optional[str] = None,
|
|
88
|
+
):
|
|
89
|
+
"""Initialize the Supermemory Cartesia agent wrapper.
|
|
90
|
+
|
|
91
|
+
Args:
|
|
92
|
+
agent: The inner Cartesia Line agent to wrap.
|
|
93
|
+
api_key: Supermemory API key (or SUPERMEMORY_API_KEY env var).
|
|
94
|
+
container_tag: Primary container tag for memory scoping (e.g., user ID).
|
|
95
|
+
custom_id: Required. Custom ID to store all conversation messages in the same document.
|
|
96
|
+
Useful for grouping multi-turn conversations (e.g., call ID, conversation ID).
|
|
97
|
+
add_memory: Memory persistence mode - "always" (default) or "never".
|
|
98
|
+
container_tags: Optional list of additional container tags for
|
|
99
|
+
organization/categorization (e.g., ["org-acme", "prod"]).
|
|
100
|
+
config: Memory retrieval configuration.
|
|
101
|
+
base_url: Optional custom Supermemory API URL.
|
|
102
|
+
|
|
103
|
+
Raises:
|
|
104
|
+
ConfigurationError: If API key, container_tag, or custom_id is missing.
|
|
105
|
+
"""
|
|
106
|
+
self.agent = agent
|
|
107
|
+
self.container_tag = container_tag
|
|
108
|
+
self.custom_id = custom_id
|
|
109
|
+
self.add_memory = add_memory
|
|
110
|
+
|
|
111
|
+
# Build container tags list: primary tag first, then additional tags
|
|
112
|
+
self.container_tags = [container_tag]
|
|
113
|
+
if container_tags:
|
|
114
|
+
self.container_tags.extend(container_tags)
|
|
115
|
+
|
|
116
|
+
self.config = config or SupermemoryCartesiaAgent.MemoryConfig()
|
|
117
|
+
|
|
118
|
+
self.api_key = api_key or os.getenv("SUPERMEMORY_API_KEY")
|
|
119
|
+
if not self.api_key:
|
|
120
|
+
raise ConfigurationError(
|
|
121
|
+
"API key required. Set SUPERMEMORY_API_KEY or pass api_key."
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
if not container_tag:
|
|
125
|
+
raise ConfigurationError("container_tag is required")
|
|
126
|
+
|
|
127
|
+
if not custom_id or not custom_id.strip():
|
|
128
|
+
raise ConfigurationError(
|
|
129
|
+
"custom_id is required and must be a non-empty string. "
|
|
130
|
+
"This ensures messages are grouped into the same document for a conversation."
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
self._supermemory_client = None
|
|
134
|
+
if supermemory is not None:
|
|
135
|
+
try:
|
|
136
|
+
self._supermemory_client = supermemory.AsyncSupermemory(
|
|
137
|
+
api_key=self.api_key,
|
|
138
|
+
base_url=base_url,
|
|
139
|
+
)
|
|
140
|
+
logger.info(f"[Supermemory] Initialized client for container_tag={container_tag}, all_tags={self.container_tags}")
|
|
141
|
+
except Exception as e:
|
|
142
|
+
logger.error(f"[Supermemory] Failed to initialize client: {e}")
|
|
143
|
+
|
|
144
|
+
self._messages_sent_count: int = 0
|
|
145
|
+
self._last_query: Optional[str] = None
|
|
146
|
+
self._background_tasks: set = set() # Track background tasks to prevent GC
|
|
147
|
+
|
|
148
|
+
async def _retrieve_memories(self, query: str) -> Dict[str, Any]:
|
|
149
|
+
"""Retrieve memories from Supermemory."""
|
|
150
|
+
if self._supermemory_client is None:
|
|
151
|
+
raise MemoryRetrievalError("Supermemory client not initialized")
|
|
152
|
+
|
|
153
|
+
try:
|
|
154
|
+
# Use primary container tag for profile retrieval
|
|
155
|
+
kwargs: Dict[str, Any] = {"container_tag": self.container_tags[0]}
|
|
156
|
+
|
|
157
|
+
if self.config.mode != "profile" and query:
|
|
158
|
+
kwargs["q"] = query
|
|
159
|
+
kwargs["threshold"] = self.config.search_threshold
|
|
160
|
+
kwargs["extra_body"] = {"limit": self.config.search_limit}
|
|
161
|
+
|
|
162
|
+
logger.info(f"[Supermemory] Retrieving memories for query: {query[:50]}...")
|
|
163
|
+
|
|
164
|
+
response = await asyncio.wait_for(
|
|
165
|
+
self._supermemory_client.profile(**kwargs),
|
|
166
|
+
timeout=10.0
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
static_count = len(response.profile.static) if response.profile.static else 0
|
|
170
|
+
dynamic_count = len(response.profile.dynamic) if response.profile.dynamic else 0
|
|
171
|
+
search_count = len(response.search_results.results) if response.search_results and response.search_results.results else 0
|
|
172
|
+
|
|
173
|
+
logger.info(f"[Supermemory] Retrieved memories - static: {static_count}, dynamic: {dynamic_count}, search: {search_count}")
|
|
174
|
+
|
|
175
|
+
search_results = []
|
|
176
|
+
if response.search_results and response.search_results.results:
|
|
177
|
+
search_results = response.search_results.results
|
|
178
|
+
|
|
179
|
+
return {
|
|
180
|
+
"profile": {
|
|
181
|
+
"static": response.profile.static or [],
|
|
182
|
+
"dynamic": response.profile.dynamic or [],
|
|
183
|
+
},
|
|
184
|
+
"search_results": search_results,
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
except asyncio.TimeoutError:
|
|
188
|
+
logger.warning("[Supermemory] Profile API timed out after 10s")
|
|
189
|
+
raise MemoryRetrievalError("Profile API timed out")
|
|
190
|
+
except Exception as e:
|
|
191
|
+
logger.error(f"[Supermemory] Error retrieving memories: {e}")
|
|
192
|
+
raise MemoryRetrievalError("Failed to retrieve memories", e)
|
|
193
|
+
|
|
194
|
+
async def _store_messages(self, messages: List[Dict[str, Any]]) -> None:
|
|
195
|
+
"""Store messages in Supermemory."""
|
|
196
|
+
if self._supermemory_client is None or not messages or self.add_memory == "never":
|
|
197
|
+
return
|
|
198
|
+
|
|
199
|
+
try:
|
|
200
|
+
# Format as conversation transcript
|
|
201
|
+
lines = []
|
|
202
|
+
for msg in messages:
|
|
203
|
+
role = msg.get("role", "")
|
|
204
|
+
content = msg.get("content", "")
|
|
205
|
+
if role == "user":
|
|
206
|
+
lines.append(f"User: {content}")
|
|
207
|
+
elif role == "assistant":
|
|
208
|
+
lines.append(f"Assistant: {content}")
|
|
209
|
+
|
|
210
|
+
logger.info(f"[Supermemory] Storing {len(messages)} messages to containers={self.container_tags}")
|
|
211
|
+
|
|
212
|
+
# Build kwargs for add() call
|
|
213
|
+
add_kwargs: Dict[str, Any] = {
|
|
214
|
+
"content": "\n".join(lines),
|
|
215
|
+
"container_tags": self.container_tags,
|
|
216
|
+
"metadata": {"platform": "cartesia"},
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
# Use custom_id for document grouping (required field)
|
|
220
|
+
add_kwargs["custom_id"] = self.custom_id
|
|
221
|
+
logger.info(f"[Supermemory] Using custom_id={self.custom_id} for document grouping")
|
|
222
|
+
|
|
223
|
+
await self._supermemory_client.add(**add_kwargs)
|
|
224
|
+
|
|
225
|
+
logger.info(f"[Supermemory] Successfully stored {len(messages)} messages")
|
|
226
|
+
|
|
227
|
+
except Exception as e:
|
|
228
|
+
logger.error(f"[Supermemory] Error storing messages: {e}")
|
|
229
|
+
|
|
230
|
+
def _build_memory_message(self, memories_data: Dict[str, Any]) -> Optional[str]:
|
|
231
|
+
"""Build memory context from retrieved data."""
|
|
232
|
+
profile = memories_data["profile"]
|
|
233
|
+
deduplicated = deduplicate_memories(
|
|
234
|
+
static=profile["static"],
|
|
235
|
+
dynamic=profile["dynamic"],
|
|
236
|
+
search_results=memories_data["search_results"],
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
total = (
|
|
240
|
+
len(deduplicated["static"])
|
|
241
|
+
+ len(deduplicated["dynamic"])
|
|
242
|
+
+ len(deduplicated["search_results"])
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
if total == 0:
|
|
246
|
+
return None
|
|
247
|
+
|
|
248
|
+
include_profile = self.config.mode in ("profile", "full")
|
|
249
|
+
include_search = self.config.mode in ("query", "full")
|
|
250
|
+
|
|
251
|
+
memory_text = format_memories_to_text(
|
|
252
|
+
deduplicated,
|
|
253
|
+
system_prompt=self.config.system_prompt,
|
|
254
|
+
include_static=include_profile,
|
|
255
|
+
include_dynamic=include_profile,
|
|
256
|
+
include_search=include_search,
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
if not memory_text:
|
|
260
|
+
return None
|
|
261
|
+
|
|
262
|
+
return f"{MEMORY_TAG_START}\n{memory_text}\n{MEMORY_TAG_END}"
|
|
263
|
+
|
|
264
|
+
def _extract_user_message(self, event: Any) -> Optional[str]:
|
|
265
|
+
"""Extract user text from a UserTurnEnded event."""
|
|
266
|
+
if not hasattr(event, 'content'):
|
|
267
|
+
return None
|
|
268
|
+
|
|
269
|
+
content = event.content
|
|
270
|
+
|
|
271
|
+
if isinstance(content, str):
|
|
272
|
+
return content
|
|
273
|
+
|
|
274
|
+
if isinstance(content, list):
|
|
275
|
+
texts = []
|
|
276
|
+
for item in content:
|
|
277
|
+
if hasattr(item, 'content') and isinstance(item.content, str):
|
|
278
|
+
texts.append(item.content)
|
|
279
|
+
elif isinstance(item, str):
|
|
280
|
+
texts.append(item)
|
|
281
|
+
return " ".join(texts) if texts else None
|
|
282
|
+
|
|
283
|
+
if hasattr(content, 'content'):
|
|
284
|
+
return str(content.content)
|
|
285
|
+
|
|
286
|
+
return str(content)
|
|
287
|
+
|
|
288
|
+
def _extract_conversation_from_history(self, history: list) -> List[Dict[str, str]]:
|
|
289
|
+
"""Extract messages from Cartesia event history."""
|
|
290
|
+
messages = []
|
|
291
|
+
seen = set()
|
|
292
|
+
|
|
293
|
+
for item in history:
|
|
294
|
+
if isinstance(item, dict):
|
|
295
|
+
if item.get("role") in ("user", "assistant"):
|
|
296
|
+
content = item.get("content", "")
|
|
297
|
+
if content and content not in seen:
|
|
298
|
+
messages.append(item)
|
|
299
|
+
seen.add(content)
|
|
300
|
+
continue
|
|
301
|
+
|
|
302
|
+
event_type = getattr(item, 'type', None) or type(item).__name__
|
|
303
|
+
|
|
304
|
+
if event_type in ('user_turn_ended', 'UserTurnEnded'):
|
|
305
|
+
nested = getattr(item, 'content', [])
|
|
306
|
+
if isinstance(nested, list):
|
|
307
|
+
for n in nested:
|
|
308
|
+
if hasattr(n, 'content') and isinstance(n.content, str):
|
|
309
|
+
if n.content not in seen:
|
|
310
|
+
messages.append({"role": "user", "content": n.content})
|
|
311
|
+
seen.add(n.content)
|
|
312
|
+
|
|
313
|
+
elif event_type in ('agent_turn_ended', 'AgentTurnEnded'):
|
|
314
|
+
nested = getattr(item, 'content', [])
|
|
315
|
+
if isinstance(nested, list):
|
|
316
|
+
texts = [n.content for n in nested if hasattr(n, 'content') and isinstance(n.content, str)]
|
|
317
|
+
if texts:
|
|
318
|
+
content = " ".join(texts)
|
|
319
|
+
if content not in seen:
|
|
320
|
+
messages.append({"role": "assistant", "content": content})
|
|
321
|
+
seen.add(content)
|
|
322
|
+
|
|
323
|
+
elif event_type in ('user_text_sent', 'UserTextSent'):
|
|
324
|
+
content = getattr(item, 'content', '')
|
|
325
|
+
if content and isinstance(content, str) and content not in seen:
|
|
326
|
+
messages.append({"role": "user", "content": content})
|
|
327
|
+
seen.add(content)
|
|
328
|
+
|
|
329
|
+
elif event_type in ('agent_text_sent', 'AgentTextSent'):
|
|
330
|
+
content = getattr(item, 'content', '')
|
|
331
|
+
if content and isinstance(content, str) and content not in seen:
|
|
332
|
+
messages.append({"role": "assistant", "content": content})
|
|
333
|
+
seen.add(content)
|
|
334
|
+
|
|
335
|
+
return messages
|
|
336
|
+
|
|
337
|
+
async def _enrich_event_with_memories(self, event: Any) -> tuple[Any, Optional[str]]:
|
|
338
|
+
"""Enrich event by retrieving memories.
|
|
339
|
+
|
|
340
|
+
Returns:
|
|
341
|
+
Tuple of (event, memory_context) - memory_context is None if no memories found.
|
|
342
|
+
The event is returned unchanged; memory injection happens at the agent level.
|
|
343
|
+
"""
|
|
344
|
+
user_message = self._extract_user_message(event)
|
|
345
|
+
|
|
346
|
+
if not user_message:
|
|
347
|
+
logger.warning("[Supermemory] Could not extract user message from event")
|
|
348
|
+
return event, None
|
|
349
|
+
|
|
350
|
+
if user_message == self._last_query:
|
|
351
|
+
return event, None
|
|
352
|
+
|
|
353
|
+
self._last_query = user_message
|
|
354
|
+
logger.info(f"[Supermemory] Processing user message: {user_message[:50]}...")
|
|
355
|
+
|
|
356
|
+
try:
|
|
357
|
+
memories_data = await self._retrieve_memories(user_message)
|
|
358
|
+
memory_context = self._build_memory_message(memories_data)
|
|
359
|
+
|
|
360
|
+
if not memory_context:
|
|
361
|
+
logger.info("[Supermemory] No memories found for context injection")
|
|
362
|
+
return event, None
|
|
363
|
+
|
|
364
|
+
logger.info("[Supermemory] Retrieved memory context for injection")
|
|
365
|
+
return event, memory_context
|
|
366
|
+
|
|
367
|
+
except MemoryRetrievalError as e:
|
|
368
|
+
logger.warning(f"[Supermemory] Memory retrieval failed: {e}")
|
|
369
|
+
return event, None
|
|
370
|
+
except Exception as e:
|
|
371
|
+
logger.error(f"[Supermemory] Error in memory enrichment: {e}")
|
|
372
|
+
return event, None
|
|
373
|
+
|
|
374
|
+
async def process(self, env: Any, event: Event) -> AsyncGenerator[Event, None]:
|
|
375
|
+
"""Process events with memory enrichment.
|
|
376
|
+
|
|
377
|
+
Args:
|
|
378
|
+
env: Turn environment from Cartesia Line.
|
|
379
|
+
event: Input event to process.
|
|
380
|
+
|
|
381
|
+
Yields:
|
|
382
|
+
Output events from the wrapped agent.
|
|
383
|
+
"""
|
|
384
|
+
try:
|
|
385
|
+
if type(event).__name__ == "UserTurnEnded":
|
|
386
|
+
logger.info("[Supermemory] Processing UserTurnEnded event")
|
|
387
|
+
event, memory_context = await self._enrich_event_with_memories(event)
|
|
388
|
+
|
|
389
|
+
# Clean up old memory context and inject new one if available
|
|
390
|
+
if hasattr(self.agent, 'config'):
|
|
391
|
+
original_prompt = getattr(self.agent.config, 'system_prompt', '')
|
|
392
|
+
# Always remove old memory context if present to prevent stale data
|
|
393
|
+
if MEMORY_TAG_START in original_prompt:
|
|
394
|
+
original_prompt = re.sub(
|
|
395
|
+
rf'{re.escape(MEMORY_TAG_START)}.*?{re.escape(MEMORY_TAG_END)}\s*',
|
|
396
|
+
'',
|
|
397
|
+
original_prompt,
|
|
398
|
+
flags=re.DOTALL
|
|
399
|
+
)
|
|
400
|
+
logger.debug("[Supermemory] Removed old memory context from system prompt")
|
|
401
|
+
|
|
402
|
+
# Inject new memory context if available
|
|
403
|
+
if memory_context:
|
|
404
|
+
self.agent.config.system_prompt = f"{memory_context}\n\n{original_prompt}"
|
|
405
|
+
logger.info("[Supermemory] Injected new memory context into system prompt")
|
|
406
|
+
else:
|
|
407
|
+
# No new memories, but we cleaned up old ones
|
|
408
|
+
self.agent.config.system_prompt = original_prompt
|
|
409
|
+
logger.debug("[Supermemory] No new memories to inject, using clean prompt")
|
|
410
|
+
|
|
411
|
+
# Store conversation in background
|
|
412
|
+
if hasattr(event, 'history') and event.history:
|
|
413
|
+
messages = self._extract_conversation_from_history(event.history)
|
|
414
|
+
unsent = messages[self._messages_sent_count:]
|
|
415
|
+
if unsent:
|
|
416
|
+
logger.info(f"[Supermemory] Queuing {len(unsent)} messages for storage")
|
|
417
|
+
task = asyncio.create_task(self._store_messages(unsent))
|
|
418
|
+
self._background_tasks.add(task)
|
|
419
|
+
task.add_done_callback(self._background_tasks.discard)
|
|
420
|
+
self._messages_sent_count = len(messages)
|
|
421
|
+
else:
|
|
422
|
+
# No history yet, store just the current user message
|
|
423
|
+
user_content = self._extract_user_message(event)
|
|
424
|
+
if user_content:
|
|
425
|
+
logger.info(f"[Supermemory] No history, storing current user message: {user_content[:50]}...")
|
|
426
|
+
task = asyncio.create_task(self._store_messages([{"role": "user", "content": user_content}]))
|
|
427
|
+
self._background_tasks.add(task)
|
|
428
|
+
task.add_done_callback(self._background_tasks.discard)
|
|
429
|
+
self._messages_sent_count = 1 # CRITICAL: Increment counter to prevent duplicate storage
|
|
430
|
+
|
|
431
|
+
async for output in self.agent.process(env, event):
|
|
432
|
+
yield output
|
|
433
|
+
else:
|
|
434
|
+
async for output in self.agent.process(env, event):
|
|
435
|
+
yield output
|
|
436
|
+
|
|
437
|
+
except Exception as e:
|
|
438
|
+
logger.error(f"[Supermemory] Error in process: {e}")
|
|
439
|
+
async for output in self.agent.process(env, event):
|
|
440
|
+
yield output
|
|
441
|
+
|
|
442
|
+
def reset_memory_tracking(self) -> None:
|
|
443
|
+
"""Reset memory tracking for a new conversation."""
|
|
444
|
+
self._messages_sent_count = 0
|
|
445
|
+
self._last_query = None
|
|
446
|
+
logger.info("[Supermemory] Reset memory tracking state")
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Custom exceptions for Supermemory Cartesia integration."""
|
|
2
|
+
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class SupermemoryCartesiaError(Exception):
|
|
7
|
+
"""Base exception for all Supermemory Cartesia errors."""
|
|
8
|
+
|
|
9
|
+
def __init__(self, message: str, original_error: Optional[Exception] = None):
|
|
10
|
+
super().__init__(message)
|
|
11
|
+
self.message = message
|
|
12
|
+
self.original_error = original_error
|
|
13
|
+
|
|
14
|
+
def __str__(self) -> str:
|
|
15
|
+
if self.original_error:
|
|
16
|
+
return f"{self.message}: {self.original_error}"
|
|
17
|
+
return self.message
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ConfigurationError(SupermemoryCartesiaError):
|
|
21
|
+
"""Raised when there are configuration issues (e.g., missing API key, invalid params)."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class MemoryRetrievalError(SupermemoryCartesiaError):
|
|
25
|
+
"""Raised when memory retrieval operations fail."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class MemoryStorageError(SupermemoryCartesiaError):
|
|
29
|
+
"""Raised when memory storage operations fail."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class APIError(SupermemoryCartesiaError):
|
|
33
|
+
"""Raised when Supermemory API requests fail."""
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
message: str,
|
|
38
|
+
status_code: Optional[int] = None,
|
|
39
|
+
response_text: Optional[str] = None,
|
|
40
|
+
original_error: Optional[Exception] = None,
|
|
41
|
+
):
|
|
42
|
+
super().__init__(message, original_error)
|
|
43
|
+
self.status_code = status_code
|
|
44
|
+
self.response_text = response_text
|
|
45
|
+
|
|
46
|
+
def __str__(self) -> str:
|
|
47
|
+
parts = [self.message]
|
|
48
|
+
if self.status_code:
|
|
49
|
+
parts.append(f"Status: {self.status_code}")
|
|
50
|
+
if self.response_text:
|
|
51
|
+
parts.append(f"Response: {self.response_text}")
|
|
52
|
+
if self.original_error:
|
|
53
|
+
parts.append(f"Cause: {self.original_error}")
|
|
54
|
+
return " | ".join(parts)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class NetworkError(SupermemoryCartesiaError):
|
|
58
|
+
"""Raised when network operations fail."""
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Utility functions for Supermemory Cartesia integration."""
|
|
2
|
+
|
|
3
|
+
from datetime import datetime, timezone
|
|
4
|
+
from typing import Any, Dict, List, Union
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def get_last_user_message(messages: List[Dict[str, str]]) -> str | None:
|
|
8
|
+
"""Extract the last user message content from a list of messages."""
|
|
9
|
+
for msg in reversed(messages):
|
|
10
|
+
if msg["role"] == "user":
|
|
11
|
+
return msg["content"]
|
|
12
|
+
return None
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def format_relative_time(iso_timestamp: str) -> str:
|
|
16
|
+
"""Convert ISO timestamp to relative time string.
|
|
17
|
+
|
|
18
|
+
Format rules:
|
|
19
|
+
- [just now] - within 30 minutes
|
|
20
|
+
- [Xmins ago] - 30-60 minutes
|
|
21
|
+
- [X hrs ago] - less than 1 day
|
|
22
|
+
- [Xd ago] - less than 1 week
|
|
23
|
+
- [X Jul] - more than 1 week, same year
|
|
24
|
+
- [X Jul, 2023] - different year
|
|
25
|
+
"""
|
|
26
|
+
try:
|
|
27
|
+
dt = datetime.fromisoformat(iso_timestamp.replace("Z", "+00:00"))
|
|
28
|
+
now = datetime.now(timezone.utc)
|
|
29
|
+
diff = now - dt
|
|
30
|
+
|
|
31
|
+
seconds = diff.total_seconds()
|
|
32
|
+
minutes = seconds / 60
|
|
33
|
+
hours = seconds / 3600
|
|
34
|
+
days = seconds / 86400
|
|
35
|
+
|
|
36
|
+
if minutes < 30:
|
|
37
|
+
return "just now"
|
|
38
|
+
elif minutes < 60:
|
|
39
|
+
return f"{int(minutes)}mins ago"
|
|
40
|
+
elif hours < 24:
|
|
41
|
+
return f"{int(hours)} hrs ago"
|
|
42
|
+
elif days < 7:
|
|
43
|
+
return f"{int(days)}d ago"
|
|
44
|
+
elif dt.year == now.year:
|
|
45
|
+
return f"{dt.day} {dt.strftime('%b')}"
|
|
46
|
+
else:
|
|
47
|
+
return f"{dt.day} {dt.strftime('%b')}, {dt.year}"
|
|
48
|
+
except Exception:
|
|
49
|
+
return ""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def deduplicate_memories(
|
|
53
|
+
static: List[str],
|
|
54
|
+
dynamic: List[str],
|
|
55
|
+
search_results: List[Dict[str, Any]],
|
|
56
|
+
) -> Dict[str, Union[List[str], List[Dict[str, Any]]]]:
|
|
57
|
+
"""Deduplicate memories. Priority: static > dynamic > search.
|
|
58
|
+
|
|
59
|
+
Args:
|
|
60
|
+
static: List of static memory strings.
|
|
61
|
+
dynamic: List of dynamic memory strings.
|
|
62
|
+
search_results: List of search result dicts with 'memory' and 'updatedAt'.
|
|
63
|
+
"""
|
|
64
|
+
seen = set()
|
|
65
|
+
|
|
66
|
+
def unique_strings(memories: List[str]) -> List[str]:
|
|
67
|
+
out = []
|
|
68
|
+
for m in memories:
|
|
69
|
+
if m not in seen:
|
|
70
|
+
seen.add(m)
|
|
71
|
+
out.append(m)
|
|
72
|
+
return out
|
|
73
|
+
|
|
74
|
+
def unique_search(results: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
|
75
|
+
out = []
|
|
76
|
+
for r in results:
|
|
77
|
+
memory = r.get("memory", "")
|
|
78
|
+
if memory and memory not in seen:
|
|
79
|
+
seen.add(memory)
|
|
80
|
+
out.append(r)
|
|
81
|
+
return out
|
|
82
|
+
|
|
83
|
+
return {
|
|
84
|
+
"static": unique_strings(static),
|
|
85
|
+
"dynamic": unique_strings(dynamic),
|
|
86
|
+
"search_results": unique_search(search_results),
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def format_memories_to_text(
|
|
91
|
+
memories: Dict[str, Union[List[str], List[Dict[str, Any]]]],
|
|
92
|
+
system_prompt: str = "Based on previous conversations, I recall:\n\n",
|
|
93
|
+
include_static: bool = True,
|
|
94
|
+
include_dynamic: bool = True,
|
|
95
|
+
include_search: bool = True,
|
|
96
|
+
) -> str:
|
|
97
|
+
"""Format deduplicated memories into a text string for injection.
|
|
98
|
+
|
|
99
|
+
Search results include temporal context (e.g., '3d ago') from updatedAt.
|
|
100
|
+
"""
|
|
101
|
+
sections = []
|
|
102
|
+
|
|
103
|
+
static = memories["static"]
|
|
104
|
+
dynamic = memories["dynamic"]
|
|
105
|
+
search_results = memories["search_results"]
|
|
106
|
+
|
|
107
|
+
if include_static and static:
|
|
108
|
+
sections.append("## User Profile (Persistent)")
|
|
109
|
+
sections.append("\n".join(f"- {item}" for item in static))
|
|
110
|
+
|
|
111
|
+
if include_dynamic and dynamic:
|
|
112
|
+
sections.append("## Recent Context")
|
|
113
|
+
sections.append("\n".join(f"- {item}" for item in dynamic))
|
|
114
|
+
|
|
115
|
+
if include_search and search_results:
|
|
116
|
+
sections.append("## Relevant Memories")
|
|
117
|
+
lines = []
|
|
118
|
+
for item in search_results:
|
|
119
|
+
if isinstance(item, dict):
|
|
120
|
+
memory = item.get("memory", "")
|
|
121
|
+
updated_at = item.get("updatedAt", "")
|
|
122
|
+
time_str = format_relative_time(updated_at) if updated_at else ""
|
|
123
|
+
if time_str:
|
|
124
|
+
lines.append(f"- [{time_str}] {memory}")
|
|
125
|
+
else:
|
|
126
|
+
lines.append(f"- {memory}")
|
|
127
|
+
else:
|
|
128
|
+
lines.append(f"- {item}")
|
|
129
|
+
sections.append("\n".join(lines))
|
|
130
|
+
|
|
131
|
+
if not sections:
|
|
132
|
+
return ""
|
|
133
|
+
|
|
134
|
+
return f"{system_prompt}\n" + "\n\n".join(sections)
|