n8n-nodes-gigachat
Version:
A user-friendly GigaChat AI (Sber) nodes for n8n
142 lines • 7.34 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.apiGigaChatExecute = apiGigaChatExecute;
const n8n_workflow_1 = require("n8n-workflow");
const GigaChatApiClient_1 = require("../../shared/GigaChatApiClient");
const remove_markdown_1 = __importDefault(require("remove-markdown"));
async function apiGigaChatExecute() {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
const items = this.getInputData();
const returnData = [];
const resource = this.getNodeParameter('resource', 0);
const operation = this.getNodeParameter('operation', 0);
const credentials = await this.getCredentials('gigaChatApi');
const scope = credentials.scope ? String(credentials.scope) : 'GIGACHAT_API_PERS';
await GigaChatApiClient_1.GigaChatApiClient.updateConfig({
credentials: credentials.authorizationKey,
scope: scope,
model: 'GigaChat',
timeout: 600,
authUrl: credentials.base_url
? `${credentials.base_url}/api/v2/oauth`
: 'https://ngw.devices.sberbank.ru:9443/api/v2/oauth',
});
for (let i = 0; i < items.length; i++) {
try {
if (resource === 'image' && operation === 'analyze') {
const binaryPropertyName = this.getNodeParameter('binaryPropertyName', 0);
const modelId = this.getNodeParameter('modelId', 0);
const prompt = this.getNodeParameter('prompt', 0);
const itemBinaryData = items[i].binary[binaryPropertyName];
const itemBuffer = Buffer.from(itemBinaryData.data, n8n_workflow_1.BINARY_ENCODING);
const fileUploaded = await GigaChatApiClient_1.GigaChatApiClient.uploadFile(new File([itemBuffer], itemBinaryData.fileName || `file${itemBinaryData.fileExtension || 'bin'}`, {
type: itemBinaryData.mimeType,
}), 'general');
const attachmentId = fileUploaded.id;
const finalResponse = await GigaChatApiClient_1.GigaChatApiClient.chatWithSession({
model: modelId,
stream: false,
messages: [
{
role: 'user',
content: prompt ? String(prompt) : 'Что изображено на фото?',
attachments: [attachmentId],
},
],
});
const removeMarkdown = this.getNodeParameter('removeMarkdown', i);
let finalMessage = ((_b = (_a = finalResponse.choices[0]) === null || _a === void 0 ? void 0 : _a.message) === null || _b === void 0 ? void 0 : _b.content) || '';
if (removeMarkdown) {
finalMessage = (0, remove_markdown_1.default)(finalMessage);
}
const executionData = this.helpers.constructExecutionMetaData(this.helpers.returnJsonArray({ response: finalMessage }), {
itemData: { item: i },
});
if (Array.isArray(executionData)) {
returnData.push(...executionData);
}
else {
returnData.push(executionData);
}
}
if (resource === 'tokens' && operation === 'count') {
const modelId = this.getNodeParameter('modelId', 0);
const prompt = this.getNodeParameter('prompt', 0);
const tokenCountResponse = await GigaChatApiClient_1.GigaChatApiClient.tokensCount([prompt], modelId);
const executionData = this.helpers.constructExecutionMetaData(this.helpers.returnJsonArray({
response: {
tokens: tokenCountResponse.tokens[0].tokens,
characters: tokenCountResponse.tokens[0].characters,
},
}), {
itemData: { item: i },
});
if (Array.isArray(executionData)) {
returnData.push(...executionData);
}
else {
returnData.push(executionData);
}
}
if (resource === 'tokens' && operation === 'balance') {
const tokenBalanceResponse = await GigaChatApiClient_1.GigaChatApiClient.balance();
const usage = {
GigaChat: (_d = (_c = tokenBalanceResponse.balance.find((el) => el.usage === 'GigaChat')) === null || _c === void 0 ? void 0 : _c.value) !== null && _d !== void 0 ? _d : 0,
'GigaChat-Pro': (_f = (_e = tokenBalanceResponse.balance.find((el) => el.usage === 'GigaChat-Pro')) === null || _e === void 0 ? void 0 : _e.value) !== null && _f !== void 0 ? _f : 0,
'GigaChat-Max': (_h = (_g = tokenBalanceResponse.balance.find((el) => el.usage === 'GigaChat-Max')) === null || _g === void 0 ? void 0 : _g.value) !== null && _h !== void 0 ? _h : 0,
embeddings: (_k = (_j = tokenBalanceResponse.balance.find((el) => el.usage === 'embeddings')) === null || _j === void 0 ? void 0 : _j.value) !== null && _k !== void 0 ? _k : 0,
};
const executionData = this.helpers.constructExecutionMetaData(this.helpers.returnJsonArray({ response: usage }), {
itemData: { item: i },
});
if (Array.isArray(executionData)) {
returnData.push(...executionData);
}
else {
returnData.push(executionData);
}
}
}
catch (error) {
let errorMessage;
if (error instanceof Error) {
errorMessage = error.message;
}
else if (typeof error === 'object' && error !== null) {
if ('response' in error && typeof error.response === 'object' && error.response !== null) {
const response = error.response;
if (response.data && typeof response.data === 'object') {
errorMessage = JSON.stringify(response.data);
}
else if (response.statusText) {
errorMessage = `HTTP ${response.status}: ${response.statusText}`;
}
else {
errorMessage = `HTTP Error: ${response.status}`;
}
}
else {
errorMessage = JSON.stringify(error);
}
}
else {
errorMessage = String(error);
}
if (this.continueOnFail()) {
returnData.push({
json: {
error: errorMessage,
},
pairedItem: { item: i },
});
continue;
}
throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage, { itemIndex: i });
}
}
return [returnData];
}
//# sourceMappingURL=utils.js.map