npm package: @protectai/layer-sdk
Description: JavaScript SDK for Protect AI's Layer.
Author: Protect AI
Latest version: 0.4.0

# 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

```sh
npm install @protectai/layer-sdk
```

## Configuration

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

```python
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:

```typescript
import { LayerSDK, OIDCClientCredentialsMiddleware, SessionActionKindEnum } from 'layer-sdk';

const authMiddleware = 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,
      kind: SessionActionKindEnum.COMPLETION_PROMPT,
      startTime: new Date(),
      endTime: new Date(Date.now() + 2000),
      attributes: { 'model.id': 'gpt-3.5-turbo-16k' },
      data: {
        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:

```typescript
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](https://semver.org/spec/v2.0.0.html) 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.