import { loadPageContent } from "https://esm.town/v/charlypoly/browserbaseUtils";
import { OpenAI } from "https://esm.town/v/std/openai?v=4";
import { z } from "npm:zod";
import { zodToJsonSchema } from "npm:zod-to-json-schema";
import { email } from "https://esm.town/v/std/email?v=12";
let html = await loadPageContent("https://news.ycombinator.com/", { textContent: false });
html = html.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "");
const schema = z.object({
top: z
.array(
z.object({
title: z.string(),
points: z.number(),
by: z.string(),
url: z.string(),
}),
)
.length(5)
.describe("Top 5 stories on Hacker News"),
});
const extractContentTool: any = {
type: "function",
function: {
name: "extract_content",
description: "Extracts the content from the given webpage(s)",
parameters: zodToJsonSchema(schema),
},
};
const openai = new OpenAI();
const completion = await openai.chat.completions.create({
model: "gpt-4-turbo",
messages: [
{
role: "system",
content: "Extract the content from the given webpage(s)",
},
{ role: "user", content: html },
],
tools: [extractContentTool],
tool_choice: "auto",
});
const result = completion.choices[0].message.tool_calls![0].function.arguments;
const parsed = schema.parse(JSON.parse(result));
email({
subject: "Top 5 hacker news of the day",
text: JSON.stringify(parsed.top, null, 2)
})