Hamza4100's picture
Update frontend/src/utils/api.ts
82b552c verified
/**
* 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;
}
}