@protectai/layer-sdk
TypeScript icon, indicating that this package has built-in type declarations

0.0.4 • Public • Published

Layer SDK Node.js API library

Layer SDK is a Node.js library for interacting with the Layer API, allowing you to create sessions and append session actions with ease.

Installation

npm install layer-sdk

Configuration

The Layer SDK can be configured by passing configuration options directly when initializing the SDK.

import { LayerSDK } from 'layer-sdk';

const client = new LayerSDK(
  'https://api.example.com',
  'your-application-id',
  'production',
  [authMiddleware]
);

Configuration Options

  • baseUrl: The base URL for the Layer API. This is where all API requests will be sent.
  • applicationId: Your unique application identifier provided by Layer.
  • environment: The environment you're operating in (e.g., "production", "development", "staging").
  • middlewares: An array of middleware objects, including authentication providers.

Quick Start

Here's a simple example of how to use the Layer SDK:

import {
  LayerSDK,
  OIDCClientCredentialsMiddleware,
  SessionActionKind,
} from "layer-sdk";

const authMiddleware = new OIDCClientCredentialsMiddleware({
  tokenUrl: "https://auth.example.com/token",
  clientId: "your-client-id",
  clientSecret: "your-client-secret",
  scope: "your-scope",
});

const client = new LayerSDK(
  "https://api.example.com",
  "your-application-id",
  "production",
  [authMiddleware],
);

async function example() {
  try {
    // Create a session
    const sessionId = await client.createSession({
      attributes: { "user.id": "user-001" },
    });

    console.log(`Session ID: ${sessionId}`);

    // Append an action
    await client.appendAction(
      sessionId,
      SessionActionKind.COMPLETION_PROMPT,
      new Date(),
      new Date(Date.now() + 2000),
      { "model.id": "gpt-3.5-turbo-16k" },
      {
        messages: [
          { content: "Hello, how can I help you?", role: "assistant" },
        ],
      },
    );
  } catch (error) {
    console.error("Error:", error);
  }
}

example();

Authentication

The Layer SDK supports optional authentication using OpenID Connect (OIDC) with Keycloak.

OIDC Authentication with Keycloak

If your Layer instance is configured to use OIDC authentication with Keycloak, you can set up the SDK to automatically handle authentication for you using the OIDCClientCredentialsMiddleware.

Configuration Options:

  • tokenUrl: The token endpoint URL for your Keycloak realm.
  • clientId: The client ID for your application, as registered in Keycloak.
  • clientSecret: The client secret for your application.
  • scope: The scope to request when obtaining an access token.

Using Without Authentication

If your Layer instance doesn't require authentication, you can initialize the Client without passing any middleware.

Resiliency

Error Handling

The SDK uses custom exception classes to provide clear and actionable error information:

  • LayerHTTPError: Raised when an HTTP request fails. It includes the status code and error message from the server.
  • LayerAuthError: Raised if there's an authentication error.

Example of handling errors:

import { LayerSDK, LayerHTTPError } from "layer-sdk";

async function example() {
  try {
    const sessionId = await client.createSession({
      attributes: { "user.id": "user-001" },
    });
  } catch (error) {
    if (error instanceof LayerHTTPError) {
      console.error(
        `HTTP error occurred: Status ${error.status}, Message: ${error.message}`,
      );
    } else if (error instanceof LayerHTTPError) {
      console.error(`Request error: ${error.message}`);
    } else {
      console.error(`Unexpected error: ${error}`);
    }
  }
}

Versioning

This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:

  1. Changes that only affect static types, without breaking runtime behavior.
  2. Changes to library internals which are technically public but not intended or documented for external use. (Please open a GitHub issue to let us know if you are relying on such internals).
  3. Changes that we do not expect to impact the vast majority of users in practice.

We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.

Requirements

Node.js 14 or higher.

Package Sidebar

Install

npm i @protectai/layer-sdk

Weekly Downloads

0

Version

0.0.4

License

Apache-2.0

Unpacked Size

36.6 kB

Total Files

14

Last publish

Collaborators

  • asofter
  • dianakpai
  • caleb-protectai
  • pai-josh