supermemory-openai-sdk 1.0.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.
src/__init__.py ADDED
@@ -0,0 +1,36 @@
1
+ """Supermemory OpenAI SDK - Memory tools for OpenAI function calling."""
2
+
3
+ from .tools import (
4
+ SupermemoryTools,
5
+ SupermemoryToolsConfig,
6
+ MemoryObject,
7
+ MemorySearchResult,
8
+ MemoryAddResult,
9
+ SearchMemoriesTool,
10
+ AddMemoryTool,
11
+ MEMORY_TOOL_SCHEMAS,
12
+ create_supermemory_tools,
13
+ get_memory_tool_definitions,
14
+ execute_memory_tool_calls,
15
+ create_search_memories_tool,
16
+ create_add_memory_tool,
17
+ )
18
+
19
+ __version__ = "0.1.0"
20
+
21
+ __all__ = [
22
+ # Tools
23
+ "SupermemoryTools",
24
+ "SupermemoryToolsConfig",
25
+ "MemoryObject",
26
+ "MemorySearchResult",
27
+ "MemoryAddResult",
28
+ "SearchMemoriesTool",
29
+ "AddMemoryTool",
30
+ "MEMORY_TOOL_SCHEMAS",
31
+ "create_supermemory_tools",
32
+ "get_memory_tool_definitions",
33
+ "execute_memory_tool_calls",
34
+ "create_search_memories_tool",
35
+ "create_add_memory_tool",
36
+ ]
src/tools.py ADDED
@@ -0,0 +1,366 @@
1
+ """Supermemory tools for OpenAI function calling."""
2
+
3
+ import json
4
+ from typing import Dict, List, Optional, Union, TypedDict
5
+
6
+ from openai.types.chat import (
7
+ ChatCompletionMessageToolCall,
8
+ ChatCompletionToolMessageParam,
9
+ ChatCompletionToolParam,
10
+ )
11
+ import supermemory
12
+ from supermemory.types import (
13
+ MemoryAddResponse,
14
+ MemoryGetResponse,
15
+ SearchExecuteResponse,
16
+ )
17
+ from supermemory.types.search_execute_response import Result
18
+
19
+
20
+ class SupermemoryToolsConfig(TypedDict, total=False):
21
+ """Configuration for Supermemory tools.
22
+
23
+ Only one of `project_id` or `container_tags` can be provided.
24
+ """
25
+
26
+ base_url: Optional[str]
27
+ container_tags: Optional[List[str]]
28
+ project_id: Optional[str]
29
+
30
+
31
+ # Type aliases using inferred types from supermemory package
32
+ MemoryObject = Union[MemoryGetResponse, MemoryAddResponse]
33
+
34
+
35
+ class MemorySearchResult(TypedDict, total=False):
36
+ """Result type for memory search operations."""
37
+
38
+ success: bool
39
+ results: Optional[List[Result]]
40
+ count: Optional[int]
41
+ error: Optional[str]
42
+
43
+
44
+ class MemoryAddResult(TypedDict, total=False):
45
+ """Result type for memory add operations."""
46
+
47
+ success: bool
48
+ memory: Optional[MemoryAddResponse]
49
+ error: Optional[str]
50
+
51
+
52
+ # Function schemas for OpenAI function calling
53
+ MEMORY_TOOL_SCHEMAS = {
54
+ "search_memories": {
55
+ "name": "search_memories",
56
+ "description": (
57
+ "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."
58
+ ),
59
+ "parameters": {
60
+ "type": "object",
61
+ "properties": {
62
+ "information_to_get": {
63
+ "type": "string",
64
+ "description": "Terms to search for in the user's memories",
65
+ },
66
+ "include_full_docs": {
67
+ "type": "boolean",
68
+ "description": (
69
+ "Whether to include the full document content in the response. "
70
+ "Defaults to true for better AI context."
71
+ ),
72
+ "default": True,
73
+ },
74
+ "limit": {
75
+ "type": "number",
76
+ "description": "Maximum number of results to return",
77
+ "default": 10,
78
+ },
79
+ },
80
+ "required": ["information_to_get"],
81
+ },
82
+ },
83
+ "add_memory": {
84
+ "name": "add_memory",
85
+ "description": (
86
+ "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."
87
+ ),
88
+ "parameters": {
89
+ "type": "object",
90
+ "properties": {
91
+ "memory": {
92
+ "type": "string",
93
+ "description": (
94
+ "The text content of the memory to add. This should be a "
95
+ "single sentence or a short paragraph."
96
+ ),
97
+ },
98
+ },
99
+ "required": ["memory"],
100
+ },
101
+ },
102
+ }
103
+
104
+
105
+ class SupermemoryTools:
106
+ """Create memory tool handlers for OpenAI function calling."""
107
+
108
+ def __init__(self, api_key: str, config: Optional[SupermemoryToolsConfig] = None):
109
+ """Initialize SupermemoryTools.
110
+
111
+ Args:
112
+ api_key: Supermemory API key
113
+ config: Optional configuration
114
+ """
115
+ config = config or {}
116
+
117
+ # Initialize Supermemory client
118
+ client_kwargs = {"api_key": api_key}
119
+ if config.get("base_url"):
120
+ client_kwargs["base_url"] = config["base_url"]
121
+
122
+ self.client = supermemory.Supermemory(**client_kwargs)
123
+
124
+ # Set container tags
125
+ if config.get("project_id"):
126
+ self.container_tags = [f"sm_project_{config['project_id']}"]
127
+ elif config.get("container_tags"):
128
+ self.container_tags = config["container_tags"]
129
+ else:
130
+ self.container_tags = ["sm_project_default"]
131
+
132
+ def get_tool_definitions(self) -> List[ChatCompletionToolParam]:
133
+ """Get OpenAI function definitions for all memory tools.
134
+
135
+ Returns:
136
+ List of ChatCompletionToolParam definitions
137
+ """
138
+ return [
139
+ {"type": "function", "function": MEMORY_TOOL_SCHEMAS["search_memories"]},
140
+ {"type": "function", "function": MEMORY_TOOL_SCHEMAS["add_memory"]},
141
+ ]
142
+
143
+ async def execute_tool_call(self, tool_call: ChatCompletionMessageToolCall) -> str:
144
+ """Execute a tool call based on the function name and arguments.
145
+
146
+ Args:
147
+ tool_call: The tool call from OpenAI
148
+
149
+ Returns:
150
+ JSON string result
151
+ """
152
+ function_name = tool_call.function.name
153
+ args = json.loads(tool_call.function.arguments)
154
+
155
+ if function_name == "search_memories":
156
+ result = await self.search_memories(**args)
157
+ elif function_name == "add_memory":
158
+ result = await self.add_memory(**args)
159
+ else:
160
+ result = {
161
+ "success": False,
162
+ "error": f"Unknown function: {function_name}",
163
+ }
164
+
165
+ return json.dumps(result)
166
+
167
+ async def search_memories(
168
+ self,
169
+ information_to_get: str,
170
+ include_full_docs: bool = True,
171
+ limit: int = 10,
172
+ ) -> MemorySearchResult:
173
+ """Search memories.
174
+
175
+ Args:
176
+ information_to_get: Terms to search for
177
+ include_full_docs: Whether to include full document content
178
+ limit: Maximum number of results
179
+
180
+ Returns:
181
+ MemorySearchResult
182
+ """
183
+ try:
184
+ response: SearchExecuteResponse = await self.client.search.execute(
185
+ q=information_to_get,
186
+ container_tags=self.container_tags,
187
+ limit=limit,
188
+ chunk_threshold=0.6,
189
+ include_full_docs=include_full_docs,
190
+ )
191
+
192
+ return MemorySearchResult(
193
+ success=True,
194
+ results=response.results,
195
+ count=len(response.results),
196
+ )
197
+ except Exception as error:
198
+ return MemorySearchResult(
199
+ success=False,
200
+ error=str(error),
201
+ )
202
+
203
+ async def add_memory(self, memory: str) -> MemoryAddResult:
204
+ """Add a memory.
205
+
206
+ Args:
207
+ memory: The memory content to add
208
+
209
+ Returns:
210
+ MemoryAddResult
211
+ """
212
+ try:
213
+ metadata: Dict[str, object] = {}
214
+
215
+ add_params = {
216
+ "content": memory,
217
+ "container_tags": self.container_tags,
218
+ }
219
+ if metadata:
220
+ add_params["metadata"] = metadata
221
+
222
+ response: MemoryAddResponse = await self.client.memories.add(**add_params)
223
+
224
+ return MemoryAddResult(
225
+ success=True,
226
+ memory=response,
227
+ )
228
+ except Exception as error:
229
+ return MemoryAddResult(
230
+ success=False,
231
+ error=str(error),
232
+ )
233
+
234
+
235
+ def create_supermemory_tools(
236
+ api_key: str, config: Optional[SupermemoryToolsConfig] = None
237
+ ) -> SupermemoryTools:
238
+ """Helper function to create SupermemoryTools instance.
239
+
240
+ Args:
241
+ api_key: Supermemory API key
242
+ config: Optional configuration
243
+
244
+ Returns:
245
+ SupermemoryTools instance
246
+ """
247
+ return SupermemoryTools(api_key, config)
248
+
249
+
250
+ def get_memory_tool_definitions() -> List[ChatCompletionToolParam]:
251
+ """Get OpenAI function definitions for memory tools.
252
+
253
+ Returns:
254
+ List of ChatCompletionToolParam definitions
255
+ """
256
+ return [
257
+ {"type": "function", "function": MEMORY_TOOL_SCHEMAS["search_memories"]},
258
+ {"type": "function", "function": MEMORY_TOOL_SCHEMAS["add_memory"]},
259
+ ]
260
+
261
+
262
+ async def execute_memory_tool_calls(
263
+ api_key: str,
264
+ tool_calls: List[ChatCompletionMessageToolCall],
265
+ config: Optional[SupermemoryToolsConfig] = None,
266
+ ) -> List[ChatCompletionToolMessageParam]:
267
+ """Execute tool calls from OpenAI function calling.
268
+
269
+ Args:
270
+ api_key: Supermemory API key
271
+ tool_calls: List of tool calls from OpenAI
272
+ config: Optional configuration
273
+
274
+ Returns:
275
+ List of tool message parameters
276
+ """
277
+ tools = SupermemoryTools(api_key, config)
278
+
279
+ async def execute_single_call(
280
+ tool_call: ChatCompletionMessageToolCall,
281
+ ) -> ChatCompletionToolMessageParam:
282
+ result = await tools.execute_tool_call(tool_call)
283
+ return ChatCompletionToolMessageParam(
284
+ tool_call_id=tool_call.id,
285
+ role="tool",
286
+ content=result,
287
+ )
288
+
289
+ # Execute all tool calls concurrently
290
+ import asyncio
291
+
292
+ results = await asyncio.gather(
293
+ *[execute_single_call(tool_call) for tool_call in tool_calls]
294
+ )
295
+
296
+ return results
297
+
298
+
299
+ # Individual tool creators for more granular control
300
+ class SearchMemoriesTool:
301
+ """Individual search memories tool."""
302
+
303
+ def __init__(self, api_key: str, config: Optional[SupermemoryToolsConfig] = None):
304
+ self.tools = SupermemoryTools(api_key, config)
305
+ self.definition: ChatCompletionToolParam = {
306
+ "type": "function",
307
+ "function": MEMORY_TOOL_SCHEMAS["search_memories"],
308
+ }
309
+
310
+ async def execute(
311
+ self,
312
+ information_to_get: str,
313
+ include_full_docs: bool = True,
314
+ limit: int = 10,
315
+ ) -> MemorySearchResult:
316
+ """Execute search memories."""
317
+ return await self.tools.search_memories(
318
+ information_to_get=information_to_get,
319
+ include_full_docs=include_full_docs,
320
+ limit=limit,
321
+ )
322
+
323
+
324
+ class AddMemoryTool:
325
+ """Individual add memory tool."""
326
+
327
+ def __init__(self, api_key: str, config: Optional[SupermemoryToolsConfig] = None):
328
+ self.tools = SupermemoryTools(api_key, config)
329
+ self.definition: ChatCompletionToolParam = {
330
+ "type": "function",
331
+ "function": MEMORY_TOOL_SCHEMAS["add_memory"],
332
+ }
333
+
334
+ async def execute(self, memory: str) -> MemoryAddResult:
335
+ """Execute add memory."""
336
+ return await self.tools.add_memory(memory=memory)
337
+
338
+
339
+ def create_search_memories_tool(
340
+ api_key: str, config: Optional[SupermemoryToolsConfig] = None
341
+ ) -> SearchMemoriesTool:
342
+ """Create individual search memories tool.
343
+
344
+ Args:
345
+ api_key: Supermemory API key
346
+ config: Optional configuration
347
+
348
+ Returns:
349
+ SearchMemoriesTool instance
350
+ """
351
+ return SearchMemoriesTool(api_key, config)
352
+
353
+
354
+ def create_add_memory_tool(
355
+ api_key: str, config: Optional[SupermemoryToolsConfig] = None
356
+ ) -> AddMemoryTool:
357
+ """Create individual add memory tool.
358
+
359
+ Args:
360
+ api_key: Supermemory API key
361
+ config: Optional configuration
362
+
363
+ Returns:
364
+ AddMemoryTool instance
365
+ """
366
+ return AddMemoryTool(api_key, config)
@@ -0,0 +1,256 @@
1
+ Metadata-Version: 2.4
2
+ Name: supermemory-openai-sdk
3
+ Version: 1.0.0
4
+ Summary: Memory tools for OpenAI function calling with supermemory
5
+ Project-URL: Homepage, https://supermemory.ai
6
+ Project-URL: Repository, https://github.com/supermemoryai/supermemory
7
+ Project-URL: Documentation, https://supermemory.ai/docs
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: ai,memory,openai,supermemory
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Requires-Python: >=3.8.1
23
+ Requires-Dist: openai>=1.102.0
24
+ Requires-Dist: supermemory>=3.0.0a28
25
+ Requires-Dist: typing-extensions>=4.0.0
26
+ Description-Content-Type: text/markdown
27
+
28
+ # Supermemory OpenAI Python SDK
29
+
30
+ Memory tools for OpenAI function calling with Supermemory integration.
31
+
32
+ This package provides memory management tools for the official [OpenAI Python SDK](https://github.com/openai/openai-python) using [Supermemory](https://supermemory.ai) capabilities.
33
+
34
+ ## Installation
35
+
36
+ Install using uv (recommended):
37
+
38
+ ```bash
39
+ uv add supermemory-openai
40
+ ```
41
+
42
+ Or with pip:
43
+
44
+ ```bash
45
+ pip install supermemory-openai
46
+ ```
47
+
48
+ ## Quick Start
49
+
50
+ ### Using Memory Tools with OpenAI
51
+
52
+ ```python
53
+ import asyncio
54
+ import openai
55
+ from supermemory_openai import SupermemoryTools, execute_memory_tool_calls
56
+
57
+ async def main():
58
+ # Initialize OpenAI client
59
+ client = openai.AsyncOpenAI(api_key="your-openai-api-key")
60
+
61
+ # Initialize Supermemory tools
62
+ tools = SupermemoryTools(
63
+ api_key="your-supermemory-api-key",
64
+ config={"project_id": "my-project"}
65
+ )
66
+
67
+ # Chat with memory tools
68
+ response = await client.chat.completions.create(
69
+ model="gpt-4o",
70
+ messages=[
71
+ {
72
+ "role": "system",
73
+ "content": "You are a helpful assistant with access to user memories."
74
+ },
75
+ {
76
+ "role": "user",
77
+ "content": "Remember that I prefer tea over coffee"
78
+ }
79
+ ],
80
+ tools=tools.get_tool_definitions()
81
+ )
82
+
83
+ # Handle tool calls if present
84
+ if response.choices[0].message.tool_calls:
85
+ tool_results = await execute_memory_tool_calls(
86
+ api_key="your-supermemory-api-key",
87
+ tool_calls=response.choices[0].message.tool_calls,
88
+ config={"project_id": "my-project"}
89
+ )
90
+ print("Tool results:", tool_results)
91
+
92
+ print(response.choices[0].message.content)
93
+
94
+ asyncio.run(main())
95
+ ```
96
+
97
+ ## Configuration
98
+
99
+ ## Memory Tools
100
+
101
+ ### SupermemoryTools Class
102
+
103
+ ```python
104
+ from supermemory_openai import SupermemoryTools
105
+
106
+ tools = SupermemoryTools(
107
+ api_key="your-supermemory-api-key",
108
+ config={
109
+ "project_id": "my-project", # or use container_tags
110
+ "base_url": "https://custom-endpoint.com", # optional
111
+ }
112
+ )
113
+
114
+ # Search memories
115
+ result = await tools.search_memories(
116
+ information_to_get="user preferences",
117
+ limit=10,
118
+ include_full_docs=True
119
+ )
120
+
121
+ # Add memory
122
+ result = await tools.add_memory(
123
+ memory="User prefers tea over coffee"
124
+ )
125
+
126
+ # Fetch specific memory
127
+ result = await tools.fetch_memory(
128
+ memory_id="memory-id-here"
129
+ )
130
+ ```
131
+
132
+ ### Individual Tools
133
+
134
+ ```python
135
+ from supermemory_openai import (
136
+ create_search_memories_tool,
137
+ create_add_memory_tool,
138
+ create_fetch_memory_tool
139
+ )
140
+
141
+ search_tool = create_search_memories_tool("your-api-key")
142
+ add_tool = create_add_memory_tool("your-api-key")
143
+ fetch_tool = create_fetch_memory_tool("your-api-key")
144
+ ```
145
+
146
+ ### Function Calling Integration
147
+
148
+ ```python
149
+ from supermemory_openai import execute_memory_tool_calls
150
+
151
+ # After getting tool calls from OpenAI
152
+ if response.choices[0].message.tool_calls:
153
+ tool_results = await execute_memory_tool_calls(
154
+ api_key="your-supermemory-api-key",
155
+ tool_calls=response.choices[0].message.tool_calls,
156
+ config={"project_id": "my-project"}
157
+ )
158
+
159
+ # Add tool results to conversation
160
+ messages.append(response.choices[0].message)
161
+ messages.extend(tool_results)
162
+ ```
163
+
164
+ ## API Reference
165
+
166
+ ### SupermemoryTools
167
+
168
+ Memory management tools for function calling.
169
+
170
+ #### Constructor
171
+
172
+ ```python
173
+ SupermemoryTools(
174
+ api_key: str,
175
+ config: Optional[SupermemoryToolsConfig] = None
176
+ )
177
+ ```
178
+
179
+ #### Methods
180
+
181
+ - `get_tool_definitions()` - Get OpenAI function definitions
182
+ - `search_memories()` - Search user memories
183
+ - `add_memory()` - Add new memory
184
+ - `fetch_memory()` - Fetch specific memory by ID
185
+ - `execute_tool_call()` - Execute individual tool call
186
+
187
+ ## Error Handling
188
+
189
+ ```python
190
+ try:
191
+ response = await client.chat_completion(
192
+ messages=[{"role": "user", "content": "Hello"}],
193
+ model="gpt-4o"
194
+ )
195
+ except Exception as e:
196
+ print(f"Error: {e}")
197
+ ```
198
+
199
+ ## Environment Variables
200
+
201
+ Set these environment variables for testing:
202
+
203
+ - `SUPERMEMORY_API_KEY` - Your Supermemory API key
204
+ - `OPENAI_API_KEY` - Your OpenAI API key
205
+ - `MODEL_NAME` - Model to use (default: "gpt-4o-mini")
206
+ - `SUPERMEMORY_BASE_URL` - Custom Supermemory base URL (optional)
207
+
208
+ ## Development
209
+
210
+ ### Setup
211
+
212
+ ```bash
213
+ # Install uv
214
+ curl -LsSf https://astral.sh/uv/install.sh | sh
215
+
216
+ # Clone and setup
217
+ git clone <repository-url>
218
+ cd packages/openai-sdk-python
219
+ uv sync --dev
220
+ ```
221
+
222
+ ### Testing
223
+
224
+ ```bash
225
+ # Run tests
226
+ uv run pytest
227
+
228
+ # Run with coverage
229
+ uv run pytest --cov=supermemory_openai
230
+
231
+ # Run specific test file
232
+ uv run pytest tests/test_infinite_chat.py
233
+ ```
234
+
235
+ ### Type Checking
236
+
237
+ ```bash
238
+ uv run mypy src/supermemory_openai
239
+ ```
240
+
241
+ ### Formatting
242
+
243
+ ```bash
244
+ uv run black src/ tests/
245
+ uv run isort src/ tests/
246
+ ```
247
+
248
+ ## License
249
+
250
+ MIT License - see LICENSE file for details.
251
+
252
+ ## Links
253
+
254
+ - [Supermemory](https://supermemory.ai) - Infinite context memory platform
255
+ - [OpenAI Python SDK](https://github.com/openai/openai-python) - Official OpenAI Python library
256
+ - [Documentation](https://docs.supermemory.ai) - Full API documentation
@@ -0,0 +1,6 @@
1
+ src/__init__.py,sha256=TS-kf3lLC8S_HAq3130aEjfFjVCvVA_xu8rhn_wy6G0,845
2
+ src/tools.py,sha256=5BHxJvJEcRD5CL559pvT3DmNa0CL6j8QfMSFfifd_so,11070
3
+ supermemory_openai_sdk-1.0.0.dist-info/METADATA,sha256=-K1d4Uqp-94-SwmHzJdwWdUEdMOx28yZ_pbqbq17Bhw,6244
4
+ supermemory_openai_sdk-1.0.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
5
+ supermemory_openai_sdk-1.0.0.dist-info/licenses/LICENSE,sha256=6lYiVGf2h1ooI6nxALS8yfG1qwWL5XvvdsTmrI_Y02s,1072
6
+ supermemory_openai_sdk-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Supermemory Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.