Skip to main content
The SDK is a lightweight wrapper over the public API. Everything you can do in the REST interface is available here with first-class TypeScript types.

Installation

Install the package from npm and add it to your project dependencies:
npm install @neuronsearchlab/sdk
# or
yarn add @neuronsearchlab/sdk
If you are using TypeScript, no additional type definitions are required—the SDK ships with them.

Authenticate the client

The client uses bearer tokens issued by the NeuronSearchLab identity service. Fetch an access token using your existing authentication flow, then configure the SDK once at startup:
import { NeuronSearchLabClient } from "@neuronsearchlab/sdk";

const client = new NeuronSearchLabClient({
  baseUrl: "https://api.neuronsearchlab.com",
  getAccessToken: async () => {
    const response = await fetch("https://api.neuronsearchlab.com/auth/token", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        clientId: process.env.NEURONSEARCHLAB_CLIENT_ID!,
        clientSecret: process.env.NEURONSEARCHLAB_CLIENT_SECRET!,
        grantType: "client_credentials",
      }),
    });

    if (!response.ok) {
      throw new Error("Unable to obtain access token");
    }

    const { access_token } = await response.json();
    return access_token as string;
  },
});
The getAccessToken callback is called automatically before each request and should resolve to a string. The example above demonstrates the client credentials grant, but you can plug in any logic—such as refreshing a cached token or forwarding a user’s session.

Upsert catalog items

Use client.items.upsert to add or update catalog entries. Each item supports metadata, custom attributes, and optional embeddings.
await client.items.upsert([
  {
    id: "article-123",
    title: "Building contextual recommendations",
    tags: ["personalization", "vector-search"],
    url: "https://example.com/articles/123",
    metadata: {
      vertical: "news",
      language: "en",
    },
  },
]);
You can batch multiple items in a single call. The SDK handles retryable errors with exponential backoff.

Record user events

Events provide the feedback loop that powers personalization. Send them as they happen from your frontend or backend:
await client.events.publish([
  {
    id: "event-1",
    type: "click",
    userId: "user-456",
    itemId: "article-123",
    timestamp: new Date().toISOString(),
    contextId: 101,
    metadata: {
      position: 2,
    },
  },
]);
The SDK automatically stamps the correct Authorization header and ensures your payload matches the API schema.

Request recommendations

When you need personalized content, call client.recommendations.get with the relevant identifiers and filters:
const { results } = await client.recommendations.get({
  userId: "user-456",
  contextId: 101,
  limit: 5,
  filters: {
    tags: { include: ["vector-search"] },
  },
});

console.log(results);
Each result includes the item payload you previously upserted, along with relevance scores. Adjust the filters, boosts, or fallback options to tune the experience.

Error handling and retries

Network issues and rate limits can happen. The client exposes interceptors so you can adjust retry logic or instrument metrics:
client.interceptors.onError((error) => {
  if (error.response?.status === 429) {
    console.warn("Back off—too many requests", error.response.headers["retry-after"]);
  }

  throw error;
});
You can also wrap individual calls in your own retry helper if you need custom behavior.

Next steps