|
| 1 | +import { NextRequest, NextResponse } from "next/server"; |
| 2 | +import { |
| 3 | + ExtractionRequestSchema, |
| 4 | + EXTRACTION_RESULT_JSON_SCHEMA, |
| 5 | + type ExtractionResponse, |
| 6 | + type ProviderId, |
| 7 | +} from "~/types/extraction"; |
| 8 | +import type { LLMProviderConfig, Message, Settings } from "~/types/llm"; |
| 9 | +import { |
| 10 | + anthropicConfig, |
| 11 | + openaiConfig, |
| 12 | + geminiConfig, |
| 13 | +} from "~/utils/llm/providers"; |
| 14 | +import { |
| 15 | + DEFAULT_EXTRACTION_PROMPT, |
| 16 | + buildUserPrompt, |
| 17 | +} from "~/prompts/extraction"; |
| 18 | +import { parseExtractionResponse } from "~/utils/ai/parseExtractionResponse"; |
| 19 | + |
| 20 | +export const runtime = "nodejs"; |
| 21 | +export const maxDuration = 300; |
| 22 | + |
| 23 | +const PROVIDER_CONFIGS: Record<ProviderId, LLMProviderConfig> = { |
| 24 | + anthropic: anthropicConfig, |
| 25 | + openai: openaiConfig, |
| 26 | + gemini: geminiConfig, |
| 27 | +}; |
| 28 | + |
| 29 | +const buildExtractionMessages = ({ |
| 30 | + provider, |
| 31 | + pdfBase64, |
| 32 | + userPrompt, |
| 33 | +}: { |
| 34 | + provider: ProviderId; |
| 35 | + pdfBase64: string; |
| 36 | + userPrompt: string; |
| 37 | +}): Message[] => { |
| 38 | + switch (provider) { |
| 39 | + case "anthropic": |
| 40 | + return [ |
| 41 | + { |
| 42 | + role: "user", |
| 43 | + content: [ |
| 44 | + { |
| 45 | + type: "document", |
| 46 | + source: { |
| 47 | + type: "base64", |
| 48 | + media_type: "application/pdf", // eslint-disable-line @typescript-eslint/naming-convention |
| 49 | + data: pdfBase64, |
| 50 | + }, |
| 51 | + }, |
| 52 | + { type: "text", text: userPrompt }, |
| 53 | + ], |
| 54 | + }, |
| 55 | + ]; |
| 56 | + case "openai": |
| 57 | + return [ |
| 58 | + { |
| 59 | + role: "user", |
| 60 | + content: [ |
| 61 | + { |
| 62 | + type: "file", |
| 63 | + file: { |
| 64 | + filename: "paper.pdf", |
| 65 | + file_data: `data:application/pdf;base64,${pdfBase64}`, // eslint-disable-line @typescript-eslint/naming-convention |
| 66 | + }, |
| 67 | + }, |
| 68 | + { type: "text", text: userPrompt }, |
| 69 | + ], |
| 70 | + }, |
| 71 | + ]; |
| 72 | + case "gemini": |
| 73 | + return [ |
| 74 | + { |
| 75 | + role: "user", |
| 76 | + content: [ |
| 77 | + { |
| 78 | + inlineData: { |
| 79 | + mimeType: "application/pdf", |
| 80 | + data: pdfBase64, |
| 81 | + }, |
| 82 | + }, |
| 83 | + { text: userPrompt }, |
| 84 | + ], |
| 85 | + }, |
| 86 | + ]; |
| 87 | + } |
| 88 | +}; |
| 89 | + |
| 90 | +export const POST = async ( |
| 91 | + request: NextRequest, |
| 92 | +): Promise<NextResponse<ExtractionResponse>> => { |
| 93 | + let body: unknown; |
| 94 | + try { |
| 95 | + body = await request.json(); |
| 96 | + } catch { |
| 97 | + return NextResponse.json( |
| 98 | + { success: false, error: "Invalid JSON body" }, |
| 99 | + { status: 400 }, |
| 100 | + ); |
| 101 | + } |
| 102 | + |
| 103 | + const validated = ExtractionRequestSchema.safeParse(body); |
| 104 | + if (!validated.success) { |
| 105 | + return NextResponse.json( |
| 106 | + { success: false, error: validated.error.message }, |
| 107 | + { status: 400 }, |
| 108 | + ); |
| 109 | + } |
| 110 | + |
| 111 | + const { pdfBase64, researchQuestion, model, provider, systemPrompt } = |
| 112 | + validated.data; |
| 113 | + |
| 114 | + const config = PROVIDER_CONFIGS[provider]; |
| 115 | + const apiKey = process.env[config.apiKeyEnvVar]; |
| 116 | + |
| 117 | + if (!apiKey) { |
| 118 | + return NextResponse.json( |
| 119 | + { success: false, error: `API key not configured for ${provider}.` }, |
| 120 | + { status: 500 }, |
| 121 | + ); |
| 122 | + } |
| 123 | + |
| 124 | + const messages = buildExtractionMessages({ |
| 125 | + provider, |
| 126 | + pdfBase64, |
| 127 | + userPrompt: buildUserPrompt(researchQuestion), |
| 128 | + }); |
| 129 | + |
| 130 | + const settings: Settings = { |
| 131 | + model, |
| 132 | + maxTokens: 16384, |
| 133 | + temperature: 0.6, |
| 134 | + systemPrompt: systemPrompt ?? DEFAULT_EXTRACTION_PROMPT, |
| 135 | + outputSchema: EXTRACTION_RESULT_JSON_SCHEMA, |
| 136 | + }; |
| 137 | + |
| 138 | + const apiUrl = |
| 139 | + typeof config.apiUrl === "function" |
| 140 | + ? config.apiUrl(settings) |
| 141 | + : config.apiUrl; |
| 142 | + |
| 143 | + try { |
| 144 | + const response = await fetch(apiUrl, { |
| 145 | + method: "POST", |
| 146 | + headers: config.apiHeaders(apiKey), |
| 147 | + body: JSON.stringify(config.formatRequestBody(messages, settings)), |
| 148 | + signal: AbortSignal.timeout(270_000), |
| 149 | + }); |
| 150 | + |
| 151 | + if (!response.ok) { |
| 152 | + const errorText = await response.text().catch(() => ""); |
| 153 | + return NextResponse.json( |
| 154 | + { |
| 155 | + success: false, |
| 156 | + error: `${provider} API error (${response.status}): ${errorText.slice(0, 200)}`, |
| 157 | + }, |
| 158 | + { status: 502 }, |
| 159 | + ); |
| 160 | + } |
| 161 | + |
| 162 | + const responseData: unknown = await response.json(); |
| 163 | + const rawText = config.extractResponseText(responseData); |
| 164 | + |
| 165 | + if (!rawText) { |
| 166 | + return NextResponse.json( |
| 167 | + { success: false, error: `Empty response from ${provider}` }, |
| 168 | + { status: 502 }, |
| 169 | + ); |
| 170 | + } |
| 171 | + |
| 172 | + let result; |
| 173 | + try { |
| 174 | + result = parseExtractionResponse(rawText); |
| 175 | + } catch (parseError) { |
| 176 | + const message = |
| 177 | + parseError instanceof SyntaxError |
| 178 | + ? "LLM returned invalid JSON" |
| 179 | + : "LLM returned unexpected response structure"; |
| 180 | + return NextResponse.json( |
| 181 | + { |
| 182 | + success: false, |
| 183 | + error: `Failed to parse extraction response — ${message}`, |
| 184 | + }, |
| 185 | + { status: 502 }, |
| 186 | + ); |
| 187 | + } |
| 188 | + |
| 189 | + return NextResponse.json({ success: true, data: result }); |
| 190 | + } catch (error) { |
| 191 | + const message = |
| 192 | + error instanceof Error |
| 193 | + ? `Extraction failed — ${error.message}` |
| 194 | + : "Extraction failed"; |
| 195 | + console.error("AI extraction failed:", error); |
| 196 | + return NextResponse.json( |
| 197 | + { success: false, error: message }, |
| 198 | + { status: 500 }, |
| 199 | + ); |
| 200 | + } |
| 201 | +}; |
0 commit comments