-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathroute.ts
More file actions
168 lines (150 loc) · 5.13 KB
/
route.ts
File metadata and controls
168 lines (150 loc) · 5.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
/**
* Scene Content Generation API
*
* Generates scene content (slides/quiz/interactive/pbl) from an outline.
* This is the first half of the two-step scene generation pipeline.
* Does NOT generate actions — use /api/generate/scene-actions for that.
*/
import { NextRequest } from 'next/server';
import { callLLM } from '@/lib/ai/llm';
import {
applyOutlineFallbacks,
generateSceneContent,
buildVisionUserContent,
} from '@/lib/generation/generation-pipeline';
import { normalizeGenerationLanguage } from '@/lib/generation/language';
import type { AgentInfo } from '@/lib/generation/generation-pipeline';
import type { SceneOutline, PdfImage, ImageMapping } from '@/lib/types/generation';
import { createLogger } from '@/lib/logger';
import { apiError, apiSuccess } from '@/lib/server/api-response';
import { resolveModelFromHeaders } from '@/lib/server/resolve-model';
const log = createLogger('Scene Content API');
export const maxDuration = 300;
export async function POST(req: NextRequest) {
try {
const body = await req.json();
const {
outline: rawOutline,
allOutlines,
pdfImages,
imageMapping,
stageInfo,
stageId,
agents,
} = body as {
outline: SceneOutline;
allOutlines: SceneOutline[];
pdfImages?: PdfImage[];
imageMapping?: ImageMapping;
stageInfo: {
name: string;
description?: string;
language?: string;
style?: string;
};
stageId: string;
agents?: AgentInfo[];
};
// Validate required fields
if (!rawOutline) {
return apiError('MISSING_REQUIRED_FIELD', 400, 'outline is required');
}
if (!allOutlines || allOutlines.length === 0) {
return apiError(
'MISSING_REQUIRED_FIELD',
400,
'allOutlines is required and must not be empty',
);
}
if (!stageId) {
return apiError('MISSING_REQUIRED_FIELD', 400, 'stageId is required');
}
// Ensure outline has language from stageInfo (fallback for older outlines)
const outline: SceneOutline = {
...rawOutline,
language: rawOutline.language ?? normalizeGenerationLanguage(stageInfo?.language),
};
// ── Model resolution from request headers ──
const { model: languageModel, modelInfo, modelString } = resolveModelFromHeaders(req);
// Detect vision capability
const hasVision = !!modelInfo?.capabilities?.vision;
// Vision-aware AI call function
const aiCall = async (
systemPrompt: string,
userPrompt: string,
images?: Array<{ id: string; src: string }>,
): Promise<string> => {
if (images?.length && hasVision) {
const result = await callLLM(
{
model: languageModel,
system: systemPrompt,
messages: [
{
role: 'user' as const,
content: buildVisionUserContent(userPrompt, images),
},
],
maxOutputTokens: modelInfo?.outputWindow,
},
'scene-content',
);
return result.text;
}
const result = await callLLM(
{
model: languageModel,
system: systemPrompt,
prompt: userPrompt,
maxOutputTokens: modelInfo?.outputWindow,
},
'scene-content',
);
return result.text;
};
// ── Apply fallbacks ──
const effectiveOutline = applyOutlineFallbacks(outline, !!languageModel);
// ── Filter images assigned to this outline ──
let assignedImages: PdfImage[] | undefined;
if (
pdfImages &&
pdfImages.length > 0 &&
effectiveOutline.suggestedImageIds &&
effectiveOutline.suggestedImageIds.length > 0
) {
const suggestedIds = new Set(effectiveOutline.suggestedImageIds);
assignedImages = pdfImages.filter((img) => suggestedIds.has(img.id));
}
// ── Media generation is handled client-side in parallel (media-orchestrator.ts) ──
// The content generator receives placeholder IDs (gen_img_1, gen_vid_1) as-is.
// resolveImageIds() in generation-pipeline.ts will keep these placeholders in elements.
const generatedMediaMapping: ImageMapping = {};
// ── Generate content ──
log.info(
`Generating content: "${effectiveOutline.title}" (${effectiveOutline.type}) [model=${modelString}]`,
);
const content = await generateSceneContent(
effectiveOutline,
aiCall,
assignedImages,
imageMapping,
effectiveOutline.type === 'pbl' ? languageModel : undefined,
hasVision,
generatedMediaMapping,
agents,
);
if (!content) {
log.error(`Failed to generate content for: "${effectiveOutline.title}"`);
return apiError(
'GENERATION_FAILED',
500,
`Failed to generate content: ${effectiveOutline.title}`,
);
}
log.info(`Content generated successfully: "${effectiveOutline.title}"`);
return apiSuccess({ content, effectiveOutline });
} catch (error) {
log.error('Scene content generation error:', error);
return apiError('INTERNAL_ERROR', 500, error instanceof Error ? error.message : String(error));
}
}