Spaces:
Sleeping
Sleeping
File size: 2,680 Bytes
82b552c | 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 | /**
* API Client for communicating with the backend.
* Handles streaming responses from the A2UI protocol.
*/
import { A2UIMessage } from "../types/a2ui";
const API_BASE_URL = import.meta.env.VITE_API_URL || "";
/**
* Send a message to the chat endpoint and stream A2UI events.
*
* @param message - User message to send
* @param onMessage - Callback function for each received message
* @param onError - Callback function for errors
*/
export async function streamChat(
message: string,
onMessage: (msg: A2UIMessage) => void,
onError: (error: Error) => void
): Promise<void> {
try {
const response = await fetch(`${API_BASE_URL}/chat`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ message }),
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
if (!response.body) {
throw new Error("Response body is empty");
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
const lines = chunk.split("\n");
for (const line of lines) {
if (line.startsWith("data: ")) {
try {
const jsonStr = line.slice(6);
const message: A2UIMessage = JSON.parse(jsonStr);
onMessage(message);
} catch (e) {
console.error("Failed to parse message:", e);
}
}
}
}
} catch (error) {
onError(error instanceof Error ? error : new Error(String(error)));
}
}
/**
* Check API health status.
*/
export async function checkHealth(): Promise<boolean> {
try {
const response = await fetch(`${API_BASE_URL}/health`);
return response.ok;
} catch {
return false;
}
}
/**
* Get available tools from the backend.
*/
export async function getTools(): Promise<any[]> {
try {
const response = await fetch(`${API_BASE_URL}/tools`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
return data.tools || [];
} catch (error) {
console.error("Failed to fetch tools:", error);
return [];
}
}
/**
* Clear chat history on the backend.
*/
export async function clearHistory(): Promise<boolean> {
try {
const response = await fetch(`${API_BASE_URL}/chat/history`, {
method: "DELETE",
});
return response.ok;
} catch (error) {
console.error("Failed to clear history:", error);
return false;
}
}
|