Skip to main content

PlatformClient

The PlatformClient is the main entry point for the Platform SDK. It provides access to all SDK modules and handles authentication, configuration, and request management.

Installation

npm install @enterpriseaigroup/platform-sdk

Basic Usage

import { PlatformClient } from '@enterpriseaigroup/platform-sdk';

const client = new PlatformClient({
apiKey: process.env.EAI_API_KEY,
tenantId: 'your-tenant-id',
baseURL: 'https://api.enterpriseai.com'
});

// Access SDK modules
const resources = await client.resources.list({ type: 'project' });
const user = await client.users.getCurrent();

Constructor Options

PlatformClientConfig

PropertyTypeRequiredDescription
apiKeystringNo*API key for authentication
tokenProviderTokenProviderNo*Custom token provider function
clientIdstringNo*OAuth client ID for client credentials flow
clientSecretstringNo*OAuth client secret for client credentials flow
tenantIdstringYesTenant identifier
baseURLstringNoBase API URL (defaults to https://api.enterpriseai.com)
timeoutnumberNoRequest timeout in milliseconds (default: 30000)
retryConfigRetryConfigNoRetry configuration for failed requests
headersRecord<string, string>NoAdditional headers to include in all requests

*One of apiKey, tokenProvider, or clientId/clientSecret must be provided.

Authentication Methods

API Key Authentication

The simplest authentication method using a static API key:

const client = new PlatformClient({
apiKey: process.env.EAI_API_KEY,
tenantId: 'acme-corp'
});

Token Provider

For dynamic token management (e.g., refreshing tokens):

const client = new PlatformClient({
tenantId: 'acme-corp',
tokenProvider: async () => {
const token = await getTokenFromStorage();
if (isTokenExpired(token)) {
return await refreshToken(token);
}
return token;
}
});

TokenProvider Interface

type TokenProvider = () => Promise<string> | string;

Client Credentials Flow

For server-to-server authentication using OAuth 2.0 client credentials:

const client = new PlatformClient({
tenantId: 'acme-corp',
clientId: process.env.EAI_CLIENT_ID,
clientSecret: process.env.EAI_CLIENT_SECRET
});

The client will automatically obtain and refresh access tokens as needed.

Configuration Options

Retry Configuration

Configure automatic retry behavior for failed requests:

const client = new PlatformClient({
apiKey: process.env.EAI_API_KEY,
tenantId: 'acme-corp',
retryConfig: {
maxRetries: 3,
retryDelay: 1000, // milliseconds
retryableStatusCodes: [408, 429, 500, 502, 503, 504],
shouldRetry: (error) => {
// Custom retry logic
return error.isNetworkError || error.statusCode >= 500;
}
}
});

RetryConfig Interface

PropertyTypeDescription
maxRetriesnumberMaximum number of retry attempts (default: 3)
retryDelaynumberDelay between retries in milliseconds (default: 1000)
retryableStatusCodesnumber[]HTTP status codes that should trigger a retry
shouldRetry(error: ApiError) => booleanCustom function to determine if a request should be retried

Custom Headers

Add custom headers to all requests:

const client = new PlatformClient({
apiKey: process.env.EAI_API_KEY,
tenantId: 'acme-corp',
headers: {
'X-Custom-Header': 'value',
'X-Request-Source': 'backend-service'
}
});

Timeout Configuration

Set a custom timeout for all requests:

const client = new PlatformClient({
apiKey: process.env.EAI_API_KEY,
tenantId: 'acme-corp',
timeout: 60000 // 60 seconds
});

SDK Modules

Once initialized, the client provides access to all SDK modules:

// Resources module
const projects = await client.resources.list({ type: 'project' });

// Chat module
const stream = await client.chat.streamChat('What is the status?');

// Documents module
const document = await client.documents.upload(file);

// Users module
const user = await client.users.getCurrent();

// Auth module
const token = await client.auth.getToken();

// Orchestrate module
const workflow = await client.orchestrate.execute('workflow-id', { input: 'data' });

Complete Example

Here's a complete example with error handling and best practices:

import { PlatformClient, ApiError } from '@enterpriseaigroup/platform-sdk';

// Initialize client with environment variables
const client = new PlatformClient({
apiKey: process.env.EAI_API_KEY,
tenantId: process.env.EAI_TENANT_ID,
baseURL: process.env.EAI_BASE_URL || 'https://api.enterpriseai.com',
timeout: 30000,
retryConfig: {
maxRetries: 3,
retryDelay: 1000,
shouldRetry: (error) => error.isRetryable
}
});

// Use the client
async function fetchProjects() {
try {
const projects = await client.resources.list({
type: 'project',
filter: { status: 'active' },
sort: { field: 'createdAt', order: 'desc' },
limit: 50
});

console.log(`Found ${projects.length} active projects`);
return projects;
} catch (error) {
if (error instanceof ApiError) {
console.error('API Error:', error.message);
console.error('Status:', error.statusCode);
console.error('Details:', error.details);
} else {
console.error('Unexpected error:', error);
}
throw error;
}
}

// Graceful shutdown
process.on('SIGTERM', () => {
client.close(); // Close pending connections
});

Error Handling

The SDK throws ApiError instances for API-related errors:

interface ApiError extends Error {
code: string;
statusCode: number;
details?: unknown;
isRetryable: boolean;
}

Common error codes:

  • UNAUTHORIZED: Invalid or expired authentication
  • FORBIDDEN: Insufficient permissions
  • NOT_FOUND: Resource not found
  • VALIDATION_ERROR: Invalid request data
  • RATE_LIMIT_EXCEEDED: Too many requests
  • INTERNAL_ERROR: Server error

Next Steps