-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
119 lines (86 loc) · 3.31 KB
/
index.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
require('dotenv').config();
const fs = require('fs');
const axios = require('axios');
const apiKey = process.env.API_KEY;
const classifyOption = fs.readFileSync('./opcoes.txt');
const textFieldName = 'teor_ato';
let output = [];
(function () {
return fs.readFile("./input.json", "utf8", async (error, data) => {
if (error) {
console.log(' não conseguiu ler o arquivo de input', error);
return;
}
// try to load already existing responses
if (fs.existsSync('./output.json')) {
const alreadyComputedOutputJson = fs.readFileSync('./output.json');
output = JSON.parse(alreadyComputedOutputJson);
}
const input = JSON.parse(data);
const total = input.length;
for (let i = 0; i < total; i++) {
const data = input[i];
const percentual = Math.trunc(((i + 1) / total) * 100);
const existingResponse = output.find((d) => d.id_pa === data.id_pa);
if (existingResponse && existingResponse.ia_result?.error?.code !== "rate_limit_exceeded") {
console.log(`processando: ${i + 1} de ${total} - ${percentual}% - skiped alerady has response`);
continue;
}
const textToClassify = data[textFieldName];
const promptText =
`Dado o seguinte texto:
${textToClassify}
classifique-o usando apenas um dos seguintes temas:
${classifyOption}`;
const result = await askIA(promptText);
if (!existingResponse) {
output.push({
...data,
ia_result: result
});
} else {
output = output.map(d => {
if (d.id_pa === data.id_pa) {
return ({
...data,
ia_result: result
});
}
return d;
})
}
console.log(`processando: ${i + 1} de ${total} - ${percentual}% - ${result?.error?.code || result}`);
let outputJson = JSON.stringify(output);
fs.writeFileSync('./output.json', outputJson);
await sleep();
}
console.log('Completed saída disponível no arquivo output.json');
});
})();
function sleep() {
return new Promise((resolve) => {
setTimeout(() => resolve(null), 800); // 0.8s
});
}
function askIA(promptText) {
return new Promise(async (resolve) => {
try {
const response = await axios.post(
'https://api.openai.com/v1/chat/completions',
{
model: 'gpt-3.5-turbo',
messages: [{ role: 'user', content: promptText }],
},
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
},
}
);
resolve(response?.data?.choices[0]?.message?.content || 'ERRO: sem resposta');
} catch (error) {
return resolve('ERRO: ' + error?.response ? error.response?.data : error?.message);
}
});
}