|
| 1 | +import { ai } from "@/lib/gemini"; |
| 2 | +import { adminDb } from "@/lib/firebase-admin"; |
| 3 | + |
| 4 | +export async function POST( |
| 5 | + request: Request, |
| 6 | + { params }: { params: Promise<{ id: string }> }, |
| 7 | +) { |
| 8 | + try { |
| 9 | + const { id } = await params; |
| 10 | + const { question } = await request.json(); |
| 11 | + |
| 12 | + if (!id) { |
| 13 | + return Response.json({ error: "Report ID is required" }, { status: 400 }); |
| 14 | + } |
| 15 | + |
| 16 | + if (!question || typeof question !== "string") { |
| 17 | + return Response.json( |
| 18 | + { error: "Question is required and must be a string" }, |
| 19 | + { status: 400 }, |
| 20 | + ); |
| 21 | + } |
| 22 | + |
| 23 | + const cacheDoc = await adminDb |
| 24 | + .collection("cache") |
| 25 | + .doc(id.toLowerCase()) |
| 26 | + .get(); |
| 27 | + |
| 28 | + if (!cacheDoc.exists) { |
| 29 | + return Response.json( |
| 30 | + { error: "Report not found", id: id.toLowerCase() }, |
| 31 | + { status: 404 }, |
| 32 | + ); |
| 33 | + } |
| 34 | + |
| 35 | + const docData = cacheDoc.data(); |
| 36 | + const contextPayload = { |
| 37 | + id: cacheDoc.id, |
| 38 | + cached_at: docData?.cached_at ?? null, |
| 39 | + query: docData?.query ?? id, |
| 40 | + report: docData?.report ?? null, |
| 41 | + }; |
| 42 | + |
| 43 | + const result = await ai.models.generateContent({ |
| 44 | + model: "gemini-2.0-flash-exp", |
| 45 | + contents: [ |
| 46 | + { |
| 47 | + role: "user", |
| 48 | + parts: [ |
| 49 | + { |
| 50 | + text: `You are an expert security analyst. Rely ONLY on the context provided below when answering the user's question. |
| 51 | +If the context does not contain the requested information, reply exactly with "I don't have information about that in this report." |
| 52 | +Do not speculate, hallucinate, or reference external knowledge. Keep answers to 2-4 concise sentences and reference concrete values from the context when available. |
| 53 | +
|
| 54 | +Context (JSON): |
| 55 | +${JSON.stringify(contextPayload, null, 2)} |
| 56 | +
|
| 57 | +Question: ${question}`, |
| 58 | + }, |
| 59 | + ], |
| 60 | + }, |
| 61 | + ], |
| 62 | + }); |
| 63 | + |
| 64 | + const answer = result.text?.trim(); |
| 65 | + |
| 66 | + if (!answer) { |
| 67 | + return Response.json( |
| 68 | + { error: "The analyst could not generate an answer." }, |
| 69 | + { status: 502 }, |
| 70 | + ); |
| 71 | + } |
| 72 | + |
| 73 | + return Response.json({ |
| 74 | + answer, |
| 75 | + reportId: cacheDoc.id, |
| 76 | + question, |
| 77 | + }); |
| 78 | + } catch (error) { |
| 79 | + console.error("Error answering report question:", error); |
| 80 | + return Response.json( |
| 81 | + { |
| 82 | + error: "Internal server error", |
| 83 | + details: error instanceof Error ? error.message : "Unknown error", |
| 84 | + }, |
| 85 | + { status: 500 }, |
| 86 | + ); |
| 87 | + } |
| 88 | +} |
0 commit comments