-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathroute.ts
More file actions
197 lines (180 loc) · 4.86 KB
/
route.ts
File metadata and controls
197 lines (180 loc) · 4.86 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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import { NextRequest, NextResponse } from "next/server";
import {
ExtractionRequestSchema,
EXTRACTION_RESULT_JSON_SCHEMA,
type ExtractionResponse,
type ProviderId,
} from "~/types/extraction";
import type { LLMProviderConfig, Message, Settings } from "~/types/llm";
import {
anthropicConfig,
openaiConfig,
geminiConfig,
} from "~/utils/llm/providers";
import { buildUserPrompt } from "~/prompts/extraction";
import { parseExtractionResponse } from "~/utils/ai/parseExtractionResponse";
export const runtime = "nodejs";
export const maxDuration = 300;
const PROVIDER_CONFIGS: Record<ProviderId, LLMProviderConfig> = {
anthropic: anthropicConfig,
openai: openaiConfig,
gemini: geminiConfig,
};
const buildExtractionMessages = ({
provider,
pdfBase64,
userPrompt,
}: {
provider: ProviderId;
pdfBase64: string;
userPrompt: string;
}): Message[] => {
switch (provider) {
case "anthropic":
return [
{
role: "user",
content: [
{
type: "document",
source: {
type: "base64",
media_type: "application/pdf", // eslint-disable-line @typescript-eslint/naming-convention
data: pdfBase64,
},
},
{ type: "text", text: userPrompt },
],
},
];
case "openai":
return [
{
role: "user",
content: [
{
type: "file",
file: {
filename: "paper.pdf",
file_data: `data:application/pdf;base64,${pdfBase64}`, // eslint-disable-line @typescript-eslint/naming-convention
},
},
{ type: "text", text: userPrompt },
],
},
];
case "gemini":
return [
{
role: "user",
content: [
{
inlineData: {
mimeType: "application/pdf",
data: pdfBase64,
},
},
{ text: userPrompt },
],
},
];
}
};
export const POST = async (
request: NextRequest,
): Promise<NextResponse<ExtractionResponse>> => {
let body: unknown;
try {
body = await request.json();
} catch {
return NextResponse.json(
{ success: false, error: "Invalid JSON body" },
{ status: 400 },
);
}
const validated = ExtractionRequestSchema.safeParse(body);
if (!validated.success) {
return NextResponse.json(
{ success: false, error: validated.error.message },
{ status: 400 },
);
}
const { pdfBase64, model, provider, systemPrompt } = validated.data;
const config = PROVIDER_CONFIGS[provider];
const apiKey = process.env[config.apiKeyEnvVar];
if (!apiKey) {
return NextResponse.json(
{ success: false, error: `API key not configured for ${provider}.` },
{ status: 500 },
);
}
const messages = buildExtractionMessages({
provider,
pdfBase64,
userPrompt: buildUserPrompt(),
});
const settings: Settings = {
model,
maxTokens: 16384,
temperature: 0.6,
systemPrompt,
outputSchema: EXTRACTION_RESULT_JSON_SCHEMA,
};
const apiUrl =
typeof config.apiUrl === "function"
? config.apiUrl(settings)
: config.apiUrl;
try {
const response = await fetch(apiUrl, {
method: "POST",
headers: config.apiHeaders(apiKey),
body: JSON.stringify(config.formatRequestBody(messages, settings)),
signal: AbortSignal.timeout(270_000),
});
if (!response.ok) {
const errorText = await response.text().catch(() => "");
return NextResponse.json(
{
success: false,
error: `${provider} API error (${response.status}): ${errorText.slice(0, 200)}`,
},
{ status: 502 },
);
}
const responseData: unknown = await response.json();
const rawText = config.extractResponseText(responseData);
if (!rawText) {
return NextResponse.json(
{ success: false, error: `Empty response from ${provider}` },
{ status: 502 },
);
}
let result;
try {
result = parseExtractionResponse(rawText);
} catch (parseError) {
const message =
parseError instanceof SyntaxError
? "LLM returned invalid JSON"
: "LLM returned unexpected response structure";
return NextResponse.json(
{
success: false,
error: `Failed to parse extraction response — ${message}`,
},
{ status: 502 },
);
}
return NextResponse.json({ success: true, data: result });
} catch (error) {
const message =
error instanceof Error
? `Extraction failed — ${error.message}`
: "Extraction failed";
console.error("AI extraction failed:", error);
return NextResponse.json(
{ success: false, error: message },
{ status: 500 },
);
}
};