import { unkey, type UnkeyContext } from "npm:@unkey/hono";
import { Hono } from "npm:hono";
import {
createBedtimeStory,
getBedtimeStoryById,
getRecentBedtimeStories,
} from "https://esm.town/v/dthyresson/bedtimeStoriesDb";
import type { BedtimeStory } from "https://esm.town/v/dthyresson/bedtimeStoriesDb";
import { getSortedActivities } from "https://esm.town/v/dthyresson/bedtimeStoryActivities";
import { getSortedAdjectives } from "https://esm.town/v/dthyresson/bedtimeStoryAdjectives";
import { getSortedAnimals } from "https://esm.town/v/dthyresson/bedtimeStoryAnimals";
import { getSortedColors } from "https://esm.town/v/dthyresson/bedtimeStoryColors";
import { generateOpenGraphTags, OpenGraphData } from "https://esm.town/v/dthyresson/generateOpenGraphTags";
import { ValTownLink } from "https://esm.town/v/dthyresson/viewOnValTownComponent";
import { chat } from "https://esm.town/v/stevekrouse/openai";
import * as fal from "npm:@fal-ai/serverless-client";
export const falConfig = () => {
fal.config({
credentials: Deno.env.get("FAL_KEY"),
});
return fal;
};
const app = new Hono<{ Variables: { unkey: UnkeyContext } }>();
function parseStory(text) {
const lines = text.split("\n").filter(line => line.trim() !== "");
const title = lines[0]
.replace(/^"|"$/g, "")
.replace(/\*\*|\*/g, "")
.replace(/\#\#|\#/g, "")
.trim();
const summary = lines[1]
.replace(/^"|"$/g, "")
.replace(/\*\*|\*/g, "")
.replace(/\#\#|\#/g, "")
.trim();
const story = lines.slice(2).join("\n").replace(/\\n/g, "\n").trim();
return {
title,
summary,
story,
};
}
export const generateBedtimeStory = async (options: BedtimeStory | null): BedtimeStory => {
const { adjective = "funny", color = "pink", animal = "penguin", activity = "flies a kite" } = options;
const { content } = await chat(
[
{
role: "system",
content: `Write a ${adjective} bedtime story about a ${color} colored ${animal} that ${activity}.
The story should have a title, be suitable for young children, give the animal a friendly name and be no longer than 300 words.
Return the title on the first line, on the second line a one sentence summary of this story, and then the story.
If the story mentions other animals, include them in the summary.
`,
},
],
{ max_tokens: 1_000, model: "gpt-4o-mini" },
);
console.log(content);
const parsedContent = parseStory(content);
const story = { ...options, ...parsedContent };
const pictureUrl = await generateBedtimeStoryPictureUrl(story);
return { ...story, pictureUrl };
};
export const generateBedtimeStoryPictureUrl = async (bedtimeStory) => {
const fal = falConfig();
const { adjective, animal, color, summary } = bedtimeStory;