-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathroute.ts
More file actions
420 lines (368 loc) · 16.8 KB
/
Copy pathroute.ts
File metadata and controls
420 lines (368 loc) · 16.8 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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
import { NextResponse } from "next/server";
import { SystemMessage, HumanMessage } from "@langchain/core/messages";
import { db } from "~/server/db/index";
import { eq, sql } from "drizzle-orm";
import ANNOptimizer from "~/app/api/agents/predictive-document-analysis/services/annOptimizer";
import {
companyEnsembleSearch,
documentEnsembleSearch,
type CompanySearchOptions,
type DocumentSearchOptions,
type SearchResult
} from "~/server/rag";
import { validateRequestBody, QuestionSchema } from "~/lib/validation";
import { auth } from "@clerk/nextjs/server";
import { qaRequestCounter, qaRequestDuration } from "~/server/metrics/registry";
import { users, document, ChatHistory } from "~/server/db/schema";
import { withRateLimit } from "~/lib/rate-limit-middleware";
import { RateLimitPresets } from "~/lib/rate-limiter";
import {
normalizeModelContent,
performWebSearch,
getSystemPrompt,
getWebSearchInstruction,
getChatModel,
getEmbeddings,
} from "../../services";
import type { AIModelType } from "../../services";
import type { SYSTEM_PROMPTS } from "../../services/prompts";
export const runtime = 'nodejs';
export const maxDuration = 300;
type PdfChunkRow = Record<string, unknown> & {
id: number;
content: string;
page: number;
distance: number;
};
const qaAnnOptimizer = new ANNOptimizer({
strategy: 'hnsw',
efSearch: 200
});
const COMPANY_SCOPE_ROLES = new Set(["employer", "owner"]);
/**
* AIChat Query - Comprehensive search solution
*
* This endpoint provides comprehensive document Q&A capabilities:
* - Supports both document-level and company-wide searches
* - Advanced retrieval with multiple fallback strategies
* - Web search integration
* - Conversation context support
* - Rich response metadata
*/
export async function POST(request: Request) {
return withRateLimit(request, RateLimitPresets.strict, async () => {
const startTime = Date.now();
const endTimer = qaRequestDuration.startTimer();
let retrievalMethod = "not_started";
const recordResult = (result: "success" | "error" | "empty") => {
qaRequestCounter.inc({ result, retrieval: retrievalMethod });
endTimer({ result, retrieval: retrievalMethod });
};
try {
const validation = await validateRequestBody(request, QuestionSchema);
if (!validation.success) {
recordResult("error");
return validation.response;
}
const { userId } = await auth();
if (!userId) {
recordResult("error");
return NextResponse.json({
success: false,
message: "Unauthorized"
}, { status: 401 });
}
const {
documentId,
companyId,
question,
style,
searchScope,
enableWebSearch,
aiPersona,
aiModel,
conversationHistory,
} = validation.data;
// Validate search scope requirements
if (searchScope === "company" && !companyId) {
recordResult("error");
return NextResponse.json({
success: false,
message: "companyId is required for company-wide search"
}, { status: 400 });
}
if (searchScope === "document" && !documentId) {
recordResult("error");
return NextResponse.json({
success: false,
message: "documentId is required for document search"
}, { status: 400 });
}
// Verify user and permissions
const [requestingUser] = await db
.select()
.from(users)
.where(eq(users.userId, userId))
.limit(1);
if (!requestingUser) {
recordResult("error");
return NextResponse.json({
success: false,
message: "Invalid user."
}, { status: 401 });
}
const userCompanyId = requestingUser.companyId;
const numericCompanyId = userCompanyId ? Number(userCompanyId) : null;
if (numericCompanyId === null || Number.isNaN(numericCompanyId)) {
recordResult("error");
return NextResponse.json({
success: false,
message: "User is not associated with a valid company."
}, { status: 403 });
}
// Validate company-wide search permissions
if (searchScope === "company") {
if (!COMPANY_SCOPE_ROLES.has(requestingUser.role)) {
recordResult("error");
return NextResponse.json({
success: false,
message: "Only employer accounts can run company-wide searches."
}, { status: 403 });
}
if (companyId !== undefined && companyId !== numericCompanyId) {
recordResult("error");
return NextResponse.json({
success: false,
message: "Company mismatch detected for the current user."
}, { status: 403 });
}
}
// Validate document access
if (searchScope === "document" && documentId) {
const [targetDocument] = await db
.select({
id: document.id,
companyId: document.companyId
})
.from(document)
.where(eq(document.id, documentId))
.limit(1);
if (!targetDocument) {
recordResult("error");
return NextResponse.json({
success: false,
message: "Document not found."
}, { status: 404 });
}
if (targetDocument.companyId !== userCompanyId) {
recordResult("error");
return NextResponse.json({
success: false,
message: "You do not have access to this document."
}, { status: 403 });
}
}
// Perform comprehensive search
const embeddings = getEmbeddings();
let documents: SearchResult[] = [];
retrievalMethod = searchScope === "company" ? 'company_ensemble_rrf' : 'document_ensemble_rrf';
try {
if (searchScope === "company") {
const companyOptions: CompanySearchOptions = {
weights: [0.4, 0.6],
topK: 10, // More results for comprehensive search
companyId: numericCompanyId
};
documents = await companyEnsembleSearch(
question,
companyOptions,
embeddings
);
} else if (searchScope === "document" && documentId) {
const documentOptions: DocumentSearchOptions = {
weights: [0.4, 0.6],
topK: 5,
documentId
};
documents = await documentEnsembleSearch(
question,
documentOptions,
embeddings
);
} else {
throw new Error("Invalid search parameters");
}
if (documents.length === 0) {
throw new Error("No ensemble results");
}
} catch (ensembleError) {
console.warn(`⚠️ [AIChat] Ensemble search failed, falling back:`, ensembleError);
if (searchScope === "company") {
retrievalMethod = 'company_fallback_failed';
documents = [];
} else if (searchScope === "document" && documentId) {
retrievalMethod = 'ann_hybrid';
try {
const questionEmbedding = await embeddings.embedQuery(question);
const annResults = await qaAnnOptimizer.searchSimilarChunks(
questionEmbedding,
[documentId],
5,
0.8
);
documents = annResults.map(result => ({
pageContent: result.content,
metadata: {
chunkId: result.id,
page: result.page,
documentId: result.documentId,
distance: 1 - result.confidence,
source: 'ann_hybrid',
searchScope: 'document' as const,
retrievalMethod: 'ann_hybrid' as const,
timestamp: new Date().toISOString()
}
}));
} catch (annError) {
console.warn(`⚠️ [AIChat] ANN search failed, using vector search:`, annError);
retrievalMethod = 'vector_fallback';
const questionEmbedding = await embeddings.embedQuery(question);
const bracketedEmbedding = `[${questionEmbedding.join(",")}]`;
const query = sql`
SELECT
id,
content,
page,
embedding <-> ${bracketedEmbedding}::vector(1536) AS distance
FROM pdr_ai_v2_pdf_chunks
WHERE document_id = ${documentId}
ORDER BY embedding <-> ${bracketedEmbedding}::vector(1536)
LIMIT 3
`;
const result = await db.execute<PdfChunkRow>(query);
documents = result.rows.map(row => ({
pageContent: row.content,
metadata: {
chunkId: row.id,
page: row.page,
distance: row.distance,
source: 'vector_fallback',
searchScope: 'document' as const,
timestamp: new Date().toISOString()
}
}));
}
} else {
retrievalMethod = 'invalid_parameters';
documents = [];
}
}
if (documents.length === 0) {
recordResult("empty");
return NextResponse.json({
success: false,
message: "No relevant content found for the given question.",
});
}
// Build comprehensive context from retrieved documents
const combinedContent = documents
.map((doc, idx) => {
const page = doc.metadata?.page ?? 'Unknown';
const source = doc.metadata?.source ?? retrievalMethod;
const distance = doc.metadata?.distance ?? 0;
const relevanceScore = Math.round((1 - Number(distance)) * 100);
console.log(`📄 [AIChat] Document ${idx + 1}: page ${page}, source: ${source}, relevance: ${relevanceScore}%`);
return `=== Chunk #${idx + 1}, Page ${page} ===\n${doc.pageContent}`;
})
.join("\n\n");
console.log(`✅ [AIChat] Built context with pages: ${documents.map(doc => doc.metadata?.page).join(', ')}`);
// Perform comprehensive web search if enabled
const documentContext = documents.length > 0
? documents.map(doc => doc.pageContent).join('\n\n')
: undefined;
const enableWebSearchFlag = Boolean(enableWebSearch ?? false);
const webSearch = await performWebSearch(
question,
documentContext,
enableWebSearchFlag,
5
);
// Get AI model and generate comprehensive response
const selectedAiModel = (aiModel ?? 'gpt-4o') as AIModelType;
const chat = getChatModel(selectedAiModel);
const selectedStyle = (style ?? 'concise') satisfies keyof typeof SYSTEM_PROMPTS;
// Build conversation context
let conversationContext = '';
if (conversationHistory) {
conversationContext = `\n\nPrevious conversation context:\n${conversationHistory}\n\nPlease continue the conversation naturally, referencing previous exchanges when relevant.`;
}
// Build comprehensive prompts
const systemPrompt = getSystemPrompt(selectedStyle, aiPersona);
const webSearchInstruction = getWebSearchInstruction(
enableWebSearchFlag,
webSearch.results,
webSearch.refinedQuery,
webSearch.reasoning
);
const userPrompt = `User's question: "${question}"${conversationContext}\n\nRelevant document content:\n${combinedContent}${webSearch.content}${webSearchInstruction}\n\nProvide a natural, conversational answer based primarily on the provided content. When using information from web sources, cite them using [Source X] format. Address the user directly and maintain continuity with any previous conversation.`;
const response = await chat.call([
new SystemMessage(systemPrompt),
new HumanMessage(userPrompt),
]);
const summarizedAnswer = normalizeModelContent(response.content);
const totalTime = Date.now() - startTime;
// Log query to ChatHistory for analytics
try {
if (documentId) {
const [doc] = await db
.select({ title: document.title })
.from(document)
.where(eq(document.id, documentId));
if (doc) {
await db.insert(ChatHistory).values({
UserId: userId,
documentId: BigInt(documentId),
documentTitle: doc.title,
question: question,
response: summarizedAnswer,
pages: documents.map(doc => doc.metadata?.page).filter((page): page is number => page !== undefined),
queryType: "simple"
});
}
}
} catch (logError) {
console.error("Failed to log chat history:", logError);
// Don't fail the request if logging fails
}
recordResult("success");
return NextResponse.json({
success: true,
summarizedAnswer,
recommendedPages: documents.map(doc => doc.metadata?.page).filter((page): page is number => page !== undefined),
retrievalMethod,
processingTimeMs: totalTime,
chunksAnalyzed: documents.length,
fusionWeights: [0.4, 0.6],
searchScope,
aiModel: selectedAiModel,
webSources: enableWebSearchFlag ? webSearch.results : undefined,
webSearch: enableWebSearchFlag ? {
refinedQuery: webSearch.refinedQuery || question,
reasoning: webSearch.reasoning,
resultsCount: webSearch.results.length
} : undefined
});
} catch (error) {
console.error("❌ [AIChat] Error in query processing:", error);
recordResult("error");
return NextResponse.json(
{
success: false,
error: "An error occurred while processing your question.",
details: error instanceof Error ? error.message : "Unknown error"
},
{ status: 500 }
);
}
});
}