-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathai.js
More file actions
210 lines (178 loc) · 6.01 KB
/
ai.js
File metadata and controls
210 lines (178 loc) · 6.01 KB
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
const https = require('https');
const http = require('http');
const { URL } = require('url');
class OpenAICompatibleClient {
constructor(config) {
if (!config || !config.baseURL || !config.apiKey) {
throw new Error('Missing baseURL or apiKey in config');
}
this.baseURL = config.baseURL.replace(/\/$/, '');
this.apiKey = config.apiKey;
this.model = config.model || 'gpt-4o-mini';
}
buildPayload(messages, options = {}, stream = false) {
const payload = {
model: options.model || this.model,
messages,
temperature: options.temperature ?? 0.7,
max_tokens: options.maxTokens ?? 1500,
stream
};
if (stream && options.includeUsage) {
payload.stream_options = { include_usage: true };
}
return payload;
}
createRequestOptions(url, payload) {
const isHttps = url.protocol === 'https:';
return {
client: isHttps ? https : http,
request: {
hostname: url.hostname,
port: url.port || (isHttps ? 443 : 80),
path: url.pathname + url.search,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`,
'Content-Length': Buffer.byteLength(payload)
},
timeout: 60000
}
};
}
extractDeltaContent(chunk) {
const delta = chunk && chunk.choices && chunk.choices[0] && chunk.choices[0].delta;
const content = delta && delta.content;
if (!content) return '';
if (typeof content === 'string') return content;
if (!Array.isArray(content)) return '';
return content.map(part => {
if (typeof part === 'string') return part;
if (part && typeof part.text === 'string') return part.text;
if (part && part.text && typeof part.text.value === 'string') return part.text.value;
return '';
}).join('');
}
async chat(messages, options = {}) {
const url = new URL(this.baseURL + '/chat/completions');
const payload = JSON.stringify(this.buildPayload(messages, options, false));
const { client, request } = this.createRequestOptions(url, payload);
return new Promise((resolve, reject) => {
const req = client.request(request, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
try {
const json = JSON.parse(data);
if (json.error) {
reject(new Error(`API Error: ${json.error.message || JSON.stringify(json.error)}`));
} else if (json.choices && json.choices[0] && json.choices[0].message) {
resolve(json.choices[0].message.content);
} else {
reject(new Error('Unexpected API response format'));
}
} catch (err) {
reject(new Error(`Parse error: ${err.message}. Raw: ${data.slice(0, 200)}`));
}
});
});
req.on('error', reject);
req.on('timeout', () => {
req.destroy();
reject(new Error('Request timeout'));
});
req.write(payload);
req.end();
});
}
async streamChat(messages, options = {}) {
const url = new URL(this.baseURL + '/chat/completions');
const payload = JSON.stringify(this.buildPayload(messages, options, true));
const { client, request } = this.createRequestOptions(url, payload);
return new Promise((resolve, reject) => {
const req = client.request(request, (res) => {
if (res.statusCode < 200 || res.statusCode >= 300) {
let errorBody = '';
res.on('data', chunk => errorBody += chunk);
res.on('end', () => reject(new Error(`HTTP ${res.statusCode}: ${errorBody.slice(0, 300)}`)));
return;
}
let buffer = '';
let fullText = '';
let done = false;
const finalize = async () => {
if (done) return;
done = true;
if (typeof options.onComplete === 'function') {
await options.onComplete(fullText);
}
resolve(fullText);
};
const processEvent = async (rawEvent) => {
const lines = rawEvent.split(/\r?\n/);
const dataLines = [];
for (const line of lines) {
if (line.startsWith('data:')) {
dataLines.push(line.slice(5).trimStart());
}
}
if (dataLines.length === 0) return;
const data = dataLines.join('\n');
if (!data) return;
if (data === '[DONE]') {
await finalize();
return;
}
let chunk;
try {
chunk = JSON.parse(data);
} catch {
return;
}
if (chunk.error) {
throw new Error(`API Error: ${chunk.error.message || JSON.stringify(chunk.error)}`);
}
const deltaText = this.extractDeltaContent(chunk);
if (!deltaText) return;
fullText += deltaText;
if (typeof options.onDelta === 'function') {
await options.onDelta(deltaText, fullText, chunk);
}
};
res.on('data', chunk => {
buffer += chunk.toString('utf8');
const consume = async () => {
let boundary = buffer.indexOf('\n\n');
while (boundary !== -1) {
const rawEvent = buffer.slice(0, boundary);
buffer = buffer.slice(boundary + 2);
await processEvent(rawEvent);
boundary = buffer.indexOf('\n\n');
}
};
consume().catch(reject);
});
res.on('end', () => {
if (!done) {
if (buffer.trim()) {
processEvent(buffer).then(() => finalize()).catch(reject);
} else {
finalize().catch(reject);
}
}
});
});
req.on('error', reject);
req.on('timeout', () => {
req.destroy();
reject(new Error('Request timeout'));
});
req.write(payload);
req.end();
});
}
}
module.exports = {
OpenAICompatibleClient
};