npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@protectai/layer-sdk

v0.0.4

Published

JavaScript SDK for Protect AI's Layer.

Downloads

33

Readme

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.