import OpenAI from "npm:openai";
const openai = new OpenAI();
export default async (req) => {
const { readable, writable } = new TransformStream();
const writer = writable.getWriter();
const textEncoder = new TextEncoder();
const url = new URL(req.url);
const prompt = url.searchParams.get("prompt") || "tell me a joke";
if (!prompt || prompt.trim() === "") {
return new Response("Please provide a prompt in the URL query.", {
headers: {
"Content-Type": "text/plain",
},
status: 400,
});
}
const stream = await openai.chat.completions.create({
model: "gpt-4o",
messages: [{
role: "system",
content: "You are a helpful assistant that provides detailed and informative responses to user prompts.",
}, {
role: "user",
content: prompt.trim(),
}],
max_tokens: 1024,
stream: true,
});
new Promise(async () => {
for await (const part of stream) {
const text = part.choices[0]?.delta?.content || "";
console.log('text::', text)
writer.write(textEncoder.encode(text));
}
writer.close();
});
return new Response(readable, {
headers: {
"Content-Type": "text/html",
},
});
};