1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
|
"""Supermemory tools for OpenAI function calling."""
import json
from typing import Dict, List, Optional, Union, TypedDict
from openai.types.chat import (
ChatCompletionMessageToolCall,
ChatCompletionToolMessageParam,
ChatCompletionFunctionToolParam,
)
import supermemory
from supermemory.types import (
MemoryAddResponse,
MemoryGetResponse,
SearchExecuteResponse,
)
from supermemory.types.search_execute_response import Result
from .exceptions import (
SupermemoryConfigurationError,
SupermemoryMemoryOperationError,
SupermemoryNetworkError,
)
class SupermemoryToolsConfig(TypedDict, total=False):
"""Configuration for Supermemory tools.
Only one of `project_id` or `container_tags` can be provided.
"""
base_url: Optional[str]
container_tags: Optional[List[str]]
project_id: Optional[str]
# Type aliases using inferred types from supermemory package
MemoryObject = Union[MemoryGetResponse, MemoryAddResponse]
class MemorySearchResult(TypedDict, total=False):
"""Result type for memory search operations."""
success: bool
results: Optional[List[Result]]
count: Optional[int]
error: Optional[str]
class MemoryAddResult(TypedDict, total=False):
"""Result type for memory add operations."""
success: bool
memory: Optional[MemoryAddResponse]
error: Optional[str]
# Function schemas for OpenAI function calling
MEMORY_TOOL_SCHEMAS: Dict[str, ChatCompletionFunctionToolParam] = {
"search_memories": {
"name": "search_memories",
"description": (
"Search (recall) memories/details/information about the user or other facts or entities. Run when explicitly asked or when context about user's past choices would be helpful."
),
"parameters": {
"type": "object",
"properties": {
"information_to_get": {
"type": "string",
"description": "Terms to search for in the user's memories",
},
"include_full_docs": {
"type": "boolean",
"description": (
"Whether to include the full document content in the response. "
"Defaults to true for better AI context."
),
"default": True,
},
"limit": {
"type": "number",
"description": "Maximum number of results to return",
"default": 10,
},
},
"required": ["information_to_get"],
},
},
"add_memory": {
"name": "add_memory",
"description": (
"Add (remember) memories/details/information about the user or other facts or entities. Run when explicitly asked or when the user mentions any information generalizable beyond the context of the current conversation."
),
"parameters": {
"type": "object",
"properties": {
"memory": {
"type": "string",
"description": (
"The text content of the memory to add. This should be a "
"single sentence or a short paragraph."
),
},
},
"required": ["memory"],
},
},
}
class SupermemoryTools:
"""Create memory tool handlers for OpenAI function calling."""
def __init__(self, api_key: str, config: Optional[SupermemoryToolsConfig] = None):
"""Initialize SupermemoryTools.
Args:
api_key: Supermemory API key
config: Optional configuration
"""
config = config or {}
# Initialize Supermemory client
client_kwargs = {"api_key": api_key}
if config.get("base_url"):
client_kwargs["base_url"] = config["base_url"]
self.client = supermemory.Supermemory(**client_kwargs)
# Set container tags
if config.get("project_id"):
self.container_tags = [f"sm_project_{config['project_id']}"]
elif config.get("container_tags"):
self.container_tags = config["container_tags"]
else:
self.container_tags = ["sm_project_default"]
def get_tool_definitions(self) -> List[ChatCompletionFunctionToolParam]:
"""Get OpenAI function definitions for all memory tools.
Returns:
List of ChatCompletionToolParam definitions
"""
return [
{"type": "function", "function": MEMORY_TOOL_SCHEMAS["search_memories"]},
{"type": "function", "function": MEMORY_TOOL_SCHEMAS["add_memory"]},
]
async def execute_tool_call(self, tool_call: ChatCompletionMessageToolCall) -> str:
"""Execute a tool call based on the function name and arguments.
Args:
tool_call: The tool call from OpenAI
Returns:
JSON string result
"""
function_name = tool_call.function.name
args = json.loads(tool_call.function.arguments)
if function_name == "search_memories":
result = await self.search_memories(**args)
elif function_name == "add_memory":
result = await self.add_memory(**args)
else:
result = {
"success": False,
"error": f"Unknown function: {function_name}",
}
return json.dumps(result)
async def search_memories(
self,
information_to_get: str,
include_full_docs: bool = True,
limit: int = 10,
) -> MemorySearchResult:
"""Search memories.
Args:
information_to_get: Terms to search for
include_full_docs: Whether to include full document content
limit: Maximum number of results
Returns:
MemorySearchResult
"""
try:
response: SearchExecuteResponse = await self.client.search.execute(
q=information_to_get,
container_tags=self.container_tags,
limit=limit,
chunk_threshold=0.6,
include_full_docs=include_full_docs,
)
return MemorySearchResult(
success=True,
results=response.results,
count=len(response.results),
)
except (OSError, ConnectionError) as network_error:
return MemorySearchResult(
success=False,
error=f"Network error: {network_error}",
)
except Exception as error:
return MemorySearchResult(
success=False,
error=f"Memory search failed: {error}",
)
async def add_memory(self, memory: str) -> MemoryAddResult:
"""Add a memory.
Args:
memory: The memory content to add
Returns:
MemoryAddResult
"""
try:
metadata: Dict[str, object] = {}
add_params = {
"content": memory,
"container_tags": self.container_tags,
}
if metadata:
add_params["metadata"] = metadata
response: MemoryAddResponse = await self.client.memories.add(**add_params)
return MemoryAddResult(
success=True,
memory=response,
)
except (OSError, ConnectionError) as network_error:
return MemoryAddResult(
success=False,
error=f"Network error: {network_error}",
)
except Exception as error:
return MemoryAddResult(
success=False,
error=f"Memory add failed: {error}",
)
def create_supermemory_tools(
api_key: str, config: Optional[SupermemoryToolsConfig] = None
) -> SupermemoryTools:
"""Helper function to create SupermemoryTools instance.
Args:
api_key: Supermemory API key
config: Optional configuration
Returns:
SupermemoryTools instance
"""
return SupermemoryTools(api_key, config)
def get_memory_tool_definitions() -> List[ChatCompletionFunctionToolParam]:
"""Get OpenAI function definitions for memory tools.
Returns:
List of ChatCompletionToolParam definitions
"""
return [
{"type": "function", "function": MEMORY_TOOL_SCHEMAS["search_memories"]},
{"type": "function", "function": MEMORY_TOOL_SCHEMAS["add_memory"]},
]
async def execute_memory_tool_calls(
api_key: str,
tool_calls: List[ChatCompletionMessageToolCall],
config: Optional[SupermemoryToolsConfig] = None,
) -> List[ChatCompletionToolMessageParam]:
"""Execute tool calls from OpenAI function calling.
Args:
api_key: Supermemory API key
tool_calls: List of tool calls from OpenAI
config: Optional configuration
Returns:
List of tool message parameters
"""
tools = SupermemoryTools(api_key, config)
async def execute_single_call(
tool_call: ChatCompletionMessageToolCall,
) -> ChatCompletionToolMessageParam:
result = await tools.execute_tool_call(tool_call)
return ChatCompletionToolMessageParam(
tool_call_id=tool_call.id,
role="tool",
content=result,
)
# Execute all tool calls concurrently
import asyncio
results = await asyncio.gather(
*[execute_single_call(tool_call) for tool_call in tool_calls]
)
return results
# Individual tool creators for more granular control
class SearchMemoriesTool:
"""Individual search memories tool."""
def __init__(self, api_key: str, config: Optional[SupermemoryToolsConfig] = None):
self.tools = SupermemoryTools(api_key, config)
self.definition: ChatCompletionToolParam = {
"type": "function",
"function": MEMORY_TOOL_SCHEMAS["search_memories"],
}
async def execute(
self,
information_to_get: str,
include_full_docs: bool = True,
limit: int = 10,
) -> MemorySearchResult:
"""Execute search memories."""
return await self.tools.search_memories(
information_to_get=information_to_get,
include_full_docs=include_full_docs,
limit=limit,
)
class AddMemoryTool:
"""Individual add memory tool."""
def __init__(self, api_key: str, config: Optional[SupermemoryToolsConfig] = None):
self.tools = SupermemoryTools(api_key, config)
self.definition: ChatCompletionToolParam = {
"type": "function",
"function": MEMORY_TOOL_SCHEMAS["add_memory"],
}
async def execute(self, memory: str) -> MemoryAddResult:
"""Execute add memory."""
return await self.tools.add_memory(memory=memory)
def create_search_memories_tool(
api_key: str, config: Optional[SupermemoryToolsConfig] = None
) -> SearchMemoriesTool:
"""Create individual search memories tool.
Args:
api_key: Supermemory API key
config: Optional configuration
Returns:
SearchMemoriesTool instance
"""
return SearchMemoriesTool(api_key, config)
def create_add_memory_tool(
api_key: str, config: Optional[SupermemoryToolsConfig] = None
) -> AddMemoryTool:
"""Create individual add memory tool.
Args:
api_key: Supermemory API key
config: Optional configuration
Returns:
AddMemoryTool instance
"""
return AddMemoryTool(api_key, config)
|