-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenai-test.js
More file actions
36 lines (29 loc) · 926 Bytes
/
openai-test.js
File metadata and controls
36 lines (29 loc) · 926 Bytes
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
const { Configuration, OpenAIApi } = require('openai');
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
async function main() {
const response = await openai.createChatCompletion({
model: 'gpt-3.5-turbo',
messages: [{ role: 'user', content: 'Say this is a test' }],
stream: true,
}, { responseType: 'stream' });
const stream = response.data;
stream.on('data', (chunk) => {
const lines = chunk.toString().split('\n').filter(line => line.trim() !== '');
for (const line of lines) {
const message = line.replace(/^data: /, '');
if (message === '[DONE]') {
stream.destroy();
return;
}
const parsed = JSON.parse(message);
process.stdout.write(parsed.choices[0].delta.content || '');
}
});
stream.on('end', () => {
process.stdout.write('\n');
});
}
main();