1
1
#!/usr/bin/env -S npm run tsn -T
2
+ import 'openai/shims/node' ;
2
3
3
4
import OpenAI , { toFile } from 'openai' ;
4
- import fs from 'fs/promises ' ;
5
+ import fs from 'fs' ;
5
6
import path from 'path' ;
6
7
7
8
// gets API Key from environment variable OPENAI_API_KEY
@@ -10,14 +11,34 @@ const openai = new OpenAI();
10
11
const speechFile = path . resolve ( __dirname , './speech.mp3' ) ;
11
12
12
13
async function main ( ) {
14
+ await streamingDemoNode ( ) ;
15
+ await blockingDemo ( ) ;
16
+ }
17
+ main ( ) ;
18
+
19
+ async function streamingDemoNode ( ) {
20
+ const response = await openai . audio . speech . create ( {
21
+ model : 'tts-1' ,
22
+ voice : 'alloy' ,
23
+ input : 'the quick brown chicken jumped over the lazy dogs' ,
24
+ } ) ;
25
+
26
+ const stream = response . body ;
27
+
28
+ console . log ( `Streaming response to ${ speechFile } ` ) ;
29
+ await streamToFile ( stream , speechFile ) ;
30
+ console . log ( 'Finished streaming' ) ;
31
+ }
32
+
33
+ async function blockingDemo ( ) {
13
34
const mp3 = await openai . audio . speech . create ( {
14
35
model : 'tts-1' ,
15
36
voice : 'alloy' ,
16
37
input : 'the quick brown fox jumped over the lazy dogs' ,
17
38
} ) ;
18
39
19
40
const buffer = Buffer . from ( await mp3 . arrayBuffer ( ) ) ;
20
- await fs . writeFile ( speechFile , buffer ) ;
41
+ await fs . promises . writeFile ( speechFile , buffer ) ;
21
42
22
43
const transcription = await openai . audio . transcriptions . create ( {
23
44
file : await toFile ( buffer , 'speech.mp3' ) ,
@@ -32,4 +53,21 @@ async function main() {
32
53
console . log ( translation . text ) ;
33
54
}
34
55
35
- main ( ) ;
56
+ /**
57
+ * Note, this is Node-specific.
58
+ *
59
+ * Other runtimes would need a different `fs`,
60
+ * and would also use a web ReadableStream,
61
+ * which is different from a Node ReadableStream.
62
+ */
63
+ async function streamToFile ( stream : NodeJS . ReadableStream , path : fs . PathLike ) {
64
+ return new Promise ( ( resolve , reject ) => {
65
+ const writeStream = fs . createWriteStream ( path ) . on ( 'error' , reject ) . on ( 'finish' , resolve ) ;
66
+
67
+ // If you don't see a `stream.pipe` method and you're using Node you might need to add `import 'openai/shims/node'` at the top of your entrypoint file.
68
+ stream . pipe ( writeStream ) . on ( 'error' , ( error ) => {
69
+ writeStream . close ( ) ;
70
+ reject ( error ) ;
71
+ } ) ;
72
+ } ) ;
73
+ }
0 commit comments