mem0ai 2.4.6 → 3.0.0-beta.1

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/dist/index.js CHANGED
@@ -123,6 +123,37 @@ async function captureClientEvent(eventName, instance, additionalData = {}) {
123
123
  );
124
124
  }
125
125
 
126
+ // src/client/utils.ts
127
+ function camelToSnake(str) {
128
+ if (str === str.toUpperCase()) return str;
129
+ return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
130
+ }
131
+ function snakeToCamel(str) {
132
+ return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
133
+ }
134
+ function camelToSnakeKeys(obj) {
135
+ if (obj === null || obj === void 0 || typeof obj !== "object") return obj;
136
+ if (Array.isArray(obj)) return obj.map(camelToSnakeKeys);
137
+ if (obj instanceof Date) return obj;
138
+ return Object.fromEntries(
139
+ Object.entries(obj).map(([key, value]) => [
140
+ camelToSnake(key),
141
+ camelToSnakeKeys(value)
142
+ ])
143
+ );
144
+ }
145
+ function snakeToCamelKeys(obj) {
146
+ if (obj === null || obj === void 0 || typeof obj !== "object") return obj;
147
+ if (Array.isArray(obj)) return obj.map(snakeToCamelKeys);
148
+ if (obj instanceof Date) return obj;
149
+ return Object.fromEntries(
150
+ Object.entries(obj).map(([key, value]) => [
151
+ snakeToCamel(key),
152
+ snakeToCamelKeys(value)
153
+ ])
154
+ );
155
+ }
156
+
126
157
  // src/common/exceptions.ts
127
158
  var MemoryError = class extends Error {
128
159
  constructor(message, errorCode, options = {}) {
@@ -221,6 +252,26 @@ function createExceptionFromResponse(statusCode, responseText, options = {}) {
221
252
  }
222
253
 
223
254
  // src/client/mem0.ts
255
+ var ENTITY_PARAMS = [
256
+ "user_id",
257
+ "agent_id",
258
+ "app_id",
259
+ "run_id",
260
+ "userId",
261
+ "agentId",
262
+ "appId",
263
+ "runId"
264
+ ];
265
+ function rejectTopLevelEntityParams(options, methodName) {
266
+ const invalidKeys = Object.keys(options != null ? options : {}).filter(
267
+ (k) => ENTITY_PARAMS.includes(k)
268
+ );
269
+ if (invalidKeys.length > 0) {
270
+ throw new Error(
271
+ `Top-level entity parameters [${invalidKeys.join(", ")}] are not supported in ${methodName}(). Use filters: { user_id: "..." } instead.`
272
+ );
273
+ }
274
+ }
224
275
  var APIError = class extends Error {
225
276
  constructor(message) {
226
277
  super(message);
@@ -239,25 +290,11 @@ var MemoryClient = class {
239
290
  throw new Error("Mem0 API key cannot be empty");
240
291
  }
241
292
  }
242
- _validateOrgProject() {
243
- if (this.organizationName === null && this.projectName !== null || this.organizationName !== null && this.projectName === null) {
244
- console.warn(
245
- "Warning: Both organizationName and projectName must be provided together when using either. This will be removed from version 1.0.40. Note that organizationName/projectName are being deprecated in favor of organizationId/projectId."
246
- );
247
- }
248
- if (this.organizationId === null && this.projectId !== null || this.organizationId !== null && this.projectId === null) {
249
- console.warn(
250
- "Warning: Both organizationId and projectId must be provided together when using either. This will be removed from version 1.0.40."
251
- );
252
- }
253
- }
254
293
  constructor(options) {
255
294
  this.apiKey = options.apiKey;
256
295
  this.host = options.host || "https://api.mem0.ai";
257
- this.organizationName = options.organizationName || null;
258
- this.projectName = options.projectName || null;
259
- this.organizationId = options.organizationId || null;
260
- this.projectId = options.projectId || null;
296
+ this.organizationId = null;
297
+ this.projectId = null;
261
298
  this.headers = {
262
299
  Authorization: `Token ${this.apiKey}`,
263
300
  "Content-Type": "application/json"
@@ -277,9 +314,7 @@ var MemoryClient = class {
277
314
  if (!this.telemetryId) {
278
315
  this.telemetryId = generateHash(this.apiKey);
279
316
  }
280
- this._validateOrgProject();
281
317
  captureClientEvent("init", this, {
282
- api_version: "v1",
283
318
  client_type: "MemoryClient"
284
319
  }).catch((error) => {
285
320
  console.error("Failed to capture event:", error);
@@ -315,12 +350,12 @@ var MemoryClient = class {
315
350
  throw createExceptionFromResponse(response.status, errorData);
316
351
  }
317
352
  const jsonResponse = await response.json();
318
- return jsonResponse;
353
+ return snakeToCamelKeys(jsonResponse);
319
354
  }
320
355
  _preparePayload(messages, options) {
321
356
  const payload = {};
322
357
  payload.messages = messages;
323
- return { ...payload, ...options };
358
+ return camelToSnakeKeys({ ...payload, ...options });
324
359
  }
325
360
  _prepareParams(options) {
326
361
  return Object.fromEntries(
@@ -344,10 +379,10 @@ var MemoryClient = class {
344
379
  if (response.status !== "ok") {
345
380
  throw new APIError(response.message || "API Key is invalid");
346
381
  }
347
- const { org_id, project_id, user_email } = response;
348
- if (org_id && !this.organizationId) this.organizationId = org_id;
349
- if (project_id && !this.projectId) this.projectId = project_id;
350
- if (user_email) this.telemetryId = user_email;
382
+ const { orgId, projectId, userEmail } = response;
383
+ if (orgId) this.organizationId = orgId;
384
+ if (projectId) this.projectId = projectId;
385
+ if (userEmail) this.telemetryId = userEmail;
351
386
  } catch (error) {
352
387
  if (error instanceof MemoryError || error instanceof APIError) {
353
388
  throw error;
@@ -360,25 +395,11 @@ var MemoryClient = class {
360
395
  }
361
396
  async add(messages, options = {}) {
362
397
  if (this.telemetryId === "") await this.ping();
363
- this._validateOrgProject();
364
- if (this.organizationName != null && this.projectName != null) {
365
- options.org_name = this.organizationName;
366
- options.project_name = this.projectName;
367
- }
368
- if (this.organizationId != null && this.projectId != null) {
369
- options.org_id = this.organizationId;
370
- options.project_id = this.projectId;
371
- if (options.org_name) delete options.org_name;
372
- if (options.project_name) delete options.project_name;
373
- }
374
- if (options.api_version) {
375
- options.version = options.api_version.toString() || "v2";
376
- }
377
398
  const payload = this._preparePayload(messages, options);
378
399
  const payloadKeys = Object.keys(payload);
379
400
  this._captureEvent("add", [payloadKeys]);
380
401
  const response = await this._fetchWithErrorHandling(
381
- `${this.host}/v1/memories/`,
402
+ `${this.host}/v3/memories/`,
382
403
  {
383
404
  method: "POST",
384
405
  headers: this.headers,
@@ -398,7 +419,6 @@ var MemoryClient = class {
398
419
  );
399
420
  }
400
421
  if (this.telemetryId === "") await this.ping();
401
- this._validateOrgProject();
402
422
  const payload = {};
403
423
  if (text !== void 0) payload.text = text;
404
424
  if (metadata !== void 0) payload.metadata = metadata;
@@ -426,62 +446,42 @@ var MemoryClient = class {
426
446
  );
427
447
  }
428
448
  async getAll(options) {
449
+ var _a2;
450
+ rejectTopLevelEntityParams(options, "getAll");
429
451
  if (this.telemetryId === "") await this.ping();
430
- this._validateOrgProject();
431
452
  const payloadKeys = Object.keys(options || {});
432
453
  this._captureEvent("get_all", [payloadKeys]);
433
- const { api_version, page, page_size, ...otherOptions } = options != null ? options : {};
434
- if (this.organizationName != null && this.projectName != null) {
435
- otherOptions.org_name = this.organizationName;
436
- otherOptions.project_name = this.projectName;
437
- }
438
- let appendedParams = "";
439
- let paginated_response = false;
440
- if (page && page_size) {
441
- appendedParams += `page=${page}&page_size=${page_size}`;
442
- paginated_response = true;
443
- }
444
- if (this.organizationId != null && this.projectId != null) {
445
- otherOptions.org_id = this.organizationId;
446
- otherOptions.project_id = this.projectId;
447
- if (otherOptions.org_name) delete otherOptions.org_name;
448
- if (otherOptions.project_name) delete otherOptions.project_name;
449
- }
450
- if (api_version === "v2") {
451
- let url = paginated_response ? `${this.host}/v2/memories/?${appendedParams}` : `${this.host}/v2/memories/`;
452
- return this._fetchWithErrorHandling(url, {
453
- method: "POST",
454
- headers: this.headers,
455
- body: JSON.stringify(otherOptions)
456
- });
457
- } else {
458
- const params = new URLSearchParams(this._prepareParams(otherOptions));
459
- const url = paginated_response ? `${this.host}/v1/memories/?${params}&${appendedParams}` : `${this.host}/v1/memories/?${params}`;
460
- return this._fetchWithErrorHandling(url, {
461
- headers: this.headers
462
- });
463
- }
454
+ const { page, pageSize, filters, ...rest } = options != null ? options : {};
455
+ const body = {
456
+ output_format: "v1.1",
457
+ ...camelToSnakeKeys(rest),
458
+ ...filters && { filters }
459
+ };
460
+ let url = `${this.host}/v2/memories/`;
461
+ if (page && pageSize) {
462
+ url += `?page=${page}&page_size=${pageSize}`;
463
+ }
464
+ const response = await this._fetchWithErrorHandling(url, {
465
+ method: "POST",
466
+ headers: this.headers,
467
+ body: JSON.stringify(body)
468
+ });
469
+ return Array.isArray(response) ? response : (_a2 = response == null ? void 0 : response.results) != null ? _a2 : response;
464
470
  }
465
471
  async search(query, options) {
472
+ rejectTopLevelEntityParams(options, "search");
466
473
  if (this.telemetryId === "") await this.ping();
467
- this._validateOrgProject();
468
474
  const payloadKeys = Object.keys(options || {});
469
475
  this._captureEvent("search", [payloadKeys]);
470
- const { api_version, ...otherOptions } = options != null ? options : {};
471
- const payload = { query, ...otherOptions };
472
- if (this.organizationName != null && this.projectName != null) {
473
- payload.org_name = this.organizationName;
474
- payload.project_name = this.projectName;
475
- }
476
- if (this.organizationId != null && this.projectId != null) {
477
- payload.org_id = this.organizationId;
478
- payload.project_id = this.projectId;
479
- if (payload.org_name) delete payload.org_name;
480
- if (payload.project_name) delete payload.project_name;
481
- }
482
- const endpoint = api_version === "v2" ? "/v2/memories/search/" : "/v1/memories/search/";
476
+ const { filters, ...rest } = options != null ? options : {};
477
+ const payload = {
478
+ query,
479
+ output_format: "v1.1",
480
+ ...camelToSnakeKeys(rest),
481
+ ...filters && { filters }
482
+ };
483
483
  const response = await this._fetchWithErrorHandling(
484
- `${this.host}${endpoint}`,
484
+ `${this.host}/v3/memories/search/`,
485
485
  {
486
486
  method: "POST",
487
487
  headers: this.headers,
@@ -503,20 +503,10 @@ var MemoryClient = class {
503
503
  }
504
504
  async deleteAll(options = {}) {
505
505
  if (this.telemetryId === "") await this.ping();
506
- this._validateOrgProject();
507
506
  const payloadKeys = Object.keys(options || {});
508
507
  this._captureEvent("delete_all", [payloadKeys]);
509
- if (this.organizationName != null && this.projectName != null) {
510
- options.org_name = this.organizationName;
511
- options.project_name = this.projectName;
512
- }
513
- if (this.organizationId != null && this.projectId != null) {
514
- options.org_id = this.organizationId;
515
- options.project_id = this.projectId;
516
- if (options.org_name) delete options.org_name;
517
- if (options.project_name) delete options.project_name;
518
- }
519
- const params = new URLSearchParams(this._prepareParams(options));
508
+ const snakeOptions = camelToSnakeKeys(this._prepareParams(options));
509
+ const params = new URLSearchParams(snakeOptions);
520
510
  const response = await this._fetchWithErrorHandling(
521
511
  `${this.host}/v1/memories/?${params}`,
522
512
  {
@@ -537,28 +527,17 @@ var MemoryClient = class {
537
527
  );
538
528
  return response;
539
529
  }
540
- async users() {
530
+ async users(options) {
541
531
  if (this.telemetryId === "") await this.ping();
542
- this._validateOrgProject();
543
532
  this._captureEvent("users", []);
544
- const options = {};
545
- if (this.organizationName != null && this.projectName != null) {
546
- options.org_name = this.organizationName;
547
- options.project_name = this.projectName;
548
- }
549
- if (this.organizationId != null && this.projectId != null) {
550
- options.org_id = this.organizationId;
551
- options.project_id = this.projectId;
552
- if (options.org_name) delete options.org_name;
553
- if (options.project_name) delete options.project_name;
554
- }
555
- const params = new URLSearchParams(options);
556
- const response = await this._fetchWithErrorHandling(
557
- `${this.host}/v1/entities/?${params}`,
558
- {
559
- headers: this.headers
560
- }
561
- );
533
+ let url = `${this.host}/v1/entities/`;
534
+ const params = [];
535
+ if (options == null ? void 0 : options.page) params.push(`page=${options.page}`);
536
+ if (options == null ? void 0 : options.pageSize) params.push(`page_size=${options.pageSize}`);
537
+ if (params.length) url += `?${params.join("&")}`;
538
+ const response = await this._fetchWithErrorHandling(url, {
539
+ headers: this.headers
540
+ });
562
541
  return response;
563
542
  }
564
543
  /**
@@ -581,17 +560,16 @@ var MemoryClient = class {
581
560
  }
582
561
  async deleteUsers(params = {}) {
583
562
  if (this.telemetryId === "") await this.ping();
584
- this._validateOrgProject();
585
563
  let to_delete = [];
586
- const { user_id, agent_id, app_id, run_id } = params;
587
- if (user_id) {
588
- to_delete = [{ type: "user", name: user_id }];
589
- } else if (agent_id) {
590
- to_delete = [{ type: "agent", name: agent_id }];
591
- } else if (app_id) {
592
- to_delete = [{ type: "app", name: app_id }];
593
- } else if (run_id) {
594
- to_delete = [{ type: "run", name: run_id }];
564
+ const { userId, agentId, appId, runId } = params;
565
+ if (userId) {
566
+ to_delete = [{ type: "user", name: userId }];
567
+ } else if (agentId) {
568
+ to_delete = [{ type: "agent", name: agentId }];
569
+ } else if (appId) {
570
+ to_delete = [{ type: "app", name: appId }];
571
+ } else if (runId) {
572
+ to_delete = [{ type: "run", name: runId }];
595
573
  } else {
596
574
  const entities = await this.users();
597
575
  to_delete = entities.results.map((entity) => ({
@@ -602,25 +580,9 @@ var MemoryClient = class {
602
580
  if (to_delete.length === 0) {
603
581
  throw new Error("No entities to delete");
604
582
  }
605
- const requestOptions = {};
606
- if (this.organizationName != null && this.projectName != null) {
607
- requestOptions.org_name = this.organizationName;
608
- requestOptions.project_name = this.projectName;
609
- }
610
- if (this.organizationId != null && this.projectId != null) {
611
- requestOptions.org_id = this.organizationId;
612
- requestOptions.project_id = this.projectId;
613
- if (requestOptions.org_name) delete requestOptions.org_name;
614
- if (requestOptions.project_name) delete requestOptions.project_name;
615
- }
616
583
  for (const entity of to_delete) {
617
584
  try {
618
- await this.client.delete(
619
- `/v2/entities/${entity.type}/${entity.name}/`,
620
- {
621
- params: requestOptions
622
- }
623
- );
585
+ await this.client.delete(`/v2/entities/${entity.type}/${entity.name}/`);
624
586
  } catch (error) {
625
587
  throw new APIError(
626
588
  `Failed to delete ${entity.type} ${entity.name}: ${error.message}`
@@ -628,16 +590,10 @@ var MemoryClient = class {
628
590
  }
629
591
  }
630
592
  this._captureEvent("delete_users", [
631
- {
632
- user_id,
633
- agent_id,
634
- app_id,
635
- run_id,
636
- sync_type: "sync"
637
- }
593
+ { userId, agentId, appId, runId, sync_type: "sync" }
638
594
  ]);
639
595
  return {
640
- message: user_id || agent_id || app_id || run_id ? "Entity deleted successfully." : "All users, agents, apps and runs deleted."
596
+ message: userId || agentId || appId || runId ? "Entity deleted successfully." : "All users, agents, apps and runs deleted."
641
597
  };
642
598
  }
643
599
  async batchUpdate(memories) {
@@ -675,7 +631,6 @@ var MemoryClient = class {
675
631
  }
676
632
  async getProject(options) {
677
633
  if (this.telemetryId === "") await this.ping();
678
- this._validateOrgProject();
679
634
  const payloadKeys = Object.keys(options || {});
680
635
  this._captureEvent("get_project", [payloadKeys]);
681
636
  const { fields } = options;
@@ -685,7 +640,7 @@ var MemoryClient = class {
685
640
  );
686
641
  }
687
642
  const params = new URLSearchParams();
688
- fields == null ? void 0 : fields.forEach((field) => params.append("fields", field));
643
+ fields == null ? void 0 : fields.forEach((field) => params.append("fields", camelToSnake(field)));
689
644
  const response = await this._fetchWithErrorHandling(
690
645
  `${this.host}/api/v1/orgs/organizations/${this.organizationId}/projects/${this.projectId}/?${params.toString()}`,
691
646
  {
@@ -696,7 +651,6 @@ var MemoryClient = class {
696
651
  }
697
652
  async updateProject(prompts) {
698
653
  if (this.telemetryId === "") await this.ping();
699
- this._validateOrgProject();
700
654
  this._captureEvent("update_project", []);
701
655
  if (!(this.organizationId && this.projectId)) {
702
656
  throw new Error(
@@ -708,7 +662,7 @@ var MemoryClient = class {
708
662
  {
709
663
  method: "PATCH",
710
664
  headers: this.headers,
711
- body: JSON.stringify(prompts)
665
+ body: JSON.stringify(camelToSnakeKeys(prompts))
712
666
  }
713
667
  );
714
668
  return response;
@@ -783,45 +737,47 @@ var MemoryClient = class {
783
737
  {
784
738
  method: "POST",
785
739
  headers: this.headers,
786
- body: JSON.stringify(data)
740
+ body: JSON.stringify(camelToSnakeKeys(data))
787
741
  }
788
742
  );
789
743
  return response;
790
744
  }
791
745
  async createMemoryExport(data) {
792
- var _a2, _b;
793
746
  if (this.telemetryId === "") await this.ping();
794
747
  this._captureEvent("create_memory_export", []);
795
748
  if (!data.filters || !data.schema) {
796
749
  throw new Error("Missing filters or schema");
797
750
  }
798
- data.org_id = ((_a2 = this.organizationId) == null ? void 0 : _a2.toString()) || null;
799
- data.project_id = ((_b = this.projectId) == null ? void 0 : _b.toString()) || null;
751
+ const { filters, ...rest } = data;
800
752
  const response = await this._fetchWithErrorHandling(
801
753
  `${this.host}/v1/exports/`,
802
754
  {
803
755
  method: "POST",
804
756
  headers: this.headers,
805
- body: JSON.stringify(data)
757
+ body: JSON.stringify({
758
+ ...camelToSnakeKeys(rest),
759
+ filters
760
+ })
806
761
  }
807
762
  );
808
763
  return response;
809
764
  }
810
765
  async getMemoryExport(data) {
811
- var _a2, _b;
812
766
  if (this.telemetryId === "") await this.ping();
813
767
  this._captureEvent("get_memory_export", []);
814
- if (!data.memory_export_id && !data.filters) {
815
- throw new Error("Missing memory_export_id or filters");
768
+ if (!data.memoryExportId && !data.filters) {
769
+ throw new Error("Missing memoryExportId or filters");
816
770
  }
817
- data.org_id = ((_a2 = this.organizationId) == null ? void 0 : _a2.toString()) || "";
818
- data.project_id = ((_b = this.projectId) == null ? void 0 : _b.toString()) || "";
771
+ const { filters, ...rest } = data;
819
772
  const response = await this._fetchWithErrorHandling(
820
773
  `${this.host}/v1/exports/get/`,
821
774
  {
822
775
  method: "POST",
823
776
  headers: this.headers,
824
- body: JSON.stringify(data)
777
+ body: JSON.stringify({
778
+ ...camelToSnakeKeys(rest),
779
+ ...filters && { filters }
780
+ })
825
781
  }
826
782
  );
827
783
  return response;