forked from gaomar/node-red-contrib-simple-gpt-vision
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnode.js
88 lines (85 loc) · 2.29 KB
/
node.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
module.exports = (RED) => {
const OpenAI = require("openai");
const main = function (config) {
RED.nodes.createNode(this, config);
this.prompt = config.prompt || [];
this.promptType = config.promptType || "str";
this.Token = config.Token || "";
const node = this;
const openai = new OpenAI({
apiKey: node.Token,
});
node.on("input", async (msg) => {
node.status({ fill: "green", shape: "dot", text: "処理中..." });
try {
let prompt = "";
RED.util.evaluateNodeProperty(
node.prompt,
node.promptType,
node,
msg,
(err, value) => {
if (err) {
return;
} else {
prompt = value;
}
}
);
// url or base64
let imageData = msg.payload;
if (!msg.payload.startsWith("http")) imageData = `data:image/png;base64,${msg.payload}`;
const messages = [
{
role: "system",
content: "lang:ja"
},
{
role: "user",
content: [
{
type: "text",
text: prompt
},
{
type: "image_url",
image_url: {
url: imageData
}
}
]
}
];
const resp = await openai.chat.completions.create({
model: 'gpt-4o',
max_tokens: 1024,
messages
})
msg.payload = resp.choices[0].message.content;
node.status({});
} catch (error) {
if (error.response) {
node.status({
fill: "red",
shape: "dot",
text: `${error.response.status}, ${JSON.stringify(
error.response.data.error.message
)}`,
});
msg.payload = `${error.response.status}, ${JSON.stringify(
error.response.data.error.message
)}`;
} else {
node.status({
fill: "red",
shape: "dot",
text: `${error.type}, ${error.message}`,
});
msg.payload = `${error.type}, ${error.message}`;
}
}
node.send(msg);
});
};
RED.nodes.registerType("simple-gpt-vision", main);
};