@anam-ai/js-sdk
Version:
Client side JavaScript SDK for Anam AI
153 lines • 8.76 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CoreApiRestClient = void 0;
const ClientError_1 = require("../lib/ClientError");
const constants_1 = require("../lib/constants");
const PersonaConfig_1 = require("../types/PersonaConfig");
class CoreApiRestClient {
constructor(sessionToken, apiKey, options) {
if (!sessionToken && !apiKey) {
throw new Error('Either sessionToken or apiKey must be provided');
}
this.sessionToken = sessionToken || null;
this.apiKey = apiKey || null;
this.baseUrl = (options === null || options === void 0 ? void 0 : options.baseUrl) || constants_1.DEFAULT_API_BASE_URL;
this.apiVersion = (options === null || options === void 0 ? void 0 : options.apiVersion) || constants_1.DEFAULT_API_VERSION;
this.apiGatewayConfig = (options === null || options === void 0 ? void 0 : options.apiGateway) || undefined;
}
/**
* Builds URL and headers for a request, applying API Gateway configuration if enabled
*/
buildGatewayUrlAndHeaders(targetPath, baseHeaders) {
var _a, _b;
if (((_a = this.apiGatewayConfig) === null || _a === void 0 ? void 0 : _a.enabled) && ((_b = this.apiGatewayConfig) === null || _b === void 0 ? void 0 : _b.baseUrl)) {
// Use gateway base URL with same endpoint path
const url = `${this.apiGatewayConfig.baseUrl}${targetPath}`;
// Add complete target URL header for gateway routing
const targetUrl = new URL(`${this.baseUrl}${targetPath}`);
const headers = Object.assign(Object.assign({}, baseHeaders), { 'X-Anam-Target-Url': targetUrl.href });
return { url, headers };
}
else {
// Direct call to Anam API
return {
url: `${this.baseUrl}${targetPath}`,
headers: baseHeaders,
};
}
}
startSession(personaConfig, sessionOptions) {
return __awaiter(this, void 0, void 0, function* () {
if (!this.sessionToken) {
if (!personaConfig) {
throw new ClientError_1.ClientError('Persona configuration must be provided when using apiKey', ClientError_1.ErrorCode.CLIENT_ERROR_CODE_VALIDATION_ERROR, 400);
}
this.sessionToken = yield this.unsafe_getSessionToken(personaConfig);
}
// Check if brainType is being used and log deprecation warning
if (personaConfig && 'brainType' in personaConfig) {
console.warn('Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.');
}
try {
const targetPath = `${this.apiVersion}/engine/session`;
const { url, headers } = this.buildGatewayUrlAndHeaders(targetPath, {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.sessionToken}`,
});
const response = yield fetch(url, {
method: 'POST',
headers,
body: JSON.stringify({
personaConfig,
sessionOptions,
clientMetadata: constants_1.CLIENT_METADATA,
}),
});
const data = yield response.json();
const errorCause = data.error;
switch (response.status) {
case 200:
case 201:
return data;
case 400:
throw new ClientError_1.ClientError('Invalid request to start session', ClientError_1.ErrorCode.CLIENT_ERROR_CODE_VALIDATION_ERROR, 400, { cause: data.message });
case 401:
throw new ClientError_1.ClientError('Authentication failed when starting session', ClientError_1.ErrorCode.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR, 401, { cause: data.message });
case 402:
throw new ClientError_1.ClientError('Please sign up for a plan to start a session', ClientError_1.ErrorCode.CLIENT_ERROR_CODE_NO_PLAN_FOUND, 402, { cause: data.message });
case 403:
throw new ClientError_1.ClientError('Authentication failed when starting session', ClientError_1.ErrorCode.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR, 403, { cause: data.message });
case 429:
if (errorCause === 'Concurrent session limit reached') {
throw new ClientError_1.ClientError('Concurrency limit reached, please upgrade your plan', ClientError_1.ErrorCode.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED, 429, { cause: data.message });
}
else if (errorCause === 'Spend cap reached') {
throw new ClientError_1.ClientError('Spend cap reached, please upgrade your plan', ClientError_1.ErrorCode.CLIENT_ERROR_CODE_SPEND_CAP_REACHED, 429, { cause: data.message });
}
else {
throw new ClientError_1.ClientError('Usage limit reached, please upgrade your plan', ClientError_1.ErrorCode.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED, 429, { cause: data.message });
}
case 503:
throw new ClientError_1.ClientError('There are no available personas, please try again later', ClientError_1.ErrorCode.CLIENT_ERROR_CODE_SERVICE_BUSY, 503, { cause: data.message });
default:
throw new ClientError_1.ClientError('Unknown error when starting session', ClientError_1.ErrorCode.CLIENT_ERROR_CODE_SERVER_ERROR, 500, { cause: data.message });
}
}
catch (error) {
if (error instanceof ClientError_1.ClientError) {
throw error;
}
throw new ClientError_1.ClientError('Failed to start session', ClientError_1.ErrorCode.CLIENT_ERROR_CODE_SERVER_ERROR, 500, { cause: error instanceof Error ? error.message : String(error) });
}
});
}
unsafe_getSessionToken(personaConfig) {
return __awaiter(this, void 0, void 0, function* () {
console.warn('Using unsecure method. This method should not be used in production.');
if (!this.apiKey) {
throw new Error('No apiKey provided');
}
// Check if brainType is being used and log deprecation warning
if (personaConfig && 'brainType' in personaConfig) {
console.warn('Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.');
}
let body = {
clientLabel: 'js-sdk-api-key',
};
if ((0, PersonaConfig_1.isCustomPersonaConfig)(personaConfig)) {
body = Object.assign(Object.assign({}, body), { personaConfig });
}
try {
const targetPath = `${this.apiVersion}/auth/session-token`;
const { url, headers } = this.buildGatewayUrlAndHeaders(targetPath, {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.apiKey}`,
});
const response = yield fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(body),
});
const data = yield response.json();
return data.sessionToken;
}
catch (e) {
throw new Error('Failed to get session token');
}
});
}
getApiUrl() {
return `${this.baseUrl}${this.apiVersion}`;
}
}
exports.CoreApiRestClient = CoreApiRestClient;
//# sourceMappingURL=CoreApiRestClient.js.map