Files
verse-quote-app/actions/get-random-quote.ts
T

33 lines
1.2 KiB
TypeScript
Raw Normal View History

import { defineAction } from "@agent-native/core/action";
import { z } from "zod";
import { withActionSpan } from "../server/otel.js";
import { fetchAllQuoteRows, hydrateQuotes, parseTags } from "../server/lib/quotes.js";
export default defineAction({
description:
"Get one random poem quote, optionally restricted to a tag. Use for a \"quote of the day\" / discover surface.",
schema: z.object({
tag: z.string().optional().describe("Only pick from quotes with this tag"),
visitorId: z
.string()
.optional()
.describe("Anonymous visitor id, used to mark whether this visitor already favorited the pick"),
}),
http: { method: "GET" },
run: async (args) => {
return withActionSpan("get-random-quote", { tag: args.tag }, async () => {
const rows = await fetchAllQuoteRows();
const candidates = args.tag
? rows.filter((row) => parseTags(row.quote.tags_json).includes(args.tag!))
: rows;
if (candidates.length === 0) return null;
const pick = candidates[Math.floor(Math.random() * candidates.length)];
const [hydrated] = await hydrateQuotes([pick], args.visitorId);
return hydrated;
});
},
});