n8n-nodes-piapi
Version:
Community n8n nodes for PiAPI - integrate generative AI capabilities (image, video, audio, 3D) into your workflows
153 lines • 6.18 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.piApiRequest = piApiRequest;
exports.llmApiRequest = llmApiRequest;
exports.waitForTaskCompletion = waitForTaskCompletion;
exports.extractImageUrlFromResponse = extractImageUrlFromResponse;
exports.isGenerationFailed = isGenerationFailed;
exports.extractFailureDetails = extractFailureDetails;
exports.processStreamedResponse = processStreamedResponse;
const n8n_workflow_1 = require("n8n-workflow");
async function piApiRequest(method, resource, body = {}, qs = {}) {
const credentials = await this.getCredentials('piAPIApi');
const options = {
method,
body,
qs,
url: `https://api.piapi.ai${resource}`,
headers: {
'Content-Type': 'application/json',
'X-API-Key': credentials.apiKey,
},
json: true,
};
try {
return await this.helpers.request(options);
}
catch (error) {
throw new n8n_workflow_1.NodeApiError(this.getNode(), error);
}
}
async function llmApiRequest(body = {}) {
const credentials = await this.getCredentials('piAPIApi');
const options = {
method: 'POST',
body,
url: 'https://api.piapi.ai/v1/chat/completions',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${credentials.apiKey}`,
},
json: true,
};
try {
return await this.helpers.request(options);
}
catch (error) {
throw new n8n_workflow_1.NodeApiError(this.getNode(), error);
}
}
async function waitForTaskCompletion(taskId, maxRetries = 20, retryInterval = 3000) {
var _a, _b;
let retries = 0;
while (retries < maxRetries) {
const response = await piApiRequest.call(this, 'GET', `/api/v1/task/${taskId}`);
const status = (_a = response.data) === null || _a === void 0 ? void 0 : _a.status;
if (status === 'success' || status === 'completed') {
return response.data;
}
if (status === 'failed') {
throw new Error(`Task failed: ${JSON.stringify(((_b = response.data) === null || _b === void 0 ? void 0 : _b.error) || 'Unknown error')}`);
}
await (0, n8n_workflow_1.sleep)(retryInterval);
retries++;
}
throw new Error(`Task timed out after ${maxRetries} retries`);
}
function extractImageUrlFromResponse(content) {
var _a, _b;
const imageUrlPattern = /!\[.*?\]\((https?:\/\/[^)]+)\)/;
const markdownMatch = content.match(imageUrlPattern);
if (markdownMatch)
return markdownMatch[1];
const markdownLinkPattern = /\[.*?\]\((https?:\/\/[^)]+)\)/;
const linkMatch = content.match(markdownLinkPattern);
if (linkMatch)
return linkMatch[1];
try {
const imageUrlJsonPattern = /"image(?:_url|Url|URL)"\s*:\s*"(https?:\/\/[^"]+)"/;
const jsonMatch = content.match(imageUrlJsonPattern);
if (jsonMatch)
return jsonMatch[1];
const urlPattern = /https?:\/\/\S+\.(?:png|jpe?g|gif|webp|bmp)(?:[?&]\S+)?/i;
const urlMatch = content.match(urlPattern);
if (urlMatch) {
let fullUrl = urlMatch[0];
fullUrl = fullUrl.replace(/["'\)]$/, '');
if (fullUrl.includes('?')) {
const startIndex = content.indexOf(fullUrl);
const remainingContent = content.substring(startIndex);
const endIndex = remainingContent.search(/[\s"'\n\r)]/);
if (endIndex > 0) {
fullUrl = remainingContent.substring(0, endIndex);
}
}
return fullUrl;
}
const dataChunks = content.split('\n\n').filter(chunk => chunk.startsWith('data: '));
for (const chunk of dataChunks) {
try {
const jsonStr = chunk.substring(6);
const jsonData = JSON.parse(jsonStr);
if (jsonData.choices && ((_b = (_a = jsonData.choices[0]) === null || _a === void 0 ? void 0 : _a.delta) === null || _b === void 0 ? void 0 : _b.content)) {
const deltaContent = jsonData.choices[0].delta.content;
const linkInDelta = deltaContent.match(markdownLinkPattern);
if (linkInDelta)
return linkInDelta[1];
const imageInDelta = deltaContent.match(imageUrlPattern);
if (imageInDelta)
return imageInDelta[1];
const contentUrlMatch = deltaContent.match(urlPattern);
if (contentUrlMatch) {
let fullUrl = contentUrlMatch[0];
fullUrl = fullUrl.replace(/["'\)]$/, '');
return fullUrl;
}
}
}
catch (e) {
}
}
return null;
}
catch (e) {
return null;
}
}
function isGenerationFailed(content) {
return content.includes('Generation failed') || content.includes('Failure reason');
}
function extractFailureDetails(content) {
var _a, _b;
const reason = ((_a = content.match(/Reason: (.*?)(?:\n|$)/i)) === null || _a === void 0 ? void 0 : _a[1]) || 'Unknown reason';
const suggestion = ((_b = content.match(/Suggestion: (.*?)(?:\n|$)/i)) === null || _b === void 0 ? void 0 : _b[1]) || '';
return { reason, suggestion };
}
function processStreamedResponse(streamResponse) {
var _a, _b;
let fullContent = '';
const dataChunks = streamResponse.split('\n\n').filter(chunk => chunk.startsWith('data: '));
for (const chunk of dataChunks) {
try {
const jsonStr = chunk.substring(6);
const jsonData = JSON.parse(jsonStr);
if (jsonData.choices && ((_b = (_a = jsonData.choices[0]) === null || _a === void 0 ? void 0 : _a.delta) === null || _b === void 0 ? void 0 : _b.content)) {
fullContent += jsonData.choices[0].delta.content;
}
}
catch (e) {
}
}
return fullContent;
}
//# sourceMappingURL=GenericFunctions.js.map
;