prolog_llm / src /api.js
fraudTech's picture
refactor: Simplify frontend to login + streaming chat only
e5f49d0
Raw History Blame Contribute Delete
3.03 kB
// src/api.js
export const API_BASE = "https://deepthoughtai-prolog-gateway.hf.space";
export async function login(username, password) {
const res = await fetch(`${API_BASE}/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
});
let json;
const text = await res.text().catch(() => "");
try {
json = text ? JSON.parse(text) : {};
} catch {
json = {};
}
if (!res.ok) {
throw new Error(json?.error || text || `Login failed (${res.status})`);
}
if (!json.ok || !json.token) {
throw new Error(json?.error || "Login failed");
}
return json; // { ok, token }
}
export async function streamChat(
message,
history,
token,
onToken,
sessionId = null,
onStatus = null,
onDebug = null
) {
const res = await fetch(`${API_BASE}/chat/stream`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ message, history, session_id: sessionId }),
});
if (!res.body) throw new Error("Streaming not supported");
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);
// Parse status messages: __STATUS__:{"message":"..."}__END__
const statusRe = /__STATUS__:(.*?)__END__/g;
const debugRe = /__DEBUG__:(.*?)__END__/g;
let match;
let lastIndex = 0;
while ((match = statusRe.exec(buffer)) !== null) {
if (match.index > lastIndex) {
const content = buffer.substring(lastIndex, match.index);
if (content) onToken(content);
}
try {
const data = JSON.parse(match[1]);
if (onStatus && data.message) onStatus(data.message);
} catch {}
lastIndex = statusRe.lastIndex;
}
// Parse debug markers
debugRe.lastIndex = 0;
while ((match = debugRe.exec(buffer)) !== null) {
try {
const data = JSON.parse(match[1]);
if (onDebug) onDebug(data);
buffer = buffer.substring(0, match.index) + buffer.substring(debugRe.lastIndex);
debugRe.lastIndex = match.index;
} catch {}
}
// Emit remaining content
if (lastIndex < buffer.length) {
const content = buffer.substring(lastIndex);
if (!content.includes("__STATUS__") && !content.includes("__DEBUG__")) {
onToken(content);
buffer = "";
} else {
const markerStart = Math.max(
content.lastIndexOf("__STATUS__"),
content.lastIndexOf("__DEBUG__")
);
if (markerStart > 0) {
onToken(content.substring(0, markerStart));
buffer = content.substring(markerStart);
} else {
buffer = content;
}
}
}
}
// Flush remaining
if (buffer && !buffer.includes("__STATUS__") && !buffer.includes("__DEBUG__")) {
onToken(buffer);
}
}