-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathwebsocket.ts
More file actions
63 lines (53 loc) · 1.69 KB
/
Copy pathwebsocket.ts
File metadata and controls
63 lines (53 loc) · 1.69 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
import { OpenAIRealtimeWebSocket } from 'openai/realtime/websocket';
async function main() {
const rt = new OpenAIRealtimeWebSocket({ model: 'gpt-realtime' });
let responseDone = false;
// access the underlying `ws.WebSocket` instance
rt.socket.addEventListener('open', () => {
console.log('Connection opened!');
rt.send({
type: 'session.update',
session: {
output_modalities: ['text'],
type: 'realtime',
},
});
rt.send({
type: 'conversation.item.create',
item: {
type: 'message',
role: 'user',
content: [{ type: 'input_text', text: 'Say a couple paragraphs!' }],
},
});
rt.send({ type: 'response.create' });
});
rt.on('error', (err) => {
// in a real world scenario this should be logged somewhere as you
// likely want to continue processing events regardless of any errors
throw err;
});
rt.on('session.created', (event) => {
console.log('session created!', event.session);
console.log();
});
rt.on('response.output_text.delta', (event) => process.stdout.write(event.delta));
rt.on('response.output_text.done', () => console.log());
// response.done also covers failed, cancelled, and incomplete responses.
rt.on('response.done', (event) => {
responseDone = true;
if (event.response.status !== 'completed') {
console.error('Response did not complete successfully.');
process.exitCode = 1;
}
rt.close();
});
rt.socket.addEventListener('close', () => {
if (!responseDone) {
console.error('WebSocket closed before the response completed.');
process.exitCode = 1;
}
console.log('\nConnection closed!');
});
}
main();