sniro23's picture
Remove conflicting .space directory to fix API endpoint configuration
4addc11
import { useState } from 'react';
const HF_API_URL = process.env.NEXT_PUBLIC_HF_API_URL;
const HF_API_TOKEN = process.env.NEXT_PUBLIC_HF_API_TOKEN;
export interface ChatMessage {
role: 'user' | 'assistant';
content: string;
}
export interface APIResponse {
answer: string;
sources?: string[];
error?: string;
}
export async function queryAPI(input: string, history: ChatMessage[] = []): Promise<APIResponse> {
try {
if (!HF_API_URL) {
throw new Error('HF_API_URL is not configured');
}
// Convert history to Gradio's chat format: a list of [user, assistant] pairs.
const gradioHistory: [string | null, string | null][] = [];
for (let i = 0; i < history.length; i += 2) {
if (i + 1 < history.length && history[i].role === 'user' && history[i+1].role === 'assistant') {
gradioHistory.push([history[i].content, history[i+1].content]);
}
}
// Use the specific Gradio API endpoint as per the documentation
const response = await fetch(`${HF_API_URL}/run/chat`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
data: [
input,
gradioHistory
],
}),
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const result = await response.json();
return {
answer: result?.data?.[0] || 'No response received from the medical assistant.',
sources: [], // Enhanced backend provides sources within the response text
};
} catch (error) {
console.error('API Error:', error);
return {
answer: '',
error: error instanceof Error ? error.message : 'An unknown error occurred',
};
}
}
export function useChatQuery() {
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const sendMessage = async (input: string) => {
try {
setIsLoading(true);
setError(null);
// Add user message
const userMessage: ChatMessage = { role: 'user', content: input };
setMessages(prev => [...prev, userMessage]);
// Query API
const response = await queryAPI(input);
if (response.error) {
throw new Error(response.error);
}
// Add assistant message
const assistantMessage: ChatMessage = {
role: 'assistant',
content: response.answer,
};
setMessages(prev => [...prev, assistantMessage]);
} catch (err) {
setError(err instanceof Error ? err.message : 'An unknown error occurred');
} finally {
setIsLoading(false);
}
};
return {
messages,
isLoading,
error,
sendMessage,
};
}