Installation

npm install supermemory

Basic Usage

To use the SDK, you’ll need an API key from Supermemory. Learn how to get one from Getting Started.

import Supermemory from 'supermemory';

const client = new Supermemory({
  apiKey: process.env['SUPERMEMORY_API_KEY'], // This is the default and can be omitted if set in env
});

async function main() {
  const response = await client.search.execute({ q: 'documents related to python' });

  console.log(response.results);
}

main();

Type Safety

This library includes TypeScript definitions for all request parameters and response fields, providing excellent type safety and autocompletion in modern editors.

import Supermemory from 'supermemory';

const client = new Supermemory({
  apiKey: process.env['SUPERMEMORY_API_KEY'],
});

async function main() {
  // Type-safe request parameters
  const params: Supermemory.MemoryCreateParams = {
    content: 'This is a detailed article about machine learning concepts...',
  };
  
  // Type-safe response
  const memory: Supermemory.MemoryCreateResponse = await client.memory.create(params);
}

main();

Error Handling

When the library is unable to connect to the API or if the API returns a non-success status code (4xx or 5xx), a subclass of APIError will be thrown.

async function main() {
  try {
    const memory = await client.memory.create({ 
      content: 'This is a detailed article about machine learning concepts...' 
    });
  } catch (err) {
    if (err instanceof Supermemory.APIError) {
      console.log(err.status);  // e.g., 400
      console.log(err.name);     // e.g., BadRequestError
      console.log(err.headers);  // e.g., {server: 'nginx', ...}
    } else {
      throw err; // Re-throw if it's not an API error
    }
  }
}

Error Types

The SDK provides specific error types for different error scenarios:

  • BadRequestError (400)
  • AuthenticationError (401)
  • PermissionDeniedError (403)
  • NotFoundError (404)
  • UnprocessableEntityError (422)
  • RateLimitError (429)
  • InternalServerError (500+)
  • APIConnectionError (network issues)
  • APIConnectionTimeoutError (request timeout)

Retries and Timeouts

Automatic Retries

Certain errors are automatically retried 2 times by default, with a short exponential backoff. Connection errors, 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors will all be retried by default.

// Configure the default for all requests:
const client = new Supermemory({
  maxRetries: 0, // default is 2
});

// Or, configure per-request:
await client.memory.create(
  { content: 'This is a detailed article about machine learning concepts...' }, 
  { maxRetries: 5 }
);

Configuring Timeouts

Requests time out after 1 minute by default. You can configure this with a timeout option:

// Configure the default for all requests:
const client = new Supermemory({
  timeout: 20 * 1000, // 20 seconds (default is 1 minute)
});

// Override per-request:
await client.memory.create(
  { content: 'This is a detailed article about machine learning concepts...' }, 
  { timeout: 5 * 1000 }
);

On timeout, an APIConnectionTimeoutError is thrown. Note that requests which time out will be retried twice by default.

Advanced Usage

Accessing Raw Response Data

The “raw” Response returned by fetch() can be accessed through the .asResponse() method on the APIPromise type that all methods return.

const response = await client.memory
  .create({ content: 'This is a detailed article about machine learning concepts...' })
  .asResponse();

console.log(response.headers.get('X-My-Header'));
console.log(response.statusText); // access the underlying Response object

You can also use the .withResponse() method to get the raw Response along with the parsed data:

const { data: memory, response: raw } = await client.memory
  .create({ content: 'This is a detailed article about machine learning concepts...' })
  .withResponse();

console.log(raw.headers.get('X-My-Header'));
console.log(memory.id);

Logging

Important: All log messages are intended for debugging only. The format and content of log messages may change between releases.

Log Levels

The log level can be configured in two ways:

  1. Via the SUPERMEMORY_LOG environment variable
  2. Using the logLevel client option (overrides the environment variable if set)
import Supermemory from 'supermemory';

const client = new Supermemory({
  logLevel: 'debug', // Show all log messages
});

Available log levels, from most to least verbose:

  • 'debug' - Show debug messages, info, warnings, and errors
  • 'info' - Show info messages, warnings, and errors
  • 'warn' - Show warnings and errors (default)
  • 'error' - Show only errors
  • 'off' - Disable all logging

At the ‘debug’ level, all HTTP requests and responses are logged, including headers and bodies. Some authentication-related headers are redacted, but sensitive data in request and response bodies may still be visible.

Custom Logger

By default, this library logs to globalThis.console. You can also provide a custom logger:

import Supermemory from 'supermemory';
import pino from 'pino';

const logger = pino();

const client = new Supermemory({
  logger: logger.child({ name: 'Supermemory' }),
  logLevel: 'debug', // Send all messages to pino, allowing it to filter
});

Making Custom/Undocumented Requests

To make requests to undocumented endpoints, you can use client.get, client.post, and other HTTP verbs:

await client.post('/some/path', {
  body: { some_prop: 'foo' },
  query: { some_query_arg: 'bar' },
});

Customizing the Fetch Client

By default, this library expects a global fetch function is defined. If you want to use a different fetch function, you can pass it to the client:

import Supermemory from 'supermemory';
import fetch from 'my-fetch';

const client = new Supermemory({ fetch });

Fetch Options

If you want to set custom fetch options without overriding the fetch function, you can provide a fetchOptions object when instantiating the client or making a request:

import Supermemory from 'supermemory';

const client = new Supermemory({
  fetchOptions: {
    // `RequestInit` options
  },
});

Configuring Proxies

import Supermemory from 'supermemory';
import * as undici from 'undici';

const proxyAgent = new undici.ProxyAgent('http://localhost:8888');
const client = new Supermemory({
  fetchOptions: {
    dispatcher: proxyAgent,
  },
});

API Reference

For a complete API reference, please see the API documentation on GitHub.