team-4/backend/ai-selector.ts
2025-08-02 13:28:10 +02:00

48 lines
1.8 KiB
TypeScript

import { GoogleGenAI } from "npm:@google/genai@1.12.0";
import { assert } from "https://deno.land/std@0.224.0/assert/mod.ts";
import schema from "./schemas/AiSuggestionsOutput.json" with { type: "json" };
import { AiSuggestionsOutput } from "./types/ai.ts";
const ai = new GoogleGenAI({});
// Generate songs using AI
export async function generateSongs(
userPrompt: string,
rules: string,
): Promise<AiSuggestionsOutput> {
const rulesText = rules && rules.trim().length > 0
? `Make sure that they follow the following set of rules: "${rules}".`
: "";
const aiPrompt = `
Based on this music request: "${userPrompt}", generate 15 suggestion for songs.
Make sure they are real, popular songs that exist on Spotify.
Make sure to follow the following set of costraints in order to suggest songs but bear in mind
to return an error only in extreme cases. Ypu can be a little open even if genres clash with eah other a little bit.
The rules are: "${rulesText}"
The type should be either succes or error.
Make the error as user friendly as possible ans concise, and don't make it happen too often.
`;
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: aiPrompt,
config: { responseMimeType: "application/json", responseSchema: schema },
});
const text = response.candidates?.at(0)?.content?.parts?.at(0)?.text;
if (!text) {
throw Error("Text not found");
}
return JSON.parse(text) as AiSuggestionsOutput;
}
Deno.test("generateSongs basic", async () => {
const prompt = "Give me 5 songs by the queens";
const rules = "Songs must vool";
const songs = await generateSongs(prompt, rules);
console.log(songs);
assert(songs.type === "success");
});