File size: 7,668 Bytes
0a56405 |
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 |
export type SearchHit = {
doc_id: string;
page_num: number;
score: number;
image_key: string;
image_url?: string | null;
width: number;
height: number;
};
export type SearchResponse = {
query: string;
results: SearchHit[];
};
export type ChatResponse = {
answer: string;
model: string;
citations: SearchHit[];
usage?: Record<string, unknown> | null;
};
export type ExportRequest = {
query: string;
top_k: number;
include_images: boolean;
hybrid: boolean;
format: "json" | "markdown";
include_snippets?: boolean;
max_snippet_chars?: number;
answer?: string | null;
};
export type ChatStreamEvent =
| { event: "citations"; data: { citations: SearchHit[] } }
| { event: "delta"; data: { text: string } }
| { event: "done"; data: { model?: string; usage?: Record<string, unknown> | null } }
| { event: "error"; data: { message: string } }
| { event: "message"; data: unknown };
const API_BASE =
process.env.NEXT_PUBLIC_API_BASE?.replace(/\/$/, "") ||
"/api";
const DEFAULT_TIMEOUT_MS = 30000;
const MAX_ERROR_CHARS = 600;
function resolvePath(path: string) {
if (path.startsWith("http://") || path.startsWith("https://")) {
return path;
}
if (!path.startsWith("/")) {
return `${API_BASE}/${path}`;
}
return `${API_BASE}${path}`;
}
export function resolveImageUrl(imageUrl?: string | null): string | null {
if (!imageUrl) return null;
if (imageUrl.startsWith("/files/")) return imageUrl;
return resolvePath(imageUrl);
}
async function postJson<T>(path: string, payload: unknown): Promise<T> {
const res = await fetchWithTimeout(resolvePath(path), {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
cache: "no-store",
});
if (!res.ok) {
const text = truncateError(await res.text());
throw new Error(`Request failed: ${res.status} ${text}`);
}
return (await res.json()) as T;
}
export async function exportEvidence(params: ExportRequest): Promise<Blob> {
const res = await fetchWithTimeout(resolvePath("/export"), {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(params),
cache: "no-store",
}, DEFAULT_TIMEOUT_MS);
if (!res.ok) {
const text = truncateError(await res.text());
throw new Error(`Export failed: ${res.status} ${text}`);
}
return await res.blob();
}
export async function runSearch(params: {
query: string;
top_k: number;
include_images: boolean;
hybrid: boolean;
}): Promise<SearchResponse> {
const response = await postJson<SearchResponse>("/search", params);
const results = Array.isArray(response.results)
? response.results
.map(normalizeHit)
.filter((item): item is SearchHit => item !== null)
: [];
return {
query: typeof response.query === "string" ? response.query : params.query,
results,
};
}
export async function runChat(params: {
query: string;
top_k: number;
include_images: boolean;
hybrid: boolean;
}): Promise<ChatResponse> {
const response = await postJson<ChatResponse>("/chat", params);
const citations = Array.isArray(response.citations)
? response.citations
.map(normalizeHit)
.filter((item): item is SearchHit => item !== null)
: [];
return {
answer: typeof response.answer === "string" ? response.answer : "",
model: typeof response.model === "string" ? response.model : "",
citations,
usage: typeof response.usage === "object" ? response.usage : null,
};
}
function parseEventBlock(block: string): { event: string; data: string } | null {
const lines = block.split(/\r?\n/);
let event = "message";
let data = "";
for (const line of lines) {
if (!line) continue;
if (line.startsWith(":") || line.startsWith("retry:") || line.startsWith("id:")) {
continue;
}
if (line.startsWith("event:")) {
event = line.replace("event:", "").trim();
continue;
}
if (line.startsWith("data:")) {
let chunk = line.slice(5);
if (chunk.startsWith(" ")) {
chunk = chunk.slice(1);
}
data += chunk;
}
}
if (!data) return null;
return { event, data };
}
export async function streamChat(
params: {
query: string;
top_k: number;
include_images: boolean;
hybrid: boolean;
},
onEvent: (event: ChatStreamEvent) => void,
signal?: AbortSignal
): Promise<void> {
const res = await fetch(resolvePath("/chat/stream"), {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "text/event-stream",
},
body: JSON.stringify(params),
cache: "no-store",
signal,
});
if (!res.ok) {
const text = truncateError(await res.text());
throw new Error(`Stream failed: ${res.status} ${text}`);
}
if (!res.body) {
throw new Error("Stream failed: response body is empty.");
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const blocks = buffer.split("\n\n");
buffer = blocks.pop() ?? "";
for (const block of blocks) {
const parsed = parseEventBlock(block);
if (!parsed) continue;
try {
const payload = JSON.parse(parsed.data);
onEvent({ event: parsed.event as ChatStreamEvent["event"], data: payload } as ChatStreamEvent);
} catch {
onEvent({ event: parsed.event as ChatStreamEvent["event"], data: parsed.data } as ChatStreamEvent);
}
}
}
if (buffer.trim()) {
const parsed = parseEventBlock(buffer);
if (parsed) {
try {
const payload = JSON.parse(parsed.data);
onEvent({ event: parsed.event as ChatStreamEvent["event"], data: payload } as ChatStreamEvent);
} catch {
onEvent({ event: parsed.event as ChatStreamEvent["event"], data: parsed.data } as ChatStreamEvent);
}
}
}
}
function truncateError(text: string): string {
if (!text) return "";
if (text.length <= MAX_ERROR_CHARS) return text;
return `${text.slice(0, MAX_ERROR_CHARS)}…`;
}
async function fetchWithTimeout(
input: RequestInfo | URL,
init: RequestInit,
timeoutMs: number = DEFAULT_TIMEOUT_MS
): Promise<Response> {
const controller = new AbortController();
if (init.signal) {
if (init.signal.aborted) {
controller.abort();
} else {
init.signal.addEventListener("abort", () => controller.abort(), { once: true });
}
}
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
return await fetch(input, {
...init,
signal: controller.signal,
});
} finally {
clearTimeout(timeout);
}
}
function normalizeHit(raw: SearchHit | null | undefined): SearchHit | null {
if (!raw || typeof raw !== "object") return null;
const docId = typeof raw.doc_id === "string" ? raw.doc_id : "";
const imageKey = typeof raw.image_key === "string" ? raw.image_key : "";
const pageNum = Number(raw.page_num);
const score = Number(raw.score);
const width = Number(raw.width);
const height = Number(raw.height);
if (!docId || !imageKey || !Number.isFinite(pageNum)) return null;
return {
doc_id: docId,
page_num: Number.isFinite(pageNum) ? pageNum : 0,
score: Number.isFinite(score) ? score : 0,
image_key: imageKey,
image_url: typeof raw.image_url === "string" ? raw.image_url : (imageKey ? `/files/${imageKey}` : null),
width: Number.isFinite(width) ? width : 0,
height: Number.isFinite(height) ? height : 0,
};
}
|