-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApiClientPerplexity.js
95 lines (80 loc) · 2.37 KB
/
ApiClientPerplexity.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
const ApiClient = require('./ApiClient');
const OpenAI = require('openai');
class ApiClientPerplexity extends ApiClient {
constructor(apiKey, messageLog) {
super(apiKey, messageLog);
this.baseURL = "https://api.perplexity.ai";
this.openai = new OpenAI({ baseURL: this.baseURL, apiKey: this.apiKey });
}
async sendMessage(model) {
const rawMessageLog = this.messageLog.getRawMessageLog();
const formattedMessageLog = this.transformMessageLog(rawMessageLog);
//console.log(JSON.stringify(formattedMessageLog, null, 2));
// Import the ora module
const ora = (await import('ora')).default;
// Create a new ora instance
const spinner = ora().start();
const response = await this.openai.chat.completions.create({
model: model,
max_tokens: 4096,
temperature: 0,
messages: formattedMessageLog,
});
// Log the entire response
console.log('\n\nAPI Response:', response);
// Stop the spinner
spinner.stop();
// Return the response
return response.choices[0].message.content;
}
transformMessageLog(rawMessageLog) {
let transformedMessageLog = [];
let userContent = '';
for (let i = 0; i < rawMessageLog.length; i++) {
let message = rawMessageLog[i];
if (message.role === 'user') {
userContent += message.content;
}
else {
if (userContent) {
transformedMessageLog.push({
role: 'user',
content: [{
type: 'text',
text: userContent
}]
});
userContent = '';
}
transformedMessageLog.push({
role: 'assistant',
content: [{
type: message.type,
text: message.content
}]
});
}
}
// if the last message was a user message, add it to the transformed message log
if (userContent) {
transformedMessageLog.push({
role: 'user',
content: [{
type: 'text',
text: userContent
}]
});
}
// Add a continue message
//transformedMessageLog.push({
// role: 'assistant',
// content: [{
// type: 'text',
// text: 'continue'
// }]
//});
//console.log(JSON.stringify(transformedMessageLog, null, 2));
return transformedMessageLog;
}
}
module.exports = ApiClientPerplexity;