Skip to content

Commit 801105c

Browse files
committed
PCX review (prettify)
1 parent 5f929e0 commit 801105c

File tree

1 file changed

+31
-31
lines changed

1 file changed

+31
-31
lines changed

src/content/docs/workers/examples/openai-sdk-streaming.mdx

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -26,36 +26,36 @@ For analytics, caching, rate limiting, and more, you can also send requests like
2626
import OpenAI from "openai";
2727

2828
export 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

Comments
 (0)