AsrorAsr's picture
Upload folder using huggingface_hub
a3ea6b0 verified
Raw
History Blame Contribute Delete
2.44 kB
const API_BASE = import.meta.env.PROD ? '/api' : 'http://localhost:8001/api';
export async function uploadDocument(file) {
const formData = new FormData();
formData.append('file', file);
const response = await fetch(`${API_BASE}/documents/upload`, {
method: 'POST',
body: formData,
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || 'Upload failed');
}
return response.json();
}
export async function listDocuments() {
const response = await fetch(`${API_BASE}/documents/`);
if (!response.ok) throw new Error('Failed to fetch documents');
return response.json();
}
export async function deleteDocument(docId) {
const response = await fetch(`${API_BASE}/documents/${docId}`, {
method: 'DELETE',
});
if (!response.ok) throw new Error('Failed to delete document');
return response.json();
}
export async function sendChatMessage(question, chatHistory, onChunk, onSources, onDone, onError) {
try {
const response = await fetch(`${API_BASE}/chat/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
question,
chat_history: chatHistory,
stream: true,
}),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || 'Chat request failed');
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6).trim();
if (data === '[DONE]') {
onDone?.();
return;
}
try {
const parsed = JSON.parse(data);
if (parsed.type === 'content') {
onChunk?.(parsed.content);
} else if (parsed.type === 'sources') {
onSources?.(parsed.sources);
} else if (parsed.type === 'error') {
onError?.(parsed.error);
}
} catch (e) {
// Skip unparseable lines
}
}
}
}
onDone?.();
} catch (error) {
onError?.(error.message);
}
}