Spaces:
Runtime error
Runtime error
File size: 2,009 Bytes
ad79323 | 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 | import { AppError } from "@/server/errors";
import {
RAG_REQUEST_TIMEOUT_MS,
RAG_SERVICE_SECRET,
RAG_SERVICE_URL,
} from "@/lib/constants";
type RagHistoryTurn = {
question: string;
answer: string;
};
type RagAnswerResponse = {
answer: string;
sources: Array<{
file_id: string;
file_name: string;
page_number: number | null;
score: number | null;
snippet: string;
}>;
};
async function callRagService<T>(
path: string,
body: Record<string, unknown>,
): Promise<T> {
const response = await fetch(`${RAG_SERVICE_URL}${path}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-rag-service-secret": RAG_SERVICE_SECRET,
},
body: JSON.stringify(body),
signal: AbortSignal.timeout(RAG_REQUEST_TIMEOUT_MS),
});
const payload = (await response.json().catch(() => null)) as
| { detail?: string; message?: string }
| T
| null;
if (!response.ok) {
throw new AppError(
(payload as { detail?: string; message?: string } | null)?.detail ||
(payload as { detail?: string; message?: string } | null)?.message ||
"تعذر التواصل مع خدمة الذكاء الاصطناعي.",
502,
);
}
return payload as T;
}
export async function ingestCaseFileIntoRag(params: {
ownerId: string;
caseId: string;
fileId: string;
bucket: string;
objectKey: string;
fileName: string;
}) {
return callRagService<{ indexed_chunks: number }>("/ingest", {
owner_id: params.ownerId,
case_id: params.caseId,
file_id: params.fileId,
bucket: params.bucket,
object_key: params.objectKey,
file_name: params.fileName,
});
}
export async function askCaseRagQuestion(params: {
ownerId: string;
caseId: string;
question: string;
history: RagHistoryTurn[];
}) {
return callRagService<RagAnswerResponse>("/answer", {
owner_id: params.ownerId,
case_id: params.caseId,
question: params.question,
history: params.history,
});
}
|