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
import { OpenAI } from "https://esm.town/v/std/openai?v=4";
const prompt = "Tell me a dad joke. Format the response as JSON with 'setup' and 'punchline' keys.";
const style = "<style>body{font-family:system-ui,sans-serif;margin:0;padding:32px}</style>";
export default async function dailyDadJoke(req: Request): Response {
const openai = new OpenAI();
const resp = await openai.chat.completions.create({
messages: [
{ role: "user", content: prompt },
],
model: "gpt-3.5-turbo",
max_tokens: 64,
});
// Clean up the response content
let content = resp.choices[0].message.content;
// Remove any markdown formatting (e.g., ```json)
content = content.replace(/```json/g, "").replace(/```/g, "");
// Now try to parse the cleaned content
let setup = "Oops! Couldn't get the joke!";
let punchline = "Try refreshing the page.";
try {
const joke = JSON.parse(content);
setup = joke.setup || setup;
punchline = joke.punchline || punchline;
} catch (e) {
console.error("Failed to parse joke response:", e);
}
const html = `
${style}
<h1>${setup}</h1>
<p>${punchline}</p>
`;
return new Response(html, {
headers: {
"Content-Type": "text/html",
},
});
}