-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat.js
90 lines (76 loc) · 2.84 KB
/
chat.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
const MODEL = "gpt-4o-mini";
const API_KEY = process.env['OPENAI_API_KEY'];
const HEADERS = {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`,
}
const URL = "https://api.openai.com/v1/chat/completions";
const chat = async (query="", json_output=false, b64image=null) => {
const content = (b64image === null) ? query : [
{
type: 'text',
text: query
},
{
type: 'image_url',
image_url: {
url: b64image
}
},
]
const body = {
messages: [{ role: 'user', content: content }],
model: MODEL
}
const request = {
headers: HEADERS,
body: JSON.stringify(body),
method: 'POST',
}
if (json_output) {
request['response_format'] = {type: 'json_object'};
}
const response = await fetch(URL, request);
const r = await response.json();
var answer = r.choices[0]?.message?.content;
if (json_output) {
answer = answer.replace('```json', '').replace('```', '');
}
return answer;
}
module.exports = function(RED) {
function ChatNode(config) {
RED.nodes.createNode(this,config);
var node = this;
node.on('input', async msg => {
const query = msg.payload;
const json_output = config.json_output;
const b64image = msg.b64image ?? null;
this.status({fill: "green", shape: "dot", text: "in progress..."});
const answer = await chat(query, json_output, b64image);
this.status({});
msg.payload = answer;
node.send(msg);
});
}
RED.nodes.registerType("chat", ChatNode);
}
if (require.main === module) {
const fs = require('node:fs');
fs.readFile('/tmp/testimg.png', 'ascii', (err, b64image) => {
if (err) {
console.error(err);
return;
}
const answer = chat('Describe', false, `data:image/png;base64,${b64image}`);
answer.then( v => { console.log(v);});
});
const text = `
Pickup key words from the attached document, then count each key words in JSON format.
Output JSON data only.
# document
Websites for 20-something men often revolve around personal growth, fitness, technology, and entertainment. Platforms like Reddit and Twitter provide diverse content and discussions, while fitness hubs such as Bodybuilding.com offer health insights. Tech enthusiasts frequent sites like TechCrunch for the latest gadgets. For personal finance, apps like Mint or blogs like Financial Samurai are popular. Entertainment websites like IMDb or gaming hubs like IGN keep them engaged. These platforms blend practicality, lifestyle, and leisure seamlessly.
`;
const answer2 = chat(text, true);
answer2.then( v => { console.log(v);});
}