@memorylayerai/vercel-ai 0.2.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 MemoryLayer
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,57 @@
1
+ # @memorylayer/vercel-ai
2
+
3
+ Vercel AI SDK integration for MemoryLayer - Add memory-augmented AI to your applications.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @memorylayer/vercel-ai @memorylayer/sdk ai zod
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ### Provider Adapter
14
+
15
+ ```typescript
16
+ import { createMemoryLayerProvider } from '@memorylayer/vercel-ai';
17
+ import { MemoryLayerClient } from '@memorylayer/sdk';
18
+ import { generateText } from 'ai';
19
+
20
+ const client = new MemoryLayerClient({
21
+ apiKey: process.env.MEMORYLAYER_API_KEY!,
22
+ });
23
+
24
+ const provider = createMemoryLayerProvider({
25
+ client,
26
+ projectId: 'proj_abc123',
27
+ });
28
+
29
+ const { text } = await generateText({
30
+ model: provider,
31
+ prompt: 'What are my preferences?',
32
+ });
33
+ ```
34
+
35
+ ### Memory Tools
36
+
37
+ ```typescript
38
+ import { memoryTool, searchTool } from '@memorylayer/vercel-ai';
39
+ import { generateText } from 'ai';
40
+
41
+ const { text } = await generateText({
42
+ model: provider,
43
+ prompt: 'Remember that I prefer dark mode',
44
+ tools: {
45
+ addMemory: memoryTool({ client, projectId: 'proj_abc123' }),
46
+ searchMemory: searchTool({ client, projectId: 'proj_abc123' }),
47
+ },
48
+ });
49
+ ```
50
+
51
+ ## Documentation
52
+
53
+ For full documentation, visit [https://docs.memorylayer.com](https://docs.memorylayer.com)
54
+
55
+ ## License
56
+
57
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,313 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ createGraphTools: () => createGraphTools,
24
+ createMemoryLayerProvider: () => createMemoryLayerProvider,
25
+ graphTool: () => graphTool,
26
+ memoryTool: () => memoryTool,
27
+ nodeDetailsTool: () => nodeDetailsTool,
28
+ nodeEdgesTool: () => nodeEdgesTool,
29
+ searchTool: () => searchTool
30
+ });
31
+ module.exports = __toCommonJS(index_exports);
32
+
33
+ // src/provider.ts
34
+ function createMemoryLayerProvider(config) {
35
+ return {
36
+ specificationVersion: "v1",
37
+ provider: "memorylayer",
38
+ modelId: config.defaultModel || "default",
39
+ /**
40
+ * Generate a completion (non-streaming)
41
+ */
42
+ async doGenerate(options) {
43
+ const messages = options.prompt.map((msg) => ({
44
+ role: msg.role,
45
+ content: msg.content
46
+ }));
47
+ const response = await config.client.router.complete({
48
+ messages,
49
+ projectId: config.projectId,
50
+ model: options.model || config.defaultModel,
51
+ temperature: options.temperature,
52
+ maxTokens: options.maxTokens
53
+ });
54
+ return {
55
+ text: response.choices[0].message.content,
56
+ finishReason: response.choices[0].finishReason,
57
+ usage: {
58
+ promptTokens: response.usage.promptTokens,
59
+ completionTokens: response.usage.completionTokens
60
+ },
61
+ rawCall: {
62
+ rawPrompt: messages,
63
+ rawSettings: {
64
+ model: options.model || config.defaultModel,
65
+ temperature: options.temperature,
66
+ maxTokens: options.maxTokens
67
+ }
68
+ }
69
+ };
70
+ },
71
+ /**
72
+ * Generate a streaming completion
73
+ */
74
+ async doStream(options) {
75
+ const messages = options.prompt.map((msg) => ({
76
+ role: msg.role,
77
+ content: msg.content
78
+ }));
79
+ const stream = config.client.router.stream({
80
+ messages,
81
+ projectId: config.projectId,
82
+ model: options.model || config.defaultModel,
83
+ temperature: options.temperature,
84
+ maxTokens: options.maxTokens,
85
+ stream: true
86
+ });
87
+ const convertedStream = convertToVercelStream(stream);
88
+ return {
89
+ stream: convertedStream,
90
+ rawCall: {
91
+ rawPrompt: messages,
92
+ rawSettings: {
93
+ model: options.model || config.defaultModel,
94
+ temperature: options.temperature,
95
+ maxTokens: options.maxTokens
96
+ }
97
+ }
98
+ };
99
+ }
100
+ };
101
+ }
102
+ async function* convertToVercelStream(stream) {
103
+ try {
104
+ for await (const chunk of stream) {
105
+ yield {
106
+ type: "text-delta",
107
+ textDelta: chunk.choices[0]?.delta?.content || ""
108
+ };
109
+ if (chunk.choices[0]?.finishReason) {
110
+ yield {
111
+ type: "finish",
112
+ finishReason: chunk.choices[0].finishReason
113
+ };
114
+ }
115
+ }
116
+ } catch (error) {
117
+ throw {
118
+ name: "AI_APICallError",
119
+ message: error instanceof Error ? error.message : "Unknown error",
120
+ cause: error
121
+ };
122
+ }
123
+ }
124
+
125
+ // src/tools.ts
126
+ var import_zod = require("zod");
127
+ function memoryTool(config) {
128
+ return {
129
+ description: "Add a memory to the MemoryLayer system for long-term storage",
130
+ parameters: import_zod.z.object({
131
+ content: import_zod.z.string().describe("The content to remember"),
132
+ metadata: import_zod.z.record(import_zod.z.any()).optional().describe("Optional metadata to associate with the memory")
133
+ }),
134
+ execute: async ({ content, metadata }) => {
135
+ try {
136
+ const memory = await config.client.memories.add({
137
+ content,
138
+ metadata,
139
+ projectId: config.projectId
140
+ });
141
+ return {
142
+ success: true,
143
+ memoryId: memory.id,
144
+ message: `Memory stored successfully with ID: ${memory.id}`
145
+ };
146
+ } catch (error) {
147
+ return {
148
+ success: false,
149
+ error: error instanceof Error ? error.message : "Unknown error"
150
+ };
151
+ }
152
+ }
153
+ };
154
+ }
155
+ function searchTool(config) {
156
+ return {
157
+ description: "Search memories in the MemoryLayer system to retrieve relevant information",
158
+ parameters: import_zod.z.object({
159
+ query: import_zod.z.string().describe("The search query to find relevant memories"),
160
+ limit: import_zod.z.number().optional().describe("Maximum number of results to return (default: 10)"),
161
+ threshold: import_zod.z.number().optional().describe("Minimum relevance score threshold (0-1)")
162
+ }),
163
+ execute: async ({ query, limit, threshold }) => {
164
+ try {
165
+ const response = await config.client.search.search({
166
+ query,
167
+ projectId: config.projectId,
168
+ limit,
169
+ threshold
170
+ });
171
+ return {
172
+ success: true,
173
+ results: response.results.map((r) => ({
174
+ content: r.memory.content,
175
+ score: r.score,
176
+ metadata: r.memory.metadata,
177
+ id: r.memory.id
178
+ })),
179
+ total: response.total
180
+ };
181
+ } catch (error) {
182
+ return {
183
+ success: false,
184
+ error: error instanceof Error ? error.message : "Unknown error"
185
+ };
186
+ }
187
+ }
188
+ };
189
+ }
190
+
191
+ // src/graph.ts
192
+ var import_ai = require("ai");
193
+ var import_zod2 = require("zod");
194
+ function graphTool(config) {
195
+ return (0, import_ai.tool)({
196
+ description: "Fetch memory graph data showing nodes (memories, documents, entities) and their relationships",
197
+ parameters: import_zod2.z.object({
198
+ limit: import_zod2.z.number().optional().describe("Maximum number of nodes to return (default: 100)"),
199
+ nodeTypes: import_zod2.z.array(import_zod2.z.enum(["memory", "document", "entity"])).optional().describe("Filter by node types"),
200
+ relationshipTypes: import_zod2.z.array(import_zod2.z.enum(["extends", "updates", "derives", "similarity"])).optional().describe("Filter by relationship types"),
201
+ startDate: import_zod2.z.string().optional().describe("Filter nodes created after this date (ISO 8601)"),
202
+ endDate: import_zod2.z.string().optional().describe("Filter nodes created before this date (ISO 8601)")
203
+ }),
204
+ execute: async ({ limit, nodeTypes, relationshipTypes, startDate, endDate }) => {
205
+ const graphData = await config.client.graph.getGraph({
206
+ spaceId: config.spaceId,
207
+ limit,
208
+ nodeTypes,
209
+ relationshipTypes,
210
+ startDate,
211
+ endDate
212
+ });
213
+ return {
214
+ nodes: graphData.nodes.map((n) => ({
215
+ id: n.id,
216
+ type: n.type,
217
+ label: n.label,
218
+ status: n.data.status,
219
+ createdAt: n.data.createdAt
220
+ })),
221
+ edges: graphData.edges.map((e) => ({
222
+ id: e.id,
223
+ source: e.source,
224
+ target: e.target,
225
+ type: e.type,
226
+ label: e.label
227
+ })),
228
+ metadata: graphData.metadata
229
+ };
230
+ }
231
+ });
232
+ }
233
+ function nodeDetailsTool(config) {
234
+ return (0, import_ai.tool)({
235
+ description: "Get detailed information about a specific node in the memory graph",
236
+ parameters: import_zod2.z.object({
237
+ nodeId: import_zod2.z.string().describe("The ID of the node to fetch details for")
238
+ }),
239
+ execute: async ({ nodeId }) => {
240
+ const details = await config.client.graph.getNodeDetails({ nodeId });
241
+ return {
242
+ node: {
243
+ id: details.node.id,
244
+ type: details.node.type,
245
+ label: details.node.label,
246
+ content: details.node.data.content,
247
+ status: details.node.data.status,
248
+ createdAt: details.node.data.createdAt,
249
+ expiresAt: details.node.data.expiresAt,
250
+ metadata: details.node.data.metadata
251
+ },
252
+ connectedNodes: details.connectedNodes.map((n) => ({
253
+ id: n.id,
254
+ type: n.type,
255
+ label: n.label
256
+ })),
257
+ edges: details.edges.map((e) => ({
258
+ id: e.id,
259
+ source: e.source,
260
+ target: e.target,
261
+ type: e.type,
262
+ label: e.label
263
+ }))
264
+ };
265
+ }
266
+ });
267
+ }
268
+ function nodeEdgesTool(config) {
269
+ return (0, import_ai.tool)({
270
+ description: "Get edges and connected nodes for a specific node in the memory graph",
271
+ parameters: import_zod2.z.object({
272
+ nodeId: import_zod2.z.string().describe("The ID of the node to fetch edges for"),
273
+ edgeTypes: import_zod2.z.array(import_zod2.z.enum(["extends", "updates", "derives", "similarity"])).optional().describe("Filter by edge types")
274
+ }),
275
+ execute: async ({ nodeId, edgeTypes }) => {
276
+ const result = await config.client.graph.getNodeEdges({
277
+ nodeId,
278
+ edgeTypes
279
+ });
280
+ return {
281
+ edges: result.edges.map((e) => ({
282
+ id: e.id,
283
+ source: e.source,
284
+ target: e.target,
285
+ type: e.type,
286
+ label: e.label
287
+ })),
288
+ connectedNodes: result.connectedNodes.map((n) => ({
289
+ id: n.id,
290
+ type: n.type,
291
+ label: n.label
292
+ }))
293
+ };
294
+ }
295
+ });
296
+ }
297
+ function createGraphTools(config) {
298
+ return {
299
+ getGraph: graphTool(config),
300
+ getNodeDetails: nodeDetailsTool(config),
301
+ getNodeEdges: nodeEdgesTool(config)
302
+ };
303
+ }
304
+ // Annotate the CommonJS export names for ESM import in node:
305
+ 0 && (module.exports = {
306
+ createGraphTools,
307
+ createMemoryLayerProvider,
308
+ graphTool,
309
+ memoryTool,
310
+ nodeDetailsTool,
311
+ nodeEdgesTool,
312
+ searchTool
313
+ });