n8n-nodes-gigachat
Version:
A user-friendly GigaChat AI (Sber) nodes for n8n
168 lines • 7.37 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GigaChatApiClient = void 0;
const axios_1 = __importDefault(require("axios"));
const gigachat_1 = require("gigachat");
const HttpsAgent_1 = require("./HttpsAgent");
const exceptions_1 = require("gigachat/exceptions");
class GigaChatApiClientInstance extends gigachat_1.GigaChat {
constructor(config) {
super({ ...config, httpsAgent: HttpsAgent_1.HttpsAgent });
this.authorizationKey = null;
}
async updateConfig(config, shouldUpdateToken = true) {
var _a;
if (this.authorizationKey !== config.credentials) {
this.authorizationKey = (_a = config.credentials) !== null && _a !== void 0 ? _a : null;
this._settings = { ...this._settings, ...config };
const axiosConfig = {
timeout: this._settings.timeout * 1000,
httpsAgent: this._settings.httpsAgent,
validateStatus: () => true,
};
this._client = axios_1.default.create({
baseURL: this._settings.baseUrl,
...axiosConfig,
});
this._authClient = axios_1.default.create({ baseURL: this._settings.authUrl, ...axiosConfig });
this._accessToken = undefined;
this._settings.accessToken = undefined;
if (shouldUpdateToken) {
await this.updateToken();
}
}
}
async chatWithSession(data, sessionId) {
var _a, _b;
if (!this._accessToken) {
await this.updateToken();
}
if (!this._accessToken) {
throw new Error('Failed to obtain access token');
}
const tokenString = this._accessToken.access_token || this._accessToken;
const headers = {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Bearer ${tokenString}`,
};
headers['User-Agent'] = 'GigaChat-JS-SDK/0.0.14';
if (sessionId) {
headers['X-Session-ID'] = sessionId;
}
headers['X-Request-ID'] = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
const r = (Math.random() * 16) | 0;
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
const freshClient = axios_1.default.create({
baseURL: this._settings.baseUrl || 'https://gigachat.devices.sberbank.ru/api/v1',
httpsAgent: HttpsAgent_1.HttpsAgent,
timeout: 30000,
validateStatus: () => true,
});
const response = await freshClient.post('/chat/completions', data, {
headers,
});
if (response.status === 401 && ((_b = (_a = response.data) === null || _a === void 0 ? void 0 : _a.message) === null || _b === void 0 ? void 0 : _b.includes('Token has expired'))) {
this._accessToken = undefined;
await this.updateToken();
headers['Authorization'] =
`Bearer ${this._accessToken.access_token || this._accessToken}`;
const retryResponse = await freshClient.post('/chat/completions', data, {
headers,
});
if (retryResponse.status !== 200) {
throw new Error(`GigaChat API error: ${retryResponse.status} ${retryResponse.statusText} - ${JSON.stringify(retryResponse.data)}`);
}
const result = retryResponse.data;
const xHeaders = {
xRequestID: retryResponse.headers['x-request-id'] || '',
xSessionID: retryResponse.headers['x-session-id'] || '',
xClientID: retryResponse.headers['x-client-id'] || '',
};
return {
...result,
xHeaders,
};
}
if (response.status !== 200) {
throw new Error(`GigaChat API error: ${response.status} ${response.statusText} - ${JSON.stringify(response.data)}`);
}
const result = response.data;
const xHeaders = {
xRequestID: response.headers['x-request-id'] || '',
xSessionID: response.headers['x-session-id'] || '',
xClientID: response.headers['x-client-id'] || '',
};
return {
...result,
xHeaders,
};
}
static getInstance(credentials) {
if (!this.instance) {
this.instance = new GigaChatApiClientInstance({});
}
if (credentials) {
const config = {
credentials: credentials.credentials || credentials.authorization,
scope: credentials.scope || 'GIGACHAT_API_PERS',
model: 'GigaChat',
timeout: 600,
authUrl: credentials.base_url
? `${credentials.base_url}/api/v2/oauth`
: 'https://ngw.devices.sberbank.ru:9443/api/v2/oauth',
};
this.instance.updateConfig(config);
}
return this.instance;
}
}
GigaChatApiClientInstance.instance = null;
class GigaChatApiClientWrapper extends GigaChatApiClientInstance {
async getModels() {
var _a, _b;
try {
const result = await super.getModels();
return result;
}
catch (error) {
if (((_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.status) === 401 || ((_b = error === null || error === void 0 ? void 0 : error.message) === null || _b === void 0 ? void 0 : _b.includes('Token has expired'))) {
this._accessToken = undefined;
await this.updateToken();
return await super.getModels();
}
if (error instanceof exceptions_1.ResponseError) {
const response = error.response;
const errorData = response.data;
let errorMessage = 'Unknown error';
if (typeof errorData === 'string') {
errorMessage = errorData;
}
else if (errorData === null || errorData === void 0 ? void 0 : errorData.message) {
errorMessage = errorData.message;
}
else if (errorData === null || errorData === void 0 ? void 0 : errorData.detail) {
errorMessage = errorData.detail;
}
else if (errorData === null || errorData === void 0 ? void 0 : errorData.error) {
errorMessage = errorData.error;
}
else if (errorData === null || errorData === void 0 ? void 0 : errorData.error_description) {
errorMessage = errorData.error_description;
}
else {
errorMessage = JSON.stringify(errorData);
}
throw new Error(`GigaChat API error (${response.status}): ${errorMessage}`);
}
throw error;
}
}
}
exports.GigaChatApiClient = new GigaChatApiClientWrapper({});
//# sourceMappingURL=GigaChatApiClient.js.map