improved question generation

This commit is contained in:
Daniel Bulant 2026-05-16 13:28:03 +02:00
parent bfeb44a625
commit fca9608de7
No known key found for this signature in database
7 changed files with 123 additions and 52 deletions

View file

@ -107,6 +107,31 @@ describe("question generation", () => {
); );
}); });
it("preserves candidate metadata on the generated question", () => {
const question = pickQuestionCandidate(
[
{
key: "social:leader",
subjectKey: "member:a",
question: {
type: "choice",
text: "Who is leading the quiz right now?",
correct: 0,
startTimestamp: 1,
endTimestamp: 2,
points: 10,
options: ["A", "B"],
} as Question,
},
],
[],
0,
);
expect(question?.questionKey).toBe("social:leader");
expect(question?.subjectKey).toBe("member:a");
});
it("returns null when member options would require fake placeholders", () => { it("returns null when member options would require fake placeholders", () => {
const members: PartyQuestionMember[] = [ const members: PartyQuestionMember[] = [
{ userId: "a", name: "Sam" }, { userId: "a", name: "Sam" },

View file

@ -0,0 +1,50 @@
import { describe, expect, it, vi } from "vitest";
import type { QuizState } from "../../party-types";
vi.mock("../audio-question-generator", () => ({
buildAudioMetadataQuestion: vi.fn(async () => null),
}));
vi.mock("../social-question-generator", () => ({
buildSocialQuestion: vi.fn(async () => null),
}));
vi.mock("../numeric-question-generator", () => ({
buildNumericQuestion: vi.fn(async () => null),
}));
import { generatePartyQuestion } from "../question-generator";
function createFakeDb() {
return {
query: {
partyMember: {
findMany: vi.fn(async () => [{ userId: "a", user: { name: "A" } }]),
},
},
};
}
describe("generatePartyQuestion", () => {
it("returns null when all real question sources are exhausted", async () => {
const quizState = {
status: "running",
workflowId: null,
questionIndex: 0,
currentQuestion: null,
answers: {},
scores: {},
history: [],
} as QuizState;
const question = await generatePartyQuestion({
db: createFakeDb() as never,
partyId: "party-1",
quizState,
analytics: null,
index: 0,
});
expect(question).toBeNull();
});
});

View file

@ -10,7 +10,6 @@ import {
isUsableText, isUsableText,
type PartyAnalytics, type PartyAnalytics,
pickQuestionCandidate, pickQuestionCandidate,
pickRandom,
type QuestionCandidate, type QuestionCandidate,
resolveQuestionSong, resolveQuestionSong,
} from "./question-utils"; } from "./question-utils";
@ -115,15 +114,13 @@ export async function buildAudioMetadataQuestion(
} }
} }
const randomTopTrack = pickRandom(topTracks); for (const topTrack of topTracks) {
if (randomTopTrack) { const trackSong = await resolveQuestionSong(dbClient, analytics, {
const randomTrackSong = await resolveQuestionSong(dbClient, analytics, { trackName: topTrack.name,
trackName: randomTopTrack.name, artistNames: topTrack.artists?.map((artist) => artist.name),
artistNames: randomTopTrack.artists?.map((artist) => artist.name), albumName: topTrack.albumName,
albumName: randomTopTrack.albumName,
}); });
const trackArtists = const trackArtists = topTrack.artists?.map((artist) => artist.name) ?? [];
randomTopTrack.artists?.map((artist) => artist.name) ?? [];
const allArtists = topArtists.length > 0 ? topArtists : trackArtists; const allArtists = topArtists.length > 0 ? topArtists : trackArtists;
const correctArtist = trackArtists[0] ?? allArtists[0]; const correctArtist = trackArtists[0] ?? allArtists[0];
if (correctArtist) { if (correctArtist) {
@ -134,41 +131,41 @@ export async function buildAudioMetadataQuestion(
); );
if (artistOptions) { if (artistOptions) {
questions.push({ questions.push({
key: `audio:performer:${randomTopTrack.name}`, key: `audio:performer:${topTrack.name}`,
subjectKey: `track:${randomTopTrack.name}`, subjectKey: `track:${topTrack.name}`,
question: { question: {
type: "choice", type: "choice",
text: `Who performs "${randomTopTrack.name}"?`, text: `Who performs "${topTrack.name}"?`,
options: artistOptions, options: artistOptions,
correct: 0, correct: 0,
points: 10, points: 10,
song: randomTrackSong ?? topSong ?? undefined, song: trackSong ?? topSong ?? undefined,
}, },
}); });
} }
const trackNames = topTracks.map((t) => t.name); const trackNames = topTracks.map((t) => t.name);
const trackNameOptions = buildOptionsWithCorrect( const trackNameOptions = buildOptionsWithCorrect(
randomTopTrack.name, topTrack.name,
trackNames, trackNames,
4, 4,
); );
if (trackNameOptions) { if (trackNameOptions) {
questions.push({ questions.push({
key: `audio:title:${randomTopTrack.name}`, key: `audio:title:${topTrack.name}`,
subjectKey: `track:${randomTopTrack.name}`, subjectKey: `track:${topTrack.name}`,
question: { question: {
type: "choice", type: "choice",
text: `What is the name of this track by ${correctArtist}?`, text: `What is the name of this track by ${correctArtist}?`,
options: trackNameOptions, options: trackNameOptions,
correct: 0, correct: 0,
points: 10, points: 10,
song: randomTrackSong ?? topSong ?? undefined, song: trackSong ?? topSong ?? undefined,
}, },
}); });
} }
if (isUsableText(topSongName) && topSongName !== randomTopTrack.name) { if (isUsableText(topSongName) && topSongName !== topTrack.name) {
const alternateSongOptions = buildOptionsWithCorrect( const alternateSongOptions = buildOptionsWithCorrect(
topSongName, topSongName,
trackNames, trackNames,
@ -192,26 +189,26 @@ export async function buildAudioMetadataQuestion(
} }
} }
if (randomTopTrack.albumName) { if (topTrack.albumName) {
const albumNames = topTracks const albumNames = topTracks
.map((track) => track.albumName) .map((track) => track.albumName)
.filter((name): name is string => Boolean(name)); .filter((name): name is string => Boolean(name));
const albumOptions = buildOptionsWithCorrect( const albumOptions = buildOptionsWithCorrect(
randomTopTrack.albumName, topTrack.albumName,
albumNames, albumNames,
4, 4,
); );
if (albumOptions) { if (albumOptions) {
questions.push({ questions.push({
key: `audio:album:${randomTopTrack.albumName}`, key: `audio:album:${topTrack.albumName}`,
subjectKey: `track:${randomTopTrack.name}`, subjectKey: `track:${topTrack.name}`,
question: { question: {
type: "choice", type: "choice",
text: `"${randomTopTrack.name}" appears on which album?`, text: `"${topTrack.name}" appears on which album?`,
options: albumOptions, options: albumOptions,
correct: 0, correct: 0,
points: 10, points: 10,
song: randomTrackSong ?? topSong ?? undefined, song: trackSong ?? topSong ?? undefined,
}, },
}); });
} }

View file

@ -3,7 +3,7 @@ import type { Question, QuizState } from "../party-types";
import { buildAudioMetadataQuestion } from "./audio-question-generator"; import { buildAudioMetadataQuestion } from "./audio-question-generator";
import { buildNumericQuestion } from "./numeric-question-generator"; import { buildNumericQuestion } from "./numeric-question-generator";
import type { PartyAnalytics } from "./question-utils"; import type { PartyAnalytics } from "./question-utils";
import { buildQuestionWindow, fetchPartyMembers } from "./question-utils"; import { fetchPartyMembers } from "./question-utils";
import { buildSocialQuestion } from "./social-question-generator"; import { buildSocialQuestion } from "./social-question-generator";
export type PartyQuestionType = "audio-metadata" | "social" | "numeric"; export type PartyQuestionType = "audio-metadata" | "social" | "numeric";
@ -69,13 +69,5 @@ export async function generatePartyQuestion({
if (q) return q; if (q) return q;
} }
return buildQuestionWindow({ return null;
type: "numeric" as const,
text: "How many players are in this party?",
correct: members.length,
range: { min: 0, max: members.length },
points: 5,
subjectKey: "party-size",
questionKey: `fallback:party-size:${members.length}`,
});
} }

View file

@ -165,7 +165,14 @@ export function pickQuestionCandidate<T extends QuestionLike>(
if (fresh.length === 0) return null; if (fresh.length === 0) return null;
const pool = fresh; const pool = fresh;
return pool[index % pool.length]?.question ?? null; const candidate = pool[index % pool.length];
if (!candidate) return null;
return {
...candidate.question,
questionKey: candidate.question.questionKey ?? candidate.key,
subjectKey:
candidate.question.subjectKey ?? candidate.subjectKey ?? undefined,
} as T;
} }
function normalizeQuestionKey(value: string): string { function normalizeQuestionKey(value: string): string {

View file

@ -12,7 +12,6 @@ import {
type PartyAnalytics, type PartyAnalytics,
type PartyQuestionMember, type PartyQuestionMember,
pickQuestionCandidate, pickQuestionCandidate,
pickRandom,
type QuestionCandidate, type QuestionCandidate,
resolveQuestionSong, resolveQuestionSong,
} from "./question-utils"; } from "./question-utils";
@ -72,27 +71,28 @@ export async function buildSocialQuestion(
} }
const topTracks = getTopClusterTracks(analytics); const topTracks = getTopClusterTracks(analytics);
const randomTrack = pickRandom(topTracks); if (hasMultipleMembers) {
if (randomTrack && hasMultipleMembers) { for (const topTrack of topTracks) {
const topListener = getTopTrackListener(randomTrack, members); const topListener = getTopTrackListener(topTrack, members);
if (topListener) { if (!topListener) continue;
const randomTrackSong = await resolveQuestionSong(dbClient, analytics, {
trackName: randomTrack.name, const trackSong = await resolveQuestionSong(dbClient, analytics, {
artistNames: randomTrack.artists?.map((artist) => artist.name), trackName: topTrack.name,
albumName: randomTrack.albumName, artistNames: topTrack.artists?.map((artist) => artist.name),
albumName: topTrack.albumName,
}); });
const options = buildMemberOptions(topListener, members); const options = buildMemberOptions(topListener, members);
if (options) { if (options) {
questions.push({ questions.push({
key: `social:track-listener:${randomTrack.name}`, key: `social:track-listener:${topTrack.name}`,
subjectKey: `track:${randomTrack.name}`, subjectKey: `track:${topTrack.name}`,
question: { question: {
type: "choice", type: "choice",
text: `Who listens the most to "${randomTrack.name}"?`, text: `Who listens the most to "${topTrack.name}"?`,
options, options,
correct: 0, correct: 0,
points: 10, points: 10,
song: randomTrackSong ?? topSong ?? undefined, song: trackSong ?? topSong ?? undefined,
}, },
}); });
} }

View file

@ -61,6 +61,9 @@ export class QuizWorkflow extends ConfiguredInstance {
quizState, quizState,
i, i,
); );
if (!question) {
break;
}
quizState.currentQuestion = question; quizState.currentQuestion = question;
quizState.answers = {}; quizState.answers = {};
const round: QuizRound = { const round: QuizRound = {
@ -148,7 +151,7 @@ export class QuizWorkflow extends ConfiguredInstance {
partyId: string, partyId: string,
quizState: QuizState, quizState: QuizState,
index: number, index: number,
): Promise<Question> { ): Promise<Question | null> {
const partyRecord = await db.query.party.findFirst({ const partyRecord = await db.query.party.findFirst({
where: { where: {
id: partyId, id: partyId,
@ -162,9 +165,6 @@ export class QuizWorkflow extends ConfiguredInstance {
analytics, analytics,
index, index,
}); });
if (!question) {
throw new Error("Failed to generate quiz question");
}
return question; return question;
} }