-
Notifications
You must be signed in to change notification settings - Fork 0
/
groq.js
184 lines (153 loc) · 6.73 KB
/
groq.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
module.exports = function(RED) {
const GROQ = require('groq-sdk');
const DEFAULT_MODEL = 'llama3-8b-8192';
const DEFAULT_TEMPERATURE = 1;
const DEFAULT_MAX_TOKEN = 100;
const DEFAULT_SYSTEM = '';
const DEFAULT_USER = '';
class GroqNode {
constructor(config) {
RED.nodes.createNode(this, config);
this.config = config;
this.groqApiKey = null;
this.client = null;
this.initialized = false;
// Initialize the node
this.initialize();
// Register input event
this.on('input', this.onInput.bind(this));
}
initialize() {
// Retrieve the GROQ configuration node
const configNode = RED.nodes.getNode(this.config.groqConfig);
if (!configNode) {
this.error("GROQ Configuration not found");
return;
}
// Extract the API Key from the configuration node's credentials
this.groqApiKey = configNode.credentials.apiKey;
// Initialize the GROQ client with the API Key
try {
this.client = new GROQ({
apiKey: this.groqApiKey,
// Add other configurations if necessary
});
this.initialized = true;
} catch (error) {
this.error(`Error initializing GROQ client: ${error.message}`);
}
}
async onInput(msg, send, done) {
if (!this.initialized) {
this.error('GROQ client not initialized');
done(new Error('GROQ client not initialized'));
return;
}
try {
const params = this.getParams(msg);
const messages = this.buildMessages(params, msg);
this.status({ fill: 'blue', shape: 'dot', text: 'Requesting' });
this.debug(`Sending GROQ request with the following parameters:
Model: ${params.model}
Temperature: ${params.temperature}
Max Token: ${params.max_token}
System Role: ${params.system}
User Message: ${messages.map(m => m.content).join('\n')}`);
const chatCompletion = await this.client.chat.completions.create({
messages: messages,
model: params.model,
temperature: params.temperature,
max_tokens: params.max_token,
});
const response = chatCompletion.choices[0].message.content;
this.debug(`Response received from GROQ: ${response}`);
msg.payload = response;
send(msg);
done();
this.status({});
} catch (error) {
this.status({ fill: 'red', shape: 'ring', text: 'Error' });
this.error(`Error connecting to GROQ: ${error.message}`, msg);
done(error);
}
}
getParams(msg) {
const model = msg.model || this.config.model || DEFAULT_MODEL;
const temperature = msg.temperature !== undefined ? parseFloat(msg.temperature) : parseFloat(this.config.temperature) || DEFAULT_TEMPERATURE;
const max_token = msg.max_token !== undefined ? parseInt(msg.max_token, 10) : parseInt(this.config.max_token, 10) || DEFAULT_MAX_TOKEN;
const system = msg.system || this.config.system || DEFAULT_SYSTEM;
const user = msg.user || this.config.user || DEFAULT_USER;
if (isNaN(temperature) || temperature < 0.01 || temperature > 2) {
throw new Error('Temperature must be a number between 0.01 and 2');
}
if (isNaN(max_token) || max_token < 1) {
throw new Error('Max Token must be a positive integer');
}
return { model, temperature, max_token, system, user };
}
buildMessages(params, msg) {
const messages = [];
if (params.system) {
messages.push({ role: 'system', content: params.system });
}
if (params.user) {
messages.push({ role: 'user', content: params.user });
} else if (msg.payload) {
messages.push({ role: 'user', content: msg.payload });
} else {
throw new Error('No user message provided');
}
return messages;
}
}
RED.nodes.registerType("groq", GroqNode, {
defaults: {
name: { value: "" },
groqConfig: { type: "groq-config", required: true },
model: { value: DEFAULT_MODEL },
temperature: { value: DEFAULT_TEMPERATURE },
max_token: { value: DEFAULT_MAX_TOKEN },
system: { value: DEFAULT_SYSTEM },
user: { value: DEFAULT_USER }
},
inputs: 1,
outputs: 1,
icon: "file.png",
label: function() {
return this.name || "groq";
}
});
RED.httpAdmin.get('/groq/models', RED.auth.needsPermission('groq.read'), async function(req, res) {
try {
const groqConfigId = req.query.groqConfig;
if (!groqConfigId) {
res.status(400).send("groqConfig parameter is missing");
return;
}
// Retrieve the GROQ configuration node
const configNode = RED.nodes.getNode(groqConfigId);
if (!configNode) {
res.status(400).send("Invalid groqConfig parameter");
return;
}
// Extract the API Key from the configuration node's credentials
const groqApiKey = configNode.credentials.apiKey;
// Initialize the GROQ client with the API Key
const client = new GROQ({
apiKey: groqApiKey,
// Add other configurations if necessary
});
// Fetch the models from the GROQ API
const modelsResponse = await client.models.list();
// Extract the necessary data (id and owned_by) from modelsResponse.data
const models = modelsResponse.data.map(model => ({
id: model.id,
owned_by: model.owned_by
}));
res.json(models);
} catch (error) {
console.error(`Error fetching models: ${error.message}`, error);
res.status(500).send(`Error fetching models: ${error.message}`);
}
});
};