UNPKG

n8n-nodes-grok

Version:

n8n node for Grok API integration

224 lines (223 loc) 9.61 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Grok = void 0; const n8n_workflow_1 = require("n8n-workflow"); const n8n_workflow_2 = require("n8n-workflow"); class Grok { constructor() { this.description = { displayName: 'Grok', name: 'grokApi', icon: 'file:grok.svg', group: ['transform'], version: 1, subtitle: '={{$parameter["operation"]}}', description: 'Interact with Grok API', defaults: { name: 'Grok', }, inputs: '={{["main"]}}', outputs: '={{["main"]}}', credentials: [ { name: 'grokApi', required: true, }, ], properties: [ { displayName: 'Operation', name: 'operation', type: 'options', noDataExpression: true, options: [ { name: 'Chat', value: 'chat', description: 'Send a chat message', action: 'Send a chat message', }, ], default: 'chat', }, { displayName: 'Model Name or ID', name: 'model', type: 'options', noDataExpression: true, typeOptions: { loadOptionsMethod: 'getModels', }, required: true, default: '', description: 'Choose from the list, or specify an ID using an <a href="https://docs.n8n.io/code/expressions/">expression</a>', }, { displayName: 'System Prompt', name: 'system_prompt', type: 'string', typeOptions: { rows: 4, }, default: '', description: 'System message to set the behavior of the assistant', placeholder: 'You are a helpful assistant...', }, { displayName: 'Message', name: 'message', type: 'string', typeOptions: { rows: 4, }, default: '', description: 'The message to send to the chat model', required: true, }, { displayName: 'Temperature', name: 'temperature', type: 'number', default: 0.9, description: 'What sampling temperature to use', }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', default: {}, options: [ { displayName: 'Frequency Penalty', name: 'frequency_penalty', type: 'number', default: 0, description: 'Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency.', }, { displayName: 'Max Tokens', name: 'max_tokens', type: 'number', default: 1000, description: 'The maximum number of tokens to generate', }, { displayName: 'Presence Penalty', name: 'presence_penalty', type: 'number', default: 0, description: 'Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far.', }, { displayName: 'Top P', name: 'top_p', type: 'number', default: 1, description: 'An alternative to sampling with temperature, called nucleus sampling', }, ], }, ], }; this.methods = { loadOptions: { async getModels() { const credentials = await this.getCredentials('grokApi'); try { const response = await this.helpers.httpRequestWithAuthentication.call(this, 'grokApi', { url: 'https://api.x.ai/v1/models', }); n8n_workflow_2.LoggerProxy.info(response); n8n_workflow_2.LoggerProxy.info(response.data); if (!(response === null || response === void 0 ? void 0 : response.data) || !Array.isArray(response.data)) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Invalid response format from Grok API'); } const models = response.data .map((model) => ({ name: model.id, value: model.id })); if (models.length === 0) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'No models found in Grok API response'); } return models; } catch (error) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Failed to load models: ${error.message}`); } }, }, }; } async execute() { var _a, _b, _c; const items = this.getInputData(); const returnData = []; const credentials = await this.getCredentials('grokApi'); if (!(credentials === null || credentials === void 0 ? void 0 : credentials.apiKey)) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'No valid API key provided'); } for (let i = 0; i < items.length; i++) { try { const operation = this.getNodeParameter('operation', i); const model = this.getNodeParameter('model', i); const systemPrompt = this.getNodeParameter('system_prompt', i, ''); const message = this.getNodeParameter('message', i); const temperature = this.getNodeParameter('temperature', i); const additionalFields = this.getNodeParameter('additionalFields', i); if (operation === 'chat') { const messages = []; // Add system message if provided if (systemPrompt) { messages.push({ role: 'system', content: systemPrompt, }); } // Add user message messages.push({ role: 'user', content: message, }); const requestBody = { model, messages, temperature, ...additionalFields, }; const response = await this.helpers.httpRequestWithAuthentication.call(this, 'grokApi', { url: 'https://api.x.ai/v1/chat/completions', method: 'POST', body: requestBody }); if (!((_c = (_b = (_a = response === null || response === void 0 ? void 0 : response.choices) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.message) === null || _c === void 0 ? void 0 : _c.content)) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Invalid response format from Grok API'); } const typedResponse = response; const messageContent = typedResponse.choices[0].message.content.trim(); returnData.push({ json: { response: messageContent, }, pairedItem: { item: i }, }); } } catch (error) { if (this.continueOnFail()) { returnData.push({ json: { error: error.message, }, pairedItem: { item: i }, }); continue; } throw error; } } return [returnData]; } } exports.Grok = Grok;