@@ -26,36 +26,36 @@ For analytics, caching, rate limiting, and more, you can also send requests like
2626import OpenAI from " openai" ;
2727
2828export default {
29- async fetch(request , env , ctx ): Promise <Response > {
30- const openai = new OpenAI ({
31- apiKey: env .OPENAI_API_KEY ,
32- });
33-
34- // Create a TransformStream to handle streaming data
35- let { readable, writable } = new TransformStream ();
36- let writer = writable .getWriter ();
37- const textEncoder = new TextEncoder ();
38-
39- ctx .waitUntil (
40- (async () => {
41- const stream = await openai .chat .completions .create ({
42- model: " gpt-4o-mini" ,
43- messages: [{ role: " user" , content: " Tell me a story" }],
44- stream: true ,
45- });
46-
47- // loop over the data as it is streamed and write to the writeable
48- for await (const part of stream ) {
49- writer .write (
50- textEncoder .encode (part .choices [0 ]?.delta ?.content || " " ),
51- );
52- }
53- writer .close ();
54- })(),
55- );
56-
57- // Send the readable back to the browser
58- return new Response (readable );
59- },
29+ async fetch(request , env , ctx ): Promise <Response > {
30+ const openai = new OpenAI ({
31+ apiKey: env .OPENAI_API_KEY ,
32+ });
33+
34+ // Create a TransformStream to handle streaming data
35+ let { readable, writable } = new TransformStream ();
36+ let writer = writable .getWriter ();
37+ const textEncoder = new TextEncoder ();
38+
39+ ctx .waitUntil (
40+ (async () => {
41+ const stream = await openai .chat .completions .create ({
42+ model: " gpt-4o-mini" ,
43+ messages: [{ role: " user" , content: " Tell me a story" }],
44+ stream: true ,
45+ });
46+
47+ // loop over the data as it is streamed and write to the writeable
48+ for await (const part of stream ) {
49+ writer .write (
50+ textEncoder .encode (part .choices [0 ]?.delta ?.content || " " ),
51+ );
52+ }
53+ writer .close ();
54+ })(),
55+ );
56+
57+ // Send the readable back to the browser
58+ return new Response (readable );
59+ },
6060} satisfies ExportedHandler <Env >;
6161```
0 commit comments